blob: e23bb34b05cc0c23bdd740b5cb4034d26c718d1e [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
Chris Lattner4b009652007-07-25 00:24:17 +0000182 // C99 6.2.5p11.
183 FloatComplexTy = getComplexType(FloatTy);
184 DoubleComplexTy = getComplexType(DoubleTy);
185 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000186
Steve Naroff9d12c902007-10-15 14:41:52 +0000187 BuiltinVaListType = QualType();
Ted Kremenek42730c52008-01-07 19:49:32 +0000188 ObjCIdType = QualType();
Steve Naroff9d12c902007-10-15 14:41:52 +0000189 IdStructType = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +0000190 ObjCClassType = QualType();
Anders Carlsson7f23e3d2007-10-31 02:53:19 +0000191 ClassStructType = 0;
192
Ted Kremenek42730c52008-01-07 19:49:32 +0000193 ObjCConstantStringType = QualType();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +0000194
195 // void * type
196 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl5d0ead72009-05-10 18:38:11 +0000197
198 // nullptr type (C++0x 2.14.7)
199 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Chris Lattner4b009652007-07-25 00:24:17 +0000200}
201
202//===----------------------------------------------------------------------===//
203// Type Sizing and Analysis
204//===----------------------------------------------------------------------===//
205
Chris Lattner2a674dc2008-06-30 18:32:54 +0000206/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
207/// scalar floating point type.
208const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
209 const BuiltinType *BT = T->getAsBuiltinType();
210 assert(BT && "Not a floating point type!");
211 switch (BT->getKind()) {
212 default: assert(0 && "Not a floating point type!");
213 case BuiltinType::Float: return Target.getFloatFormat();
214 case BuiltinType::Double: return Target.getDoubleFormat();
215 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
216 }
217}
218
Chris Lattnerbd3153e2009-01-24 21:53:27 +0000219/// getDeclAlign - Return a conservative estimate of the alignment of the
220/// specified decl. Note that bitfields do not have a valid alignment, so
221/// this method will assert on them.
Daniel Dunbar96d1f1b2009-02-17 22:16:19 +0000222unsigned ASTContext::getDeclAlignInBytes(const Decl *D) {
Eli Friedman0ee57322009-02-22 02:56:25 +0000223 unsigned Align = Target.getCharWidth();
224
Douglas Gregor98da6ae2009-06-18 16:11:24 +0000225 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>(*this))
Eli Friedman0ee57322009-02-22 02:56:25 +0000226 Align = std::max(Align, AA->getAlignment());
227
Chris Lattnerbd3153e2009-01-24 21:53:27 +0000228 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
229 QualType T = VD->getType();
Anders Carlssonaa0783b2009-04-10 04:47:03 +0000230 if (const ReferenceType* RT = T->getAsReferenceType()) {
231 unsigned AS = RT->getPointeeType().getAddressSpace();
Anders Carlssoneeaeda32009-04-10 04:52:36 +0000232 Align = Target.getPointerAlign(AS);
Anders Carlssonaa0783b2009-04-10 04:47:03 +0000233 } else if (!T->isIncompleteType() && !T->isFunctionType()) {
234 // Incomplete or function types default to 1.
Eli Friedman0ee57322009-02-22 02:56:25 +0000235 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
236 T = cast<ArrayType>(T)->getElementType();
237
238 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
239 }
Chris Lattnerbd3153e2009-01-24 21:53:27 +0000240 }
Eli Friedman0ee57322009-02-22 02:56:25 +0000241
242 return Align / Target.getCharWidth();
Chris Lattnerbd3153e2009-01-24 21:53:27 +0000243}
Chris Lattner2a674dc2008-06-30 18:32:54 +0000244
Chris Lattner4b009652007-07-25 00:24:17 +0000245/// getTypeSize - Return the size of the specified type, in bits. This method
246/// does not work on incomplete types.
247std::pair<uint64_t, unsigned>
Daniel Dunbar7d6a5d22008-11-08 05:48:37 +0000248ASTContext::getTypeInfo(const Type *T) {
Mike Stump44d1f402009-02-27 18:32:39 +0000249 uint64_t Width=0;
250 unsigned Align=8;
Chris Lattner4b009652007-07-25 00:24:17 +0000251 switch (T->getTypeClass()) {
Douglas Gregor4fa58902009-02-26 23:50:07 +0000252#define TYPE(Class, Base)
253#define ABSTRACT_TYPE(Class, Base)
Douglas Gregorab380272009-04-30 17:32:17 +0000254#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor4fa58902009-02-26 23:50:07 +0000255#define DEPENDENT_TYPE(Class, Base) case Type::Class:
256#include "clang/AST/TypeNodes.def"
Douglas Gregorab380272009-04-30 17:32:17 +0000257 assert(false && "Should not see dependent types");
Douglas Gregor4fa58902009-02-26 23:50:07 +0000258 break;
259
Chris Lattner4b009652007-07-25 00:24:17 +0000260 case Type::FunctionNoProto:
261 case Type::FunctionProto:
Douglas Gregorab380272009-04-30 17:32:17 +0000262 // GCC extension: alignof(function) = 32 bits
263 Width = 0;
264 Align = 32;
265 break;
266
Douglas Gregor4fa58902009-02-26 23:50:07 +0000267 case Type::IncompleteArray:
Steve Naroff83c13012007-08-30 01:06:46 +0000268 case Type::VariableArray:
Douglas Gregorab380272009-04-30 17:32:17 +0000269 Width = 0;
270 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
271 break;
272
Steve Naroff83c13012007-08-30 01:06:46 +0000273 case Type::ConstantArray: {
Daniel Dunbar7d6a5d22008-11-08 05:48:37 +0000274 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Steve Naroff83c13012007-08-30 01:06:46 +0000275
Chris Lattner8cd0e932008-03-05 18:54:05 +0000276 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000277 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner4b009652007-07-25 00:24:17 +0000278 Align = EltInfo.second;
279 break;
Christopher Lamb82c758b2007-12-29 05:10:55 +0000280 }
Nate Begemanaf6ed502008-04-18 23:10:10 +0000281 case Type::ExtVector:
Chris Lattner4b009652007-07-25 00:24:17 +0000282 case Type::Vector: {
283 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner8cd0e932008-03-05 18:54:05 +0000284 getTypeInfo(cast<VectorType>(T)->getElementType());
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000285 Width = EltInfo.first*cast<VectorType>(T)->getNumElements();
Eli Friedman5949a022008-05-30 09:31:38 +0000286 Align = Width;
Nate Begeman7903d052009-01-18 06:42:49 +0000287 // If the alignment is not a power of 2, round up to the next power of 2.
288 // This happens for non-power-of-2 length vectors.
289 // FIXME: this should probably be a target property.
290 Align = 1 << llvm::Log2_32_Ceil(Align);
Chris Lattner4b009652007-07-25 00:24:17 +0000291 break;
292 }
293
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000294 case Type::Builtin:
Chris Lattner4b009652007-07-25 00:24:17 +0000295 switch (cast<BuiltinType>(T)->getKind()) {
296 default: assert(0 && "Unknown builtin type!");
297 case BuiltinType::Void:
Douglas Gregorab380272009-04-30 17:32:17 +0000298 // GCC extension: alignof(void) = 8 bits.
299 Width = 0;
300 Align = 8;
301 break;
302
Chris Lattnerb66237b2007-12-19 19:23:28 +0000303 case BuiltinType::Bool:
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000304 Width = Target.getBoolWidth();
305 Align = Target.getBoolAlign();
Chris Lattnerb66237b2007-12-19 19:23:28 +0000306 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000307 case BuiltinType::Char_S:
308 case BuiltinType::Char_U:
309 case BuiltinType::UChar:
Chris Lattnerb66237b2007-12-19 19:23:28 +0000310 case BuiltinType::SChar:
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000311 Width = Target.getCharWidth();
312 Align = Target.getCharAlign();
Chris Lattnerb66237b2007-12-19 19:23:28 +0000313 break;
Argiris Kirtzidis1ed03e72008-08-09 16:51:54 +0000314 case BuiltinType::WChar:
315 Width = Target.getWCharWidth();
316 Align = Target.getWCharAlign();
317 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000318 case BuiltinType::UShort:
Chris Lattnerb66237b2007-12-19 19:23:28 +0000319 case BuiltinType::Short:
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000320 Width = Target.getShortWidth();
321 Align = Target.getShortAlign();
Chris Lattnerb66237b2007-12-19 19:23:28 +0000322 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000323 case BuiltinType::UInt:
Chris Lattnerb66237b2007-12-19 19:23:28 +0000324 case BuiltinType::Int:
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000325 Width = Target.getIntWidth();
326 Align = Target.getIntAlign();
Chris Lattnerb66237b2007-12-19 19:23:28 +0000327 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000328 case BuiltinType::ULong:
Chris Lattnerb66237b2007-12-19 19:23:28 +0000329 case BuiltinType::Long:
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000330 Width = Target.getLongWidth();
331 Align = Target.getLongAlign();
Chris Lattnerb66237b2007-12-19 19:23:28 +0000332 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000333 case BuiltinType::ULongLong:
Chris Lattnerb66237b2007-12-19 19:23:28 +0000334 case BuiltinType::LongLong:
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000335 Width = Target.getLongLongWidth();
336 Align = Target.getLongLongAlign();
Chris Lattnerb66237b2007-12-19 19:23:28 +0000337 break;
Chris Lattner4b11cc22009-04-30 02:55:13 +0000338 case BuiltinType::Int128:
339 case BuiltinType::UInt128:
340 Width = 128;
341 Align = 128; // int128_t is 128-bit aligned on all targets.
342 break;
Chris Lattnerb66237b2007-12-19 19:23:28 +0000343 case BuiltinType::Float:
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000344 Width = Target.getFloatWidth();
345 Align = Target.getFloatAlign();
Chris Lattnerb66237b2007-12-19 19:23:28 +0000346 break;
347 case BuiltinType::Double:
Chris Lattner1d78a862008-04-07 07:01:58 +0000348 Width = Target.getDoubleWidth();
349 Align = Target.getDoubleAlign();
Chris Lattnerb66237b2007-12-19 19:23:28 +0000350 break;
351 case BuiltinType::LongDouble:
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000352 Width = Target.getLongDoubleWidth();
353 Align = Target.getLongDoubleAlign();
Chris Lattnerb66237b2007-12-19 19:23:28 +0000354 break;
Sebastian Redl5d0ead72009-05-10 18:38:11 +0000355 case BuiltinType::NullPtr:
356 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
357 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redlc4cce782009-05-27 19:34:06 +0000358 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000359 }
360 break;
Eli Friedmanff3fcdf2009-02-13 02:31:07 +0000361 case Type::FixedWidthInt:
362 // FIXME: This isn't precisely correct; the width/alignment should depend
363 // on the available types for the target
364 Width = cast<FixedWidthIntType>(T)->getWidth();
Chris Lattnere9174982009-02-15 21:20:13 +0000365 Width = std::max(llvm::NextPowerOf2(Width - 1), (uint64_t)8);
Eli Friedmanff3fcdf2009-02-13 02:31:07 +0000366 Align = Width;
367 break;
Fariborz Jahanianb60352a2009-02-17 18:27:45 +0000368 case Type::ExtQual:
Chris Lattner8cd0e932008-03-05 18:54:05 +0000369 // FIXME: Pointers into different addr spaces could have different sizes and
370 // alignment requirements: getPointerInfo should take an AddrSpace.
Fariborz Jahanianb60352a2009-02-17 18:27:45 +0000371 return getTypeInfo(QualType(cast<ExtQualType>(T)->getBaseType(), 0));
Steve Naroffc75c1a82009-06-17 22:40:22 +0000372 case Type::ObjCObjectPointer:
Douglas Gregor4fa58902009-02-26 23:50:07 +0000373 case Type::ObjCQualifiedInterface:
Chris Lattner1d78a862008-04-07 07:01:58 +0000374 Width = Target.getPointerWidth(0);
Chris Lattner461a6c52008-03-08 08:34:58 +0000375 Align = Target.getPointerAlign(0);
Chris Lattnerb66237b2007-12-19 19:23:28 +0000376 break;
Steve Naroff62f09f52008-09-24 15:05:44 +0000377 case Type::BlockPointer: {
378 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
379 Width = Target.getPointerWidth(AS);
380 Align = Target.getPointerAlign(AS);
381 break;
382 }
Chris Lattner461a6c52008-03-08 08:34:58 +0000383 case Type::Pointer: {
384 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner1d78a862008-04-07 07:01:58 +0000385 Width = Target.getPointerWidth(AS);
Chris Lattner461a6c52008-03-08 08:34:58 +0000386 Align = Target.getPointerAlign(AS);
387 break;
388 }
Sebastian Redlce6fff02009-03-16 23:22:08 +0000389 case Type::LValueReference:
390 case Type::RValueReference:
Chris Lattner4b009652007-07-25 00:24:17 +0000391 // "When applied to a reference or a reference type, the result is the size
392 // of the referenced type." C++98 5.3.3p2: expr.sizeof.
Chris Lattnerb66237b2007-12-19 19:23:28 +0000393 // FIXME: This is wrong for struct layout: a reference in a struct has
394 // pointer size.
Chris Lattnercfac88d2008-04-02 17:35:06 +0000395 return getTypeInfo(cast<ReferenceType>(T)->getPointeeType());
Sebastian Redl75555032009-01-24 21:16:55 +0000396 case Type::MemberPointer: {
Anders Carlsson86cf4ac2009-05-17 02:06:04 +0000397 // FIXME: This is ABI dependent. We use the Itanium C++ ABI.
398 // http://www.codesourcery.com/public/cxx-abi/abi.html#member-pointers
399 // If we ever want to support other ABIs this needs to be abstracted.
400
Sebastian Redl75555032009-01-24 21:16:55 +0000401 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
Anders Carlsson86cf4ac2009-05-17 02:06:04 +0000402 std::pair<uint64_t, unsigned> PtrDiffInfo =
403 getTypeInfo(getPointerDiffType());
404 Width = PtrDiffInfo.first;
Sebastian Redl75555032009-01-24 21:16:55 +0000405 if (Pointee->isFunctionType())
406 Width *= 2;
Anders Carlsson86cf4ac2009-05-17 02:06:04 +0000407 Align = PtrDiffInfo.second;
408 break;
Sebastian Redl75555032009-01-24 21:16:55 +0000409 }
Chris Lattner4b009652007-07-25 00:24:17 +0000410 case Type::Complex: {
411 // Complex types have the same alignment as their elements, but twice the
412 // size.
413 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner8cd0e932008-03-05 18:54:05 +0000414 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000415 Width = EltInfo.first*2;
Chris Lattner4b009652007-07-25 00:24:17 +0000416 Align = EltInfo.second;
417 break;
418 }
Devang Patel4b6bf702008-06-04 21:54:36 +0000419 case Type::ObjCInterface: {
Daniel Dunbar7d6a5d22008-11-08 05:48:37 +0000420 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel4b6bf702008-06-04 21:54:36 +0000421 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
422 Width = Layout.getSize();
423 Align = Layout.getAlignment();
424 break;
425 }
Douglas Gregor4fa58902009-02-26 23:50:07 +0000426 case Type::Record:
Douglas Gregor4fa58902009-02-26 23:50:07 +0000427 case Type::Enum: {
Daniel Dunbar7d6a5d22008-11-08 05:48:37 +0000428 const TagType *TT = cast<TagType>(T);
429
430 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattnerfd799692008-08-09 21:35:13 +0000431 Width = 1;
432 Align = 1;
433 break;
434 }
435
Daniel Dunbar7d6a5d22008-11-08 05:48:37 +0000436 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner2bf1d6c2008-04-06 22:05:18 +0000437 return getTypeInfo(ET->getDecl()->getIntegerType());
438
Daniel Dunbar7d6a5d22008-11-08 05:48:37 +0000439 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner2bf1d6c2008-04-06 22:05:18 +0000440 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
441 Width = Layout.getSize();
442 Align = Layout.getAlignment();
Chris Lattner4b009652007-07-25 00:24:17 +0000443 break;
444 }
Douglas Gregordd13e842009-03-30 22:58:21 +0000445
Douglas Gregorab380272009-04-30 17:32:17 +0000446 case Type::Typedef: {
447 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregor98da6ae2009-06-18 16:11:24 +0000448 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>(*this)) {
Douglas Gregorab380272009-04-30 17:32:17 +0000449 Align = Aligned->getAlignment();
450 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
451 } else
452 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregordd13e842009-03-30 22:58:21 +0000453 break;
Chris Lattner2bf1d6c2008-04-06 22:05:18 +0000454 }
Douglas Gregorab380272009-04-30 17:32:17 +0000455
456 case Type::TypeOfExpr:
457 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
458 .getTypePtr());
459
460 case Type::TypeOf:
461 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
462
Anders Carlsson93ab5332009-06-24 19:06:50 +0000463 case Type::Decltype:
464 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
465 .getTypePtr());
466
Douglas Gregorab380272009-04-30 17:32:17 +0000467 case Type::QualifiedName:
468 return getTypeInfo(cast<QualifiedNameType>(T)->getNamedType().getTypePtr());
469
470 case Type::TemplateSpecialization:
471 assert(getCanonicalType(T) != T &&
472 "Cannot request the size of a dependent type");
473 // FIXME: this is likely to be wrong once we support template
474 // aliases, since a template alias could refer to a typedef that
475 // has an __aligned__ attribute on it.
476 return getTypeInfo(getCanonicalType(T));
477 }
Chris Lattner4b009652007-07-25 00:24:17 +0000478
479 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000480 return std::make_pair(Width, Align);
Chris Lattner4b009652007-07-25 00:24:17 +0000481}
482
Chris Lattner83165b52009-01-27 18:08:34 +0000483/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
484/// type for the current target in bits. This can be different than the ABI
485/// alignment in cases where it is beneficial for performance to overalign
486/// a data type.
487unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
488 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman66c9edf2009-05-25 21:27:19 +0000489
490 // Double and long long should be naturally aligned if possible.
491 if (const ComplexType* CT = T->getAsComplexType())
492 T = CT->getElementType().getTypePtr();
493 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
494 T->isSpecificBuiltinType(BuiltinType::LongLong))
495 return std::max(ABIAlign, (unsigned)getTypeSize(T));
496
Chris Lattner83165b52009-01-27 18:08:34 +0000497 return ABIAlign;
498}
499
500
Devang Patelbfe323c2008-06-04 21:22:16 +0000501/// LayoutField - Field layout.
502void ASTRecordLayout::LayoutField(const FieldDecl *FD, unsigned FieldNo,
Daniel Dunbar2cb762f2008-10-16 02:34:03 +0000503 bool IsUnion, unsigned StructPacking,
Devang Patelbfe323c2008-06-04 21:22:16 +0000504 ASTContext &Context) {
Daniel Dunbar2cb762f2008-10-16 02:34:03 +0000505 unsigned FieldPacking = StructPacking;
Devang Patelbfe323c2008-06-04 21:22:16 +0000506 uint64_t FieldOffset = IsUnion ? 0 : Size;
507 uint64_t FieldSize;
508 unsigned FieldAlign;
Daniel Dunbar2cb762f2008-10-16 02:34:03 +0000509
510 // FIXME: Should this override struct packing? Probably we want to
511 // take the minimum?
Douglas Gregor98da6ae2009-06-18 16:11:24 +0000512 if (const PackedAttr *PA = FD->getAttr<PackedAttr>(Context))
Daniel Dunbar2cb762f2008-10-16 02:34:03 +0000513 FieldPacking = PA->getAlignment();
Devang Patelbfe323c2008-06-04 21:22:16 +0000514
515 if (const Expr *BitWidthExpr = FD->getBitWidth()) {
516 // TODO: Need to check this algorithm on other targets!
517 // (tested on Linux-X86)
Eli Friedman5255e7a2009-04-26 19:19:15 +0000518 FieldSize = BitWidthExpr->EvaluateAsInt(Context).getZExtValue();
Devang Patelbfe323c2008-06-04 21:22:16 +0000519
520 std::pair<uint64_t, unsigned> FieldInfo =
521 Context.getTypeInfo(FD->getType());
522 uint64_t TypeSize = FieldInfo.first;
523
Daniel Dunbar2cb762f2008-10-16 02:34:03 +0000524 // Determine the alignment of this bitfield. The packing
525 // attributes define a maximum and the alignment attribute defines
526 // a minimum.
527 // FIXME: What is the right behavior when the specified alignment
528 // is smaller than the specified packing?
Devang Patelbfe323c2008-06-04 21:22:16 +0000529 FieldAlign = FieldInfo.second;
Daniel Dunbar2cb762f2008-10-16 02:34:03 +0000530 if (FieldPacking)
531 FieldAlign = std::min(FieldAlign, FieldPacking);
Douglas Gregor98da6ae2009-06-18 16:11:24 +0000532 if (const AlignedAttr *AA = FD->getAttr<AlignedAttr>(Context))
Devang Patelbfe323c2008-06-04 21:22:16 +0000533 FieldAlign = std::max(FieldAlign, AA->getAlignment());
534
535 // Check if we need to add padding to give the field the correct
536 // alignment.
537 if (FieldSize == 0 || (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize)
538 FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1);
539
540 // Padding members don't affect overall alignment
541 if (!FD->getIdentifier())
542 FieldAlign = 1;
543 } else {
Chris Lattnerfd799692008-08-09 21:35:13 +0000544 if (FD->getType()->isIncompleteArrayType()) {
545 // This is a flexible array member; we can't directly
Devang Patelbfe323c2008-06-04 21:22:16 +0000546 // query getTypeInfo about these, so we figure it out here.
547 // Flexible array members don't have any size, but they
548 // have to be aligned appropriately for their element type.
549 FieldSize = 0;
Chris Lattnera1923f62008-08-04 07:31:14 +0000550 const ArrayType* ATy = Context.getAsArrayType(FD->getType());
Devang Patelbfe323c2008-06-04 21:22:16 +0000551 FieldAlign = Context.getTypeAlign(ATy->getElementType());
Anders Carlsson0843ea52009-04-10 05:31:15 +0000552 } else if (const ReferenceType *RT = FD->getType()->getAsReferenceType()) {
553 unsigned AS = RT->getPointeeType().getAddressSpace();
554 FieldSize = Context.Target.getPointerWidth(AS);
555 FieldAlign = Context.Target.getPointerAlign(AS);
Devang Patelbfe323c2008-06-04 21:22:16 +0000556 } else {
557 std::pair<uint64_t, unsigned> FieldInfo =
558 Context.getTypeInfo(FD->getType());
559 FieldSize = FieldInfo.first;
560 FieldAlign = FieldInfo.second;
561 }
562
Daniel Dunbar2cb762f2008-10-16 02:34:03 +0000563 // Determine the alignment of this bitfield. The packing
564 // attributes define a maximum and the alignment attribute defines
565 // a minimum. Additionally, the packing alignment must be at least
566 // a byte for non-bitfields.
567 //
568 // FIXME: What is the right behavior when the specified alignment
569 // is smaller than the specified packing?
570 if (FieldPacking)
571 FieldAlign = std::min(FieldAlign, std::max(8U, FieldPacking));
Douglas Gregor98da6ae2009-06-18 16:11:24 +0000572 if (const AlignedAttr *AA = FD->getAttr<AlignedAttr>(Context))
Devang Patelbfe323c2008-06-04 21:22:16 +0000573 FieldAlign = std::max(FieldAlign, AA->getAlignment());
574
575 // Round up the current record size to the field's alignment boundary.
576 FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1);
577 }
578
579 // Place this field at the current location.
580 FieldOffsets[FieldNo] = FieldOffset;
581
582 // Reserve space for this field.
583 if (IsUnion) {
584 Size = std::max(Size, FieldSize);
585 } else {
586 Size = FieldOffset + FieldSize;
587 }
588
Daniel Dunbar5523e862009-05-04 05:16:21 +0000589 // Remember the next available offset.
590 NextOffset = Size;
591
Devang Patelbfe323c2008-06-04 21:22:16 +0000592 // Remember max struct/class alignment.
593 Alignment = std::max(Alignment, FieldAlign);
594}
595
Daniel Dunbar1af336e2009-04-22 17:43:55 +0000596static void CollectLocalObjCIvars(ASTContext *Ctx,
597 const ObjCInterfaceDecl *OI,
598 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahanian0556b152008-12-17 21:40:49 +0000599 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
600 E = OI->ivar_end(); I != E; ++I) {
Chris Lattner9329cf52009-03-31 08:48:01 +0000601 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahanian0556b152008-12-17 21:40:49 +0000602 if (!IVDecl->isInvalidDecl())
603 Fields.push_back(cast<FieldDecl>(IVDecl));
604 }
605}
606
Daniel Dunbar1af336e2009-04-22 17:43:55 +0000607void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
608 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
609 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
610 CollectObjCIvars(SuperClass, Fields);
611 CollectLocalObjCIvars(this, OI, Fields);
612}
613
Fariborz Jahanianb290be02009-06-04 01:19:09 +0000614/// ShallowCollectObjCIvars -
615/// Collect all ivars, including those synthesized, in the current class.
616///
617void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
618 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars,
619 bool CollectSynthesized) {
620 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
621 E = OI->ivar_end(); I != E; ++I) {
622 Ivars.push_back(*I);
623 }
624 if (CollectSynthesized)
625 CollectSynthesizedIvars(OI, Ivars);
626}
627
Fariborz Jahanian02ebfa82009-05-12 18:14:29 +0000628void ASTContext::CollectProtocolSynthesizedIvars(const ObjCProtocolDecl *PD,
629 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
630 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(*this),
631 E = PD->prop_end(*this); I != E; ++I)
632 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
633 Ivars.push_back(Ivar);
634
635 // Also look into nested protocols.
636 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
637 E = PD->protocol_end(); P != E; ++P)
638 CollectProtocolSynthesizedIvars(*P, Ivars);
639}
640
641/// CollectSynthesizedIvars -
642/// This routine collect synthesized ivars for the designated class.
643///
644void ASTContext::CollectSynthesizedIvars(const ObjCInterfaceDecl *OI,
645 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
646 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(*this),
647 E = OI->prop_end(*this); I != E; ++I) {
648 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
649 Ivars.push_back(Ivar);
650 }
651 // Also look into interface's protocol list for properties declared
652 // in the protocol and whose ivars are synthesized.
653 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
654 PE = OI->protocol_end(); P != PE; ++P) {
655 ObjCProtocolDecl *PD = (*P);
656 CollectProtocolSynthesizedIvars(PD, Ivars);
657 }
658}
659
Fariborz Jahanianb290be02009-06-04 01:19:09 +0000660unsigned ASTContext::CountProtocolSynthesizedIvars(const ObjCProtocolDecl *PD) {
661 unsigned count = 0;
662 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(*this),
663 E = PD->prop_end(*this); I != E; ++I)
664 if ((*I)->getPropertyIvarDecl())
665 ++count;
666
667 // Also look into nested protocols.
668 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
669 E = PD->protocol_end(); P != E; ++P)
670 count += CountProtocolSynthesizedIvars(*P);
671 return count;
672}
673
674unsigned ASTContext::CountSynthesizedIvars(const ObjCInterfaceDecl *OI)
675{
676 unsigned count = 0;
677 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(*this),
678 E = OI->prop_end(*this); I != E; ++I) {
679 if ((*I)->getPropertyIvarDecl())
680 ++count;
681 }
682 // Also look into interface's protocol list for properties declared
683 // in the protocol and whose ivars are synthesized.
684 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
685 PE = OI->protocol_end(); P != PE; ++P) {
686 ObjCProtocolDecl *PD = (*P);
687 count += CountProtocolSynthesizedIvars(PD);
688 }
689 return count;
690}
691
Daniel Dunbar1fbaef12009-05-03 10:38:35 +0000692/// getInterfaceLayoutImpl - Get or compute information about the
693/// layout of the given interface.
694///
695/// \param Impl - If given, also include the layout of the interface's
696/// implementation. This may differ by including synthesized ivars.
Devang Patel4b6bf702008-06-04 21:54:36 +0000697const ASTRecordLayout &
Daniel Dunbar1fbaef12009-05-03 10:38:35 +0000698ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
699 const ObjCImplementationDecl *Impl) {
Daniel Dunbar94d2ede2009-05-03 13:15:50 +0000700 assert(!D->isForwardDecl() && "Invalid interface decl!");
701
Devang Patel4b6bf702008-06-04 21:54:36 +0000702 // Look up this layout, if already laid out, return what we have.
Daniel Dunbarb3170af2009-05-03 11:41:43 +0000703 ObjCContainerDecl *Key =
704 Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
705 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
706 return *Entry;
Devang Patel4b6bf702008-06-04 21:54:36 +0000707
Daniel Dunbar5b9332f2009-05-03 11:16:44 +0000708 unsigned FieldCount = D->ivar_size();
709 // Add in synthesized ivar count if laying out an implementation.
710 if (Impl) {
Fariborz Jahanianb290be02009-06-04 01:19:09 +0000711 unsigned SynthCount = CountSynthesizedIvars(D);
712 FieldCount += SynthCount;
Daniel Dunbarb3170af2009-05-03 11:41:43 +0000713 // If there aren't any sythesized ivars then reuse the interface
Daniel Dunbar5b9332f2009-05-03 11:16:44 +0000714 // entry. Note we can't cache this because we simply free all
715 // entries later; however we shouldn't look up implementations
716 // frequently.
Fariborz Jahanianb290be02009-06-04 01:19:09 +0000717 if (SynthCount == 0)
Daniel Dunbar5b9332f2009-05-03 11:16:44 +0000718 return getObjCLayout(D, 0);
719 }
720
Devang Patel8682d882008-06-06 02:14:01 +0000721 ASTRecordLayout *NewEntry = NULL;
Devang Patel8682d882008-06-06 02:14:01 +0000722 if (ObjCInterfaceDecl *SD = D->getSuperClass()) {
Devang Patel8682d882008-06-06 02:14:01 +0000723 const ASTRecordLayout &SL = getASTObjCInterfaceLayout(SD);
724 unsigned Alignment = SL.getAlignment();
Daniel Dunbarb3170af2009-05-03 11:41:43 +0000725
Daniel Dunbarb5dc2942009-05-07 21:58:26 +0000726 // We start laying out ivars not at the end of the superclass
727 // structure, but at the next byte following the last field.
728 uint64_t Size = llvm::RoundUpToAlignment(SL.NextOffset, 8);
Daniel Dunbar5523e862009-05-04 05:16:21 +0000729
Daniel Dunbarb3170af2009-05-03 11:41:43 +0000730 ObjCLayouts[Key] = NewEntry = new ASTRecordLayout(Size, Alignment);
Devang Patel8682d882008-06-06 02:14:01 +0000731 NewEntry->InitializeLayout(FieldCount);
Devang Patel8682d882008-06-06 02:14:01 +0000732 } else {
Daniel Dunbarb3170af2009-05-03 11:41:43 +0000733 ObjCLayouts[Key] = NewEntry = new ASTRecordLayout();
Devang Patel8682d882008-06-06 02:14:01 +0000734 NewEntry->InitializeLayout(FieldCount);
735 }
Devang Patel4b6bf702008-06-04 21:54:36 +0000736
Daniel Dunbar2cb762f2008-10-16 02:34:03 +0000737 unsigned StructPacking = 0;
Douglas Gregor98da6ae2009-06-18 16:11:24 +0000738 if (const PackedAttr *PA = D->getAttr<PackedAttr>(*this))
Daniel Dunbar2cb762f2008-10-16 02:34:03 +0000739 StructPacking = PA->getAlignment();
Devang Patel4b6bf702008-06-04 21:54:36 +0000740
Douglas Gregor98da6ae2009-06-18 16:11:24 +0000741 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>(*this))
Devang Patel4b6bf702008-06-04 21:54:36 +0000742 NewEntry->SetAlignment(std::max(NewEntry->getAlignment(),
743 AA->getAlignment()));
744
745 // Layout each ivar sequentially.
746 unsigned i = 0;
Fariborz Jahanianb290be02009-06-04 01:19:09 +0000747 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
748 ShallowCollectObjCIvars(D, Ivars, Impl);
749 for (unsigned k = 0, e = Ivars.size(); k != e; ++k)
750 NewEntry->LayoutField(Ivars[k], i++, false, StructPacking, *this);
751
Devang Patel4b6bf702008-06-04 21:54:36 +0000752 // Finally, round the size of the total struct up to the alignment of the
753 // struct itself.
754 NewEntry->FinalizeLayout();
755 return *NewEntry;
756}
757
Daniel Dunbar1fbaef12009-05-03 10:38:35 +0000758const ASTRecordLayout &
759ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
760 return getObjCLayout(D, 0);
761}
762
763const ASTRecordLayout &
764ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
765 return getObjCLayout(D->getClassInterface(), D);
766}
767
Devang Patel7a78e432007-11-01 19:11:01 +0000768/// getASTRecordLayout - Get or compute information about the layout of the
Chris Lattner4b009652007-07-25 00:24:17 +0000769/// specified record (struct/union/class), which indicates its size and field
770/// position information.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000771const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
Ted Kremenek46a837c2008-09-05 17:16:31 +0000772 D = D->getDefinition(*this);
773 assert(D && "Cannot get layout of forward declarations!");
Eli Friedman5949a022008-05-30 09:31:38 +0000774
Chris Lattner4b009652007-07-25 00:24:17 +0000775 // Look up this layout, if already laid out, return what we have.
Devang Patel7a78e432007-11-01 19:11:01 +0000776 const ASTRecordLayout *&Entry = ASTRecordLayouts[D];
Chris Lattner4b009652007-07-25 00:24:17 +0000777 if (Entry) return *Entry;
Eli Friedman5949a022008-05-30 09:31:38 +0000778
Devang Patel7a78e432007-11-01 19:11:01 +0000779 // Allocate and assign into ASTRecordLayouts here. The "Entry" reference can
780 // be invalidated (dangle) if the ASTRecordLayouts hashtable is inserted into.
781 ASTRecordLayout *NewEntry = new ASTRecordLayout();
Chris Lattner4b009652007-07-25 00:24:17 +0000782 Entry = NewEntry;
Eli Friedman5949a022008-05-30 09:31:38 +0000783
Douglas Gregor39677622008-12-11 20:41:00 +0000784 // FIXME: Avoid linear walk through the fields, if possible.
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000785 NewEntry->InitializeLayout(std::distance(D->field_begin(*this),
786 D->field_end(*this)));
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +0000787 bool IsUnion = D->isUnion();
Chris Lattner4b009652007-07-25 00:24:17 +0000788
Daniel Dunbar2cb762f2008-10-16 02:34:03 +0000789 unsigned StructPacking = 0;
Douglas Gregor98da6ae2009-06-18 16:11:24 +0000790 if (const PackedAttr *PA = D->getAttr<PackedAttr>(*this))
Daniel Dunbar2cb762f2008-10-16 02:34:03 +0000791 StructPacking = PA->getAlignment();
792
Douglas Gregor98da6ae2009-06-18 16:11:24 +0000793 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>(*this))
Devang Patelbfe323c2008-06-04 21:22:16 +0000794 NewEntry->SetAlignment(std::max(NewEntry->getAlignment(),
795 AA->getAlignment()));
Anders Carlsson058237f2008-02-18 07:13:09 +0000796
Eli Friedman5949a022008-05-30 09:31:38 +0000797 // Layout each field, for now, just sequentially, respecting alignment. In
798 // the future, this will need to be tweakable by targets.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000799 unsigned FieldIdx = 0;
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000800 for (RecordDecl::field_iterator Field = D->field_begin(*this),
801 FieldEnd = D->field_end(*this);
Douglas Gregor8acb7272008-12-11 16:49:14 +0000802 Field != FieldEnd; (void)++Field, ++FieldIdx)
803 NewEntry->LayoutField(*Field, FieldIdx, IsUnion, StructPacking, *this);
Eli Friedman5949a022008-05-30 09:31:38 +0000804
805 // Finally, round the size of the total struct up to the alignment of the
806 // struct itself.
Sebastian Redlc4cce782009-05-27 19:34:06 +0000807 NewEntry->FinalizeLayout(getLangOptions().CPlusPlus);
Chris Lattner4b009652007-07-25 00:24:17 +0000808 return *NewEntry;
809}
810
Chris Lattner4b009652007-07-25 00:24:17 +0000811//===----------------------------------------------------------------------===//
812// Type creation/memoization methods
813//===----------------------------------------------------------------------===//
814
Fariborz Jahanianb60352a2009-02-17 18:27:45 +0000815QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +0000816 QualType CanT = getCanonicalType(T);
817 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner35fef522008-02-20 20:55:12 +0000818 return T;
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000819
820 // If we are composing extended qualifiers together, merge together into one
821 // ExtQualType node.
822 unsigned CVRQuals = T.getCVRQualifiers();
823 QualType::GCAttrTypes GCAttr = QualType::GCNone;
824 Type *TypeNode = T.getTypePtr();
Chris Lattner35fef522008-02-20 20:55:12 +0000825
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000826 if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
827 // If this type already has an address space specified, it cannot get
828 // another one.
829 assert(EQT->getAddressSpace() == 0 &&
830 "Type cannot be in multiple addr spaces!");
831 GCAttr = EQT->getObjCGCAttr();
832 TypeNode = EQT->getBaseType();
833 }
Chris Lattner35fef522008-02-20 20:55:12 +0000834
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000835 // Check if we've already instantiated this type.
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000836 llvm::FoldingSetNodeID ID;
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000837 ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000838 void *InsertPos = 0;
Fariborz Jahanianb60352a2009-02-17 18:27:45 +0000839 if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000840 return QualType(EXTQy, CVRQuals);
841
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000842 // If the base type isn't canonical, this won't be a canonical type either,
843 // so fill in the canonical type field.
844 QualType Canonical;
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000845 if (!TypeNode->isCanonical()) {
Fariborz Jahanianb60352a2009-02-17 18:27:45 +0000846 Canonical = getAddrSpaceQualType(CanT, AddressSpace);
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000847
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000848 // Update InsertPos, the previous call could have invalidated it.
Fariborz Jahanianb60352a2009-02-17 18:27:45 +0000849 ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattner578a37e2008-10-12 00:26:57 +0000850 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000851 }
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000852 ExtQualType *New =
853 new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
Fariborz Jahanianb60352a2009-02-17 18:27:45 +0000854 ExtQualTypes.InsertNode(New, InsertPos);
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000855 Types.push_back(New);
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000856 return QualType(New, CVRQuals);
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000857}
858
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000859QualType ASTContext::getObjCGCQualType(QualType T,
860 QualType::GCAttrTypes GCAttr) {
Fariborz Jahanianaf238092009-02-18 05:09:49 +0000861 QualType CanT = getCanonicalType(T);
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000862 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahanianaf238092009-02-18 05:09:49 +0000863 return T;
864
Fariborz Jahanian143b0082009-06-03 17:15:17 +0000865 if (T->isPointerType()) {
866 QualType Pointee = T->getAsPointerType()->getPointeeType();
867 if (Pointee->isPointerType()) {
868 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
869 return getPointerType(ResultType);
870 }
871 }
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000872 // If we are composing extended qualifiers together, merge together into one
873 // ExtQualType node.
874 unsigned CVRQuals = T.getCVRQualifiers();
875 Type *TypeNode = T.getTypePtr();
876 unsigned AddressSpace = 0;
877
878 if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
879 // If this type already has an address space specified, it cannot get
880 // another one.
881 assert(EQT->getObjCGCAttr() == QualType::GCNone &&
882 "Type cannot be in multiple addr spaces!");
883 AddressSpace = EQT->getAddressSpace();
884 TypeNode = EQT->getBaseType();
885 }
Fariborz Jahanianaf238092009-02-18 05:09:49 +0000886
887 // Check if we've already instantiated an gc qual'd type of this type.
888 llvm::FoldingSetNodeID ID;
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000889 ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
Fariborz Jahanianaf238092009-02-18 05:09:49 +0000890 void *InsertPos = 0;
891 if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000892 return QualType(EXTQy, CVRQuals);
Fariborz Jahanianaf238092009-02-18 05:09:49 +0000893
894 // If the base type isn't canonical, this won't be a canonical type either,
895 // so fill in the canonical type field.
Eli Friedman94fcc9a2009-02-27 23:04:43 +0000896 // FIXME: Isn't this also not canonical if the base type is a array
897 // or pointer type? I can't find any documentation for objc_gc, though...
Fariborz Jahanianaf238092009-02-18 05:09:49 +0000898 QualType Canonical;
899 if (!T->isCanonical()) {
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000900 Canonical = getObjCGCQualType(CanT, GCAttr);
Fariborz Jahanianaf238092009-02-18 05:09:49 +0000901
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000902 // Update InsertPos, the previous call could have invalidated it.
Fariborz Jahanianaf238092009-02-18 05:09:49 +0000903 ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
904 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
905 }
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000906 ExtQualType *New =
907 new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
Fariborz Jahanianaf238092009-02-18 05:09:49 +0000908 ExtQualTypes.InsertNode(New, InsertPos);
909 Types.push_back(New);
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000910 return QualType(New, CVRQuals);
Fariborz Jahanianaf238092009-02-18 05:09:49 +0000911}
Chris Lattner4b009652007-07-25 00:24:17 +0000912
913/// getComplexType - Return the uniqued reference to the type for a complex
914/// number with the specified element type.
915QualType ASTContext::getComplexType(QualType T) {
916 // Unique pointers, to guarantee there is only one pointer of a particular
917 // structure.
918 llvm::FoldingSetNodeID ID;
919 ComplexType::Profile(ID, T);
920
921 void *InsertPos = 0;
922 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
923 return QualType(CT, 0);
924
925 // If the pointee type isn't canonical, this won't be a canonical type either,
926 // so fill in the canonical type field.
927 QualType Canonical;
928 if (!T->isCanonical()) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +0000929 Canonical = getComplexType(getCanonicalType(T));
Chris Lattner4b009652007-07-25 00:24:17 +0000930
931 // Get the new insert position for the node we care about.
932 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattner578a37e2008-10-12 00:26:57 +0000933 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner4b009652007-07-25 00:24:17 +0000934 }
Steve Naroff93fd2112009-01-27 22:08:43 +0000935 ComplexType *New = new (*this,8) ComplexType(T, Canonical);
Chris Lattner4b009652007-07-25 00:24:17 +0000936 Types.push_back(New);
937 ComplexTypes.InsertNode(New, InsertPos);
938 return QualType(New, 0);
939}
940
Eli Friedmanff3fcdf2009-02-13 02:31:07 +0000941QualType ASTContext::getFixedWidthIntType(unsigned Width, bool Signed) {
942 llvm::DenseMap<unsigned, FixedWidthIntType*> &Map = Signed ?
943 SignedFixedWidthIntTypes : UnsignedFixedWidthIntTypes;
944 FixedWidthIntType *&Entry = Map[Width];
945 if (!Entry)
946 Entry = new FixedWidthIntType(Width, Signed);
947 return QualType(Entry, 0);
948}
Chris Lattner4b009652007-07-25 00:24:17 +0000949
950/// getPointerType - Return the uniqued reference to the type for a pointer to
951/// the specified type.
952QualType ASTContext::getPointerType(QualType T) {
953 // Unique pointers, to guarantee there is only one pointer of a particular
954 // structure.
955 llvm::FoldingSetNodeID ID;
956 PointerType::Profile(ID, T);
957
958 void *InsertPos = 0;
959 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
960 return QualType(PT, 0);
961
962 // If the pointee type isn't canonical, this won't be a canonical type either,
963 // so fill in the canonical type field.
964 QualType Canonical;
965 if (!T->isCanonical()) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +0000966 Canonical = getPointerType(getCanonicalType(T));
Chris Lattner4b009652007-07-25 00:24:17 +0000967
968 // Get the new insert position for the node we care about.
969 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattner578a37e2008-10-12 00:26:57 +0000970 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner4b009652007-07-25 00:24:17 +0000971 }
Steve Naroff93fd2112009-01-27 22:08:43 +0000972 PointerType *New = new (*this,8) PointerType(T, Canonical);
Chris Lattner4b009652007-07-25 00:24:17 +0000973 Types.push_back(New);
974 PointerTypes.InsertNode(New, InsertPos);
975 return QualType(New, 0);
976}
977
Steve Naroff7aa54752008-08-27 16:04:49 +0000978/// getBlockPointerType - Return the uniqued reference to the type for
979/// a pointer to the specified block.
980QualType ASTContext::getBlockPointerType(QualType T) {
Steve Narofffd5b19d2008-08-28 19:20:44 +0000981 assert(T->isFunctionType() && "block of function types only");
982 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff7aa54752008-08-27 16:04:49 +0000983 // structure.
984 llvm::FoldingSetNodeID ID;
985 BlockPointerType::Profile(ID, T);
986
987 void *InsertPos = 0;
988 if (BlockPointerType *PT =
989 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
990 return QualType(PT, 0);
991
Steve Narofffd5b19d2008-08-28 19:20:44 +0000992 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff7aa54752008-08-27 16:04:49 +0000993 // type either so fill in the canonical type field.
994 QualType Canonical;
995 if (!T->isCanonical()) {
996 Canonical = getBlockPointerType(getCanonicalType(T));
997
998 // Get the new insert position for the node we care about.
999 BlockPointerType *NewIP =
1000 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattner578a37e2008-10-12 00:26:57 +00001001 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff7aa54752008-08-27 16:04:49 +00001002 }
Steve Naroff93fd2112009-01-27 22:08:43 +00001003 BlockPointerType *New = new (*this,8) BlockPointerType(T, Canonical);
Steve Naroff7aa54752008-08-27 16:04:49 +00001004 Types.push_back(New);
1005 BlockPointerTypes.InsertNode(New, InsertPos);
1006 return QualType(New, 0);
1007}
1008
Sebastian Redlce6fff02009-03-16 23:22:08 +00001009/// getLValueReferenceType - Return the uniqued reference to the type for an
1010/// lvalue reference to the specified type.
1011QualType ASTContext::getLValueReferenceType(QualType T) {
Chris Lattner4b009652007-07-25 00:24:17 +00001012 // Unique pointers, to guarantee there is only one pointer of a particular
1013 // structure.
1014 llvm::FoldingSetNodeID ID;
1015 ReferenceType::Profile(ID, T);
1016
1017 void *InsertPos = 0;
Sebastian Redlce6fff02009-03-16 23:22:08 +00001018 if (LValueReferenceType *RT =
1019 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattner4b009652007-07-25 00:24:17 +00001020 return QualType(RT, 0);
Sebastian Redlce6fff02009-03-16 23:22:08 +00001021
Chris Lattner4b009652007-07-25 00:24:17 +00001022 // If the referencee type isn't canonical, this won't be a canonical type
1023 // either, so fill in the canonical type field.
1024 QualType Canonical;
1025 if (!T->isCanonical()) {
Sebastian Redlce6fff02009-03-16 23:22:08 +00001026 Canonical = getLValueReferenceType(getCanonicalType(T));
1027
Chris Lattner4b009652007-07-25 00:24:17 +00001028 // Get the new insert position for the node we care about.
Sebastian Redlce6fff02009-03-16 23:22:08 +00001029 LValueReferenceType *NewIP =
1030 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattner578a37e2008-10-12 00:26:57 +00001031 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner4b009652007-07-25 00:24:17 +00001032 }
1033
Sebastian Redlce6fff02009-03-16 23:22:08 +00001034 LValueReferenceType *New = new (*this,8) LValueReferenceType(T, Canonical);
Chris Lattner4b009652007-07-25 00:24:17 +00001035 Types.push_back(New);
Sebastian Redlce6fff02009-03-16 23:22:08 +00001036 LValueReferenceTypes.InsertNode(New, InsertPos);
1037 return QualType(New, 0);
1038}
1039
1040/// getRValueReferenceType - Return the uniqued reference to the type for an
1041/// rvalue reference to the specified type.
1042QualType ASTContext::getRValueReferenceType(QualType T) {
1043 // Unique pointers, to guarantee there is only one pointer of a particular
1044 // structure.
1045 llvm::FoldingSetNodeID ID;
1046 ReferenceType::Profile(ID, T);
1047
1048 void *InsertPos = 0;
1049 if (RValueReferenceType *RT =
1050 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1051 return QualType(RT, 0);
1052
1053 // If the referencee type isn't canonical, this won't be a canonical type
1054 // either, so fill in the canonical type field.
1055 QualType Canonical;
1056 if (!T->isCanonical()) {
1057 Canonical = getRValueReferenceType(getCanonicalType(T));
1058
1059 // Get the new insert position for the node we care about.
1060 RValueReferenceType *NewIP =
1061 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1062 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1063 }
1064
1065 RValueReferenceType *New = new (*this,8) RValueReferenceType(T, Canonical);
1066 Types.push_back(New);
1067 RValueReferenceTypes.InsertNode(New, InsertPos);
Chris Lattner4b009652007-07-25 00:24:17 +00001068 return QualType(New, 0);
1069}
1070
Sebastian Redl75555032009-01-24 21:16:55 +00001071/// getMemberPointerType - Return the uniqued reference to the type for a
1072/// member pointer to the specified type, in the specified class.
1073QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls)
1074{
1075 // Unique pointers, to guarantee there is only one pointer of a particular
1076 // structure.
1077 llvm::FoldingSetNodeID ID;
1078 MemberPointerType::Profile(ID, T, Cls);
1079
1080 void *InsertPos = 0;
1081 if (MemberPointerType *PT =
1082 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1083 return QualType(PT, 0);
1084
1085 // If the pointee or class type isn't canonical, this won't be a canonical
1086 // type either, so fill in the canonical type field.
1087 QualType Canonical;
1088 if (!T->isCanonical()) {
1089 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1090
1091 // Get the new insert position for the node we care about.
1092 MemberPointerType *NewIP =
1093 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1094 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1095 }
Steve Naroff93fd2112009-01-27 22:08:43 +00001096 MemberPointerType *New = new (*this,8) MemberPointerType(T, Cls, Canonical);
Sebastian Redl75555032009-01-24 21:16:55 +00001097 Types.push_back(New);
1098 MemberPointerTypes.InsertNode(New, InsertPos);
1099 return QualType(New, 0);
1100}
1101
Steve Naroff83c13012007-08-30 01:06:46 +00001102/// getConstantArrayType - Return the unique reference to the type for an
1103/// array of the specified element type.
1104QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner08bea472009-05-13 04:12:56 +00001105 const llvm::APInt &ArySizeIn,
Steve Naroff24c9b982007-08-30 18:10:14 +00001106 ArrayType::ArraySizeModifier ASM,
1107 unsigned EltTypeQuals) {
Eli Friedmanb4c71b32009-05-29 20:17:55 +00001108 assert((EltTy->isDependentType() || EltTy->isConstantSizeType()) &&
1109 "Constant array of VLAs is illegal!");
1110
Chris Lattner08bea472009-05-13 04:12:56 +00001111 // Convert the array size into a canonical width matching the pointer size for
1112 // the target.
1113 llvm::APInt ArySize(ArySizeIn);
1114 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1115
Chris Lattner4b009652007-07-25 00:24:17 +00001116 llvm::FoldingSetNodeID ID;
Chris Lattner3f7a8f12009-02-19 17:31:02 +00001117 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Chris Lattner4b009652007-07-25 00:24:17 +00001118
1119 void *InsertPos = 0;
Ted Kremenek738e6c02007-10-31 17:10:13 +00001120 if (ConstantArrayType *ATP =
1121 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattner4b009652007-07-25 00:24:17 +00001122 return QualType(ATP, 0);
1123
1124 // If the element type isn't canonical, this won't be a canonical type either,
1125 // so fill in the canonical type field.
1126 QualType Canonical;
1127 if (!EltTy->isCanonical()) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001128 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroff24c9b982007-08-30 18:10:14 +00001129 ASM, EltTypeQuals);
Chris Lattner4b009652007-07-25 00:24:17 +00001130 // Get the new insert position for the node we care about.
Ted Kremenek738e6c02007-10-31 17:10:13 +00001131 ConstantArrayType *NewIP =
1132 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattner578a37e2008-10-12 00:26:57 +00001133 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner4b009652007-07-25 00:24:17 +00001134 }
1135
Ted Kremenekc70e7d02009-01-19 21:31:22 +00001136 ConstantArrayType *New =
Steve Naroff93fd2112009-01-27 22:08:43 +00001137 new(*this,8)ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek738e6c02007-10-31 17:10:13 +00001138 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner4b009652007-07-25 00:24:17 +00001139 Types.push_back(New);
1140 return QualType(New, 0);
1141}
1142
Steve Naroffe2579e32007-08-30 18:14:25 +00001143/// getVariableArrayType - Returns a non-unique reference to the type for a
1144/// variable array of the specified element type.
Steve Naroff24c9b982007-08-30 18:10:14 +00001145QualType ASTContext::getVariableArrayType(QualType EltTy, Expr *NumElts,
1146 ArrayType::ArraySizeModifier ASM,
1147 unsigned EltTypeQuals) {
Eli Friedman8ff07782008-02-15 18:16:39 +00001148 // Since we don't unique expressions, it isn't possible to unique VLA's
1149 // that have an expression provided for their size.
1150
Ted Kremenekc70e7d02009-01-19 21:31:22 +00001151 VariableArrayType *New =
Steve Naroff93fd2112009-01-27 22:08:43 +00001152 new(*this,8)VariableArrayType(EltTy,QualType(), NumElts, ASM, EltTypeQuals);
Eli Friedman8ff07782008-02-15 18:16:39 +00001153
1154 VariableArrayTypes.push_back(New);
1155 Types.push_back(New);
1156 return QualType(New, 0);
1157}
1158
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001159/// getDependentSizedArrayType - Returns a non-unique reference to
1160/// the type for a dependently-sized array of the specified element
1161/// type. FIXME: We will need these to be uniqued, or at least
1162/// comparable, at some point.
1163QualType ASTContext::getDependentSizedArrayType(QualType EltTy, Expr *NumElts,
1164 ArrayType::ArraySizeModifier ASM,
1165 unsigned EltTypeQuals) {
1166 assert((NumElts->isTypeDependent() || NumElts->isValueDependent()) &&
1167 "Size must be type- or value-dependent!");
1168
1169 // Since we don't unique expressions, it isn't possible to unique
1170 // dependently-sized array types.
1171
Ted Kremenekc70e7d02009-01-19 21:31:22 +00001172 DependentSizedArrayType *New =
Steve Naroff93fd2112009-01-27 22:08:43 +00001173 new (*this,8) DependentSizedArrayType(EltTy, QualType(), NumElts,
1174 ASM, EltTypeQuals);
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001175
1176 DependentSizedArrayTypes.push_back(New);
1177 Types.push_back(New);
1178 return QualType(New, 0);
1179}
1180
Eli Friedman8ff07782008-02-15 18:16:39 +00001181QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1182 ArrayType::ArraySizeModifier ASM,
1183 unsigned EltTypeQuals) {
1184 llvm::FoldingSetNodeID ID;
Chris Lattner3f7a8f12009-02-19 17:31:02 +00001185 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedman8ff07782008-02-15 18:16:39 +00001186
1187 void *InsertPos = 0;
1188 if (IncompleteArrayType *ATP =
1189 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1190 return QualType(ATP, 0);
1191
1192 // If the element type isn't canonical, this won't be a canonical type
1193 // either, so fill in the canonical type field.
1194 QualType Canonical;
1195
1196 if (!EltTy->isCanonical()) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001197 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek3793e1a2007-10-29 23:37:31 +00001198 ASM, EltTypeQuals);
Eli Friedman8ff07782008-02-15 18:16:39 +00001199
1200 // Get the new insert position for the node we care about.
1201 IncompleteArrayType *NewIP =
1202 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattner578a37e2008-10-12 00:26:57 +00001203 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek3793e1a2007-10-29 23:37:31 +00001204 }
Eli Friedman8ff07782008-02-15 18:16:39 +00001205
Steve Naroff93fd2112009-01-27 22:08:43 +00001206 IncompleteArrayType *New = new (*this,8) IncompleteArrayType(EltTy, Canonical,
Ted Kremenekc70e7d02009-01-19 21:31:22 +00001207 ASM, EltTypeQuals);
Eli Friedman8ff07782008-02-15 18:16:39 +00001208
1209 IncompleteArrayTypes.InsertNode(New, InsertPos);
1210 Types.push_back(New);
1211 return QualType(New, 0);
Steve Naroff83c13012007-08-30 01:06:46 +00001212}
1213
Chris Lattner4b009652007-07-25 00:24:17 +00001214/// getVectorType - Return the unique reference to a vector type of
1215/// the specified element type and size. VectorType must be a built-in type.
1216QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) {
1217 BuiltinType *baseType;
1218
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001219 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Chris Lattner4b009652007-07-25 00:24:17 +00001220 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
1221
1222 // Check if we've already instantiated a vector of this type.
1223 llvm::FoldingSetNodeID ID;
1224 VectorType::Profile(ID, vecType, NumElts, Type::Vector);
1225 void *InsertPos = 0;
1226 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1227 return QualType(VTP, 0);
1228
1229 // If the element type isn't canonical, this won't be a canonical type either,
1230 // so fill in the canonical type field.
1231 QualType Canonical;
1232 if (!vecType->isCanonical()) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001233 Canonical = getVectorType(getCanonicalType(vecType), NumElts);
Chris Lattner4b009652007-07-25 00:24:17 +00001234
1235 // Get the new insert position for the node we care about.
1236 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattner578a37e2008-10-12 00:26:57 +00001237 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner4b009652007-07-25 00:24:17 +00001238 }
Steve Naroff93fd2112009-01-27 22:08:43 +00001239 VectorType *New = new (*this,8) VectorType(vecType, NumElts, Canonical);
Chris Lattner4b009652007-07-25 00:24:17 +00001240 VectorTypes.InsertNode(New, InsertPos);
1241 Types.push_back(New);
1242 return QualType(New, 0);
1243}
1244
Nate Begemanaf6ed502008-04-18 23:10:10 +00001245/// getExtVectorType - Return the unique reference to an extended vector type of
Chris Lattner4b009652007-07-25 00:24:17 +00001246/// the specified element type and size. VectorType must be a built-in type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00001247QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Chris Lattner4b009652007-07-25 00:24:17 +00001248 BuiltinType *baseType;
1249
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001250 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begemanaf6ed502008-04-18 23:10:10 +00001251 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Chris Lattner4b009652007-07-25 00:24:17 +00001252
1253 // Check if we've already instantiated a vector of this type.
1254 llvm::FoldingSetNodeID ID;
Nate Begemanaf6ed502008-04-18 23:10:10 +00001255 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector);
Chris Lattner4b009652007-07-25 00:24:17 +00001256 void *InsertPos = 0;
1257 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1258 return QualType(VTP, 0);
1259
1260 // If the element type isn't canonical, this won't be a canonical type either,
1261 // so fill in the canonical type field.
1262 QualType Canonical;
1263 if (!vecType->isCanonical()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001264 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Chris Lattner4b009652007-07-25 00:24:17 +00001265
1266 // Get the new insert position for the node we care about.
1267 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattner578a37e2008-10-12 00:26:57 +00001268 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner4b009652007-07-25 00:24:17 +00001269 }
Steve Naroff93fd2112009-01-27 22:08:43 +00001270 ExtVectorType *New = new (*this,8) ExtVectorType(vecType, NumElts, Canonical);
Chris Lattner4b009652007-07-25 00:24:17 +00001271 VectorTypes.InsertNode(New, InsertPos);
1272 Types.push_back(New);
1273 return QualType(New, 0);
1274}
1275
Douglas Gregor2a2e0402009-06-17 21:51:59 +00001276QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
1277 Expr *SizeExpr,
1278 SourceLocation AttrLoc) {
1279 DependentSizedExtVectorType *New =
1280 new (*this,8) DependentSizedExtVectorType(vecType, QualType(),
1281 SizeExpr, AttrLoc);
1282
1283 DependentSizedExtVectorTypes.push_back(New);
1284 Types.push_back(New);
1285 return QualType(New, 0);
1286}
1287
Douglas Gregor4fa58902009-02-26 23:50:07 +00001288/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattner4b009652007-07-25 00:24:17 +00001289///
Douglas Gregor4fa58902009-02-26 23:50:07 +00001290QualType ASTContext::getFunctionNoProtoType(QualType ResultTy) {
Chris Lattner4b009652007-07-25 00:24:17 +00001291 // Unique functions, to guarantee there is only one function of a particular
1292 // structure.
1293 llvm::FoldingSetNodeID ID;
Douglas Gregor4fa58902009-02-26 23:50:07 +00001294 FunctionNoProtoType::Profile(ID, ResultTy);
Chris Lattner4b009652007-07-25 00:24:17 +00001295
1296 void *InsertPos = 0;
Douglas Gregor4fa58902009-02-26 23:50:07 +00001297 if (FunctionNoProtoType *FT =
1298 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattner4b009652007-07-25 00:24:17 +00001299 return QualType(FT, 0);
1300
1301 QualType Canonical;
1302 if (!ResultTy->isCanonical()) {
Douglas Gregor4fa58902009-02-26 23:50:07 +00001303 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy));
Chris Lattner4b009652007-07-25 00:24:17 +00001304
1305 // Get the new insert position for the node we care about.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001306 FunctionNoProtoType *NewIP =
1307 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattner578a37e2008-10-12 00:26:57 +00001308 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner4b009652007-07-25 00:24:17 +00001309 }
1310
Douglas Gregor4fa58902009-02-26 23:50:07 +00001311 FunctionNoProtoType *New =new(*this,8)FunctionNoProtoType(ResultTy,Canonical);
Chris Lattner4b009652007-07-25 00:24:17 +00001312 Types.push_back(New);
Douglas Gregor4fa58902009-02-26 23:50:07 +00001313 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Chris Lattner4b009652007-07-25 00:24:17 +00001314 return QualType(New, 0);
1315}
1316
1317/// getFunctionType - Return a normal function type with a typed argument
1318/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner2fda0ed2008-10-05 17:34:18 +00001319QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argiris Kirtzidis4b269b42008-10-24 21:46:40 +00001320 unsigned NumArgs, bool isVariadic,
Sebastian Redl2767d882009-05-27 22:11:52 +00001321 unsigned TypeQuals, bool hasExceptionSpec,
1322 bool hasAnyExceptionSpec, unsigned NumExs,
1323 const QualType *ExArray) {
Chris Lattner4b009652007-07-25 00:24:17 +00001324 // Unique functions, to guarantee there is only one function of a particular
1325 // structure.
1326 llvm::FoldingSetNodeID ID;
Douglas Gregor4fa58902009-02-26 23:50:07 +00001327 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl2767d882009-05-27 22:11:52 +00001328 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
1329 NumExs, ExArray);
Chris Lattner4b009652007-07-25 00:24:17 +00001330
1331 void *InsertPos = 0;
Douglas Gregor4fa58902009-02-26 23:50:07 +00001332 if (FunctionProtoType *FTP =
1333 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattner4b009652007-07-25 00:24:17 +00001334 return QualType(FTP, 0);
Sebastian Redl2767d882009-05-27 22:11:52 +00001335
1336 // Determine whether the type being created is already canonical or not.
Chris Lattner4b009652007-07-25 00:24:17 +00001337 bool isCanonical = ResultTy->isCanonical();
Sebastian Redl2767d882009-05-27 22:11:52 +00001338 if (hasExceptionSpec)
1339 isCanonical = false;
Chris Lattner4b009652007-07-25 00:24:17 +00001340 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
1341 if (!ArgArray[i]->isCanonical())
1342 isCanonical = false;
1343
1344 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl2767d882009-05-27 22:11:52 +00001345 // The exception spec is not part of the canonical type.
Chris Lattner4b009652007-07-25 00:24:17 +00001346 QualType Canonical;
1347 if (!isCanonical) {
1348 llvm::SmallVector<QualType, 16> CanonicalArgs;
1349 CanonicalArgs.reserve(NumArgs);
1350 for (unsigned i = 0; i != NumArgs; ++i)
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001351 CanonicalArgs.push_back(getCanonicalType(ArgArray[i]));
Sebastian Redl2767d882009-05-27 22:11:52 +00001352
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001353 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad9e6bef42009-05-21 09:52:38 +00001354 CanonicalArgs.data(), NumArgs,
Sebastian Redlba9a3712009-05-06 23:27:55 +00001355 isVariadic, TypeQuals);
Sebastian Redl2767d882009-05-27 22:11:52 +00001356
Chris Lattner4b009652007-07-25 00:24:17 +00001357 // Get the new insert position for the node we care about.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001358 FunctionProtoType *NewIP =
1359 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattner578a37e2008-10-12 00:26:57 +00001360 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner4b009652007-07-25 00:24:17 +00001361 }
Sebastian Redl2767d882009-05-27 22:11:52 +00001362
Douglas Gregor4fa58902009-02-26 23:50:07 +00001363 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl2767d882009-05-27 22:11:52 +00001364 // for two variable size arrays (for parameter and exception types) at the
1365 // end of them.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001366 FunctionProtoType *FTP =
Sebastian Redl2767d882009-05-27 22:11:52 +00001367 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1368 NumArgs*sizeof(QualType) +
1369 NumExs*sizeof(QualType), 8);
Douglas Gregor4fa58902009-02-26 23:50:07 +00001370 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl2767d882009-05-27 22:11:52 +00001371 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
1372 ExArray, NumExs, Canonical);
Chris Lattner4b009652007-07-25 00:24:17 +00001373 Types.push_back(FTP);
Douglas Gregor4fa58902009-02-26 23:50:07 +00001374 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Chris Lattner4b009652007-07-25 00:24:17 +00001375 return QualType(FTP, 0);
1376}
1377
Douglas Gregor1d661552008-04-13 21:07:44 +00001378/// getTypeDeclType - Return the unique reference to the type for the
1379/// specified type declaration.
Ted Kremenek46a837c2008-09-05 17:16:31 +00001380QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) {
Argiris Kirtzidiseeec5482008-10-16 16:50:47 +00001381 assert(Decl && "Passed null for Decl param");
Douglas Gregor1d661552008-04-13 21:07:44 +00001382 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1383
Argiris Kirtzidiseeec5482008-10-16 16:50:47 +00001384 if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor1d661552008-04-13 21:07:44 +00001385 return getTypedefType(Typedef);
Douglas Gregora4918772009-02-05 23:33:38 +00001386 else if (isa<TemplateTypeParmDecl>(Decl)) {
1387 assert(false && "Template type parameter types are always available.");
1388 } else if (ObjCInterfaceDecl *ObjCInterface = dyn_cast<ObjCInterfaceDecl>(Decl))
Douglas Gregor1d661552008-04-13 21:07:44 +00001389 return getObjCInterfaceType(ObjCInterface);
Argiris Kirtzidisea29d1e2008-08-07 20:55:28 +00001390
Douglas Gregor2e047592009-02-28 01:32:25 +00001391 if (RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Ted Kremenekc70e7d02009-01-19 21:31:22 +00001392 if (PrevDecl)
1393 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Naroff93fd2112009-01-27 22:08:43 +00001394 else
1395 Decl->TypeForDecl = new (*this,8) RecordType(Record);
Ted Kremenek46a837c2008-09-05 17:16:31 +00001396 }
Ted Kremenekc70e7d02009-01-19 21:31:22 +00001397 else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
1398 if (PrevDecl)
1399 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Naroff93fd2112009-01-27 22:08:43 +00001400 else
1401 Decl->TypeForDecl = new (*this,8) EnumType(Enum);
Ted Kremenekc70e7d02009-01-19 21:31:22 +00001402 }
Argiris Kirtzidisea29d1e2008-08-07 20:55:28 +00001403 else
Douglas Gregor1d661552008-04-13 21:07:44 +00001404 assert(false && "TypeDecl without a type?");
Argiris Kirtzidisea29d1e2008-08-07 20:55:28 +00001405
Ted Kremenek46a837c2008-09-05 17:16:31 +00001406 if (!PrevDecl) Types.push_back(Decl->TypeForDecl);
Argiris Kirtzidisea29d1e2008-08-07 20:55:28 +00001407 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor1d661552008-04-13 21:07:44 +00001408}
1409
Chris Lattner4b009652007-07-25 00:24:17 +00001410/// getTypedefType - Return the unique reference to the type for the
1411/// specified typename decl.
1412QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
1413 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1414
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001415 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
Douglas Gregor4fa58902009-02-26 23:50:07 +00001416 Decl->TypeForDecl = new(*this,8) TypedefType(Type::Typedef, Decl, Canonical);
Chris Lattner4b009652007-07-25 00:24:17 +00001417 Types.push_back(Decl->TypeForDecl);
1418 return QualType(Decl->TypeForDecl, 0);
1419}
1420
Ted Kremenek42730c52008-01-07 19:49:32 +00001421/// getObjCInterfaceType - Return the unique reference to the type for the
Steve Naroff81f1bba2007-09-06 21:24:23 +00001422/// specified ObjC interface decl.
Daniel Dunbarbe1ff272009-04-22 04:34:53 +00001423QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) {
Steve Naroff81f1bba2007-09-06 21:24:23 +00001424 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1425
Daniel Dunbarbe1ff272009-04-22 04:34:53 +00001426 ObjCInterfaceDecl *OID = const_cast<ObjCInterfaceDecl*>(Decl);
1427 Decl->TypeForDecl = new(*this,8) ObjCInterfaceType(Type::ObjCInterface, OID);
Steve Naroff81f1bba2007-09-06 21:24:23 +00001428 Types.push_back(Decl->TypeForDecl);
1429 return QualType(Decl->TypeForDecl, 0);
1430}
1431
Douglas Gregora4918772009-02-05 23:33:38 +00001432/// \brief Retrieve the template type parameter type for a template
Anders Carlsson4e3d3552009-06-16 00:30:48 +00001433/// parameter or parameter pack with the given depth, index, and (optionally)
1434/// name.
Douglas Gregora4918772009-02-05 23:33:38 +00001435QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson4e3d3552009-06-16 00:30:48 +00001436 bool ParameterPack,
Douglas Gregora4918772009-02-05 23:33:38 +00001437 IdentifierInfo *Name) {
1438 llvm::FoldingSetNodeID ID;
Anders Carlsson4e3d3552009-06-16 00:30:48 +00001439 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregora4918772009-02-05 23:33:38 +00001440 void *InsertPos = 0;
1441 TemplateTypeParmType *TypeParm
1442 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1443
1444 if (TypeParm)
1445 return QualType(TypeParm, 0);
1446
Anders Carlsson4e3d3552009-06-16 00:30:48 +00001447 if (Name) {
1448 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
1449 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, ParameterPack,
1450 Name, Canon);
1451 } else
1452 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregora4918772009-02-05 23:33:38 +00001453
1454 Types.push_back(TypeParm);
1455 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1456
1457 return QualType(TypeParm, 0);
1458}
1459
Douglas Gregor8e458f42009-02-09 18:46:07 +00001460QualType
Douglas Gregordd13e842009-03-30 22:58:21 +00001461ASTContext::getTemplateSpecializationType(TemplateName Template,
1462 const TemplateArgument *Args,
1463 unsigned NumArgs,
1464 QualType Canon) {
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001465 if (!Canon.isNull())
1466 Canon = getCanonicalType(Canon);
Douglas Gregor9c7825b2009-02-26 22:19:44 +00001467
Douglas Gregor8e458f42009-02-09 18:46:07 +00001468 llvm::FoldingSetNodeID ID;
Douglas Gregordd13e842009-03-30 22:58:21 +00001469 TemplateSpecializationType::Profile(ID, Template, Args, NumArgs);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001470
Douglas Gregor8e458f42009-02-09 18:46:07 +00001471 void *InsertPos = 0;
Douglas Gregordd13e842009-03-30 22:58:21 +00001472 TemplateSpecializationType *Spec
1473 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor8e458f42009-02-09 18:46:07 +00001474
1475 if (Spec)
1476 return QualType(Spec, 0);
1477
Douglas Gregordd13e842009-03-30 22:58:21 +00001478 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001479 sizeof(TemplateArgument) * NumArgs),
1480 8);
Douglas Gregordd13e842009-03-30 22:58:21 +00001481 Spec = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, Canon);
Douglas Gregor8e458f42009-02-09 18:46:07 +00001482 Types.push_back(Spec);
Douglas Gregordd13e842009-03-30 22:58:21 +00001483 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
Douglas Gregor8e458f42009-02-09 18:46:07 +00001484
1485 return QualType(Spec, 0);
1486}
1487
Douglas Gregor734b4ba2009-03-19 00:18:19 +00001488QualType
Douglas Gregor1e589cc2009-03-26 23:50:42 +00001489ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
Douglas Gregor734b4ba2009-03-19 00:18:19 +00001490 QualType NamedType) {
1491 llvm::FoldingSetNodeID ID;
Douglas Gregor1e589cc2009-03-26 23:50:42 +00001492 QualifiedNameType::Profile(ID, NNS, NamedType);
Douglas Gregor734b4ba2009-03-19 00:18:19 +00001493
1494 void *InsertPos = 0;
1495 QualifiedNameType *T
1496 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
1497 if (T)
1498 return QualType(T, 0);
1499
Douglas Gregor1e589cc2009-03-26 23:50:42 +00001500 T = new (*this) QualifiedNameType(NNS, NamedType,
1501 getCanonicalType(NamedType));
Douglas Gregor734b4ba2009-03-19 00:18:19 +00001502 Types.push_back(T);
1503 QualifiedNameTypes.InsertNode(T, InsertPos);
1504 return QualType(T, 0);
1505}
1506
Douglas Gregord3022602009-03-27 23:10:48 +00001507QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1508 const IdentifierInfo *Name,
1509 QualType Canon) {
1510 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1511
1512 if (Canon.isNull()) {
1513 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1514 if (CanonNNS != NNS)
1515 Canon = getTypenameType(CanonNNS, Name);
1516 }
1517
1518 llvm::FoldingSetNodeID ID;
1519 TypenameType::Profile(ID, NNS, Name);
1520
1521 void *InsertPos = 0;
1522 TypenameType *T
1523 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1524 if (T)
1525 return QualType(T, 0);
1526
1527 T = new (*this) TypenameType(NNS, Name, Canon);
1528 Types.push_back(T);
1529 TypenameTypes.InsertNode(T, InsertPos);
1530 return QualType(T, 0);
1531}
1532
Douglas Gregor77da5802009-04-01 00:28:59 +00001533QualType
1534ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1535 const TemplateSpecializationType *TemplateId,
1536 QualType Canon) {
1537 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1538
1539 if (Canon.isNull()) {
1540 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1541 QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
1542 if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
1543 const TemplateSpecializationType *CanonTemplateId
1544 = CanonType->getAsTemplateSpecializationType();
1545 assert(CanonTemplateId &&
1546 "Canonical type must also be a template specialization type");
1547 Canon = getTypenameType(CanonNNS, CanonTemplateId);
1548 }
1549 }
1550
1551 llvm::FoldingSetNodeID ID;
1552 TypenameType::Profile(ID, NNS, TemplateId);
1553
1554 void *InsertPos = 0;
1555 TypenameType *T
1556 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1557 if (T)
1558 return QualType(T, 0);
1559
1560 T = new (*this) TypenameType(NNS, TemplateId, Canon);
1561 Types.push_back(T);
1562 TypenameTypes.InsertNode(T, InsertPos);
1563 return QualType(T, 0);
1564}
1565
Chris Lattnere1352302008-04-07 04:56:42 +00001566/// CmpProtocolNames - Comparison predicate for sorting protocols
1567/// alphabetically.
1568static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
1569 const ObjCProtocolDecl *RHS) {
Douglas Gregor24afd4a2008-11-17 14:58:09 +00001570 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere1352302008-04-07 04:56:42 +00001571}
1572
1573static void SortAndUniqueProtocols(ObjCProtocolDecl **&Protocols,
1574 unsigned &NumProtocols) {
1575 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
1576
1577 // Sort protocols, keyed by name.
1578 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
1579
1580 // Remove duplicates.
1581 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
1582 NumProtocols = ProtocolsEnd-Protocols;
1583}
1584
Steve Naroffc75c1a82009-06-17 22:40:22 +00001585/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
1586/// the given interface decl and the conforming protocol list.
1587QualType ASTContext::getObjCObjectPointerType(ObjCInterfaceDecl *Decl,
1588 ObjCProtocolDecl **Protocols,
1589 unsigned NumProtocols) {
1590 // Sort the protocol list alphabetically to canonicalize it.
1591 if (NumProtocols)
1592 SortAndUniqueProtocols(Protocols, NumProtocols);
1593
1594 llvm::FoldingSetNodeID ID;
1595 ObjCObjectPointerType::Profile(ID, Decl, Protocols, NumProtocols);
1596
1597 void *InsertPos = 0;
1598 if (ObjCObjectPointerType *QT =
1599 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1600 return QualType(QT, 0);
1601
1602 // No Match;
1603 ObjCObjectPointerType *QType =
1604 new (*this,8) ObjCObjectPointerType(Decl, Protocols, NumProtocols);
1605
1606 Types.push_back(QType);
1607 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
1608 return QualType(QType, 0);
1609}
Chris Lattnere1352302008-04-07 04:56:42 +00001610
Chris Lattnerb0c6a1f2008-04-07 04:44:08 +00001611/// getObjCQualifiedInterfaceType - Return a ObjCQualifiedInterfaceType type for
1612/// the given interface decl and the conforming protocol list.
Ted Kremenek42730c52008-01-07 19:49:32 +00001613QualType ASTContext::getObjCQualifiedInterfaceType(ObjCInterfaceDecl *Decl,
1614 ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
Chris Lattnere1352302008-04-07 04:56:42 +00001615 // Sort the protocol list alphabetically to canonicalize it.
1616 SortAndUniqueProtocols(Protocols, NumProtocols);
1617
Fariborz Jahanian91193f62007-10-11 00:55:41 +00001618 llvm::FoldingSetNodeID ID;
Chris Lattner7cdcb252008-04-07 06:38:24 +00001619 ObjCQualifiedInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
Fariborz Jahanian91193f62007-10-11 00:55:41 +00001620
1621 void *InsertPos = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +00001622 if (ObjCQualifiedInterfaceType *QT =
1623 ObjCQualifiedInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahanian91193f62007-10-11 00:55:41 +00001624 return QualType(QT, 0);
1625
1626 // No Match;
Ted Kremenek42730c52008-01-07 19:49:32 +00001627 ObjCQualifiedInterfaceType *QType =
Steve Naroff93fd2112009-01-27 22:08:43 +00001628 new (*this,8) ObjCQualifiedInterfaceType(Decl, Protocols, NumProtocols);
Ted Kremenekc70e7d02009-01-19 21:31:22 +00001629
Fariborz Jahanian91193f62007-10-11 00:55:41 +00001630 Types.push_back(QType);
Ted Kremenek42730c52008-01-07 19:49:32 +00001631 ObjCQualifiedInterfaceTypes.InsertNode(QType, InsertPos);
Fariborz Jahanian91193f62007-10-11 00:55:41 +00001632 return QualType(QType, 0);
1633}
1634
Chris Lattnere1352302008-04-07 04:56:42 +00001635/// getObjCQualifiedIdType - Return an ObjCQualifiedIdType for the 'id' decl
1636/// and the conforming protocol list.
Chris Lattner4a68fe02008-07-26 00:46:50 +00001637QualType ASTContext::getObjCQualifiedIdType(ObjCProtocolDecl **Protocols,
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001638 unsigned NumProtocols) {
Steve Naroffc75c1a82009-06-17 22:40:22 +00001639 return getObjCObjectPointerType(0, Protocols, NumProtocols);
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001640}
1641
Douglas Gregor4fa58902009-02-26 23:50:07 +00001642/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
1643/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff0604dd92007-08-01 18:02:17 +00001644/// multiple declarations that refer to "typeof(x)" all contain different
1645/// DeclRefExpr's. This doesn't effect the type checker, since it operates
1646/// on canonical type's (which are always unique).
Douglas Gregor4fa58902009-02-26 23:50:07 +00001647QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001648 QualType Canonical = getCanonicalType(tofExpr->getType());
Douglas Gregor4fa58902009-02-26 23:50:07 +00001649 TypeOfExprType *toe = new (*this,8) TypeOfExprType(tofExpr, Canonical);
Steve Naroff0604dd92007-08-01 18:02:17 +00001650 Types.push_back(toe);
1651 return QualType(toe, 0);
Steve Naroff7cbb1462007-07-31 12:34:36 +00001652}
1653
Steve Naroff0604dd92007-08-01 18:02:17 +00001654/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
1655/// TypeOfType AST's. The only motivation to unique these nodes would be
1656/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
1657/// an issue. This doesn't effect the type checker, since it operates
1658/// on canonical type's (which are always unique).
Steve Naroff7cbb1462007-07-31 12:34:36 +00001659QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001660 QualType Canonical = getCanonicalType(tofType);
Steve Naroff93fd2112009-01-27 22:08:43 +00001661 TypeOfType *tot = new (*this,8) TypeOfType(tofType, Canonical);
Steve Naroff0604dd92007-08-01 18:02:17 +00001662 Types.push_back(tot);
1663 return QualType(tot, 0);
Steve Naroff7cbb1462007-07-31 12:34:36 +00001664}
1665
Anders Carlsson93ab5332009-06-24 19:06:50 +00001666/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
1667/// DecltypeType AST's. The only motivation to unique these nodes would be
1668/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
1669/// an issue. This doesn't effect the type checker, since it operates
1670/// on canonical type's (which are always unique).
1671QualType ASTContext::getDecltypeType(Expr *e) {
1672 // FIXME: Use the right type here!
1673 QualType Canonical = getCanonicalType(e->getType());
1674 DecltypeType *dt = new (*this, 8) DecltypeType(e, Canonical);
1675 Types.push_back(dt);
1676 return QualType(dt, 0);
1677}
1678
Chris Lattner4b009652007-07-25 00:24:17 +00001679/// getTagDeclType - Return the unique reference to the type for the
1680/// specified TagDecl (struct/union/class/enum) decl.
1681QualType ASTContext::getTagDeclType(TagDecl *Decl) {
Ted Kremenekae8fa032007-11-26 21:16:01 +00001682 assert (Decl);
Douglas Gregor1d661552008-04-13 21:07:44 +00001683 return getTypeDeclType(Decl);
Chris Lattner4b009652007-07-25 00:24:17 +00001684}
1685
1686/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
1687/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
1688/// needs to agree with the definition in <stddef.h>.
1689QualType ASTContext::getSizeType() const {
Douglas Gregorc6507e42008-11-03 14:12:49 +00001690 return getFromTargetType(Target.getSizeType());
Chris Lattner4b009652007-07-25 00:24:17 +00001691}
1692
Argiris Kirtzidis1ed03e72008-08-09 16:51:54 +00001693/// getSignedWCharType - Return the type of "signed wchar_t".
1694/// Used when in C++, as a GCC extension.
1695QualType ASTContext::getSignedWCharType() const {
1696 // FIXME: derive from "Target" ?
1697 return WCharTy;
1698}
1699
1700/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
1701/// Used when in C++, as a GCC extension.
1702QualType ASTContext::getUnsignedWCharType() const {
1703 // FIXME: derive from "Target" ?
1704 return UnsignedIntTy;
1705}
1706
Chris Lattner4b009652007-07-25 00:24:17 +00001707/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
1708/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
1709QualType ASTContext::getPointerDiffType() const {
Douglas Gregorc6507e42008-11-03 14:12:49 +00001710 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner4b009652007-07-25 00:24:17 +00001711}
1712
Chris Lattner19eb97e2008-04-02 05:18:44 +00001713//===----------------------------------------------------------------------===//
1714// Type Operators
1715//===----------------------------------------------------------------------===//
1716
Chris Lattner3dae6f42008-04-06 22:41:35 +00001717/// getCanonicalType - Return the canonical (structural) type corresponding to
1718/// the specified potentially non-canonical type. The non-canonical version
1719/// of a type may have many "decorated" versions of types. Decorators can
1720/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
1721/// to be free of any of these, allowing two canonical types to be compared
1722/// for exact equality with a simple pointer comparison.
1723QualType ASTContext::getCanonicalType(QualType T) {
1724 QualType CanType = T.getTypePtr()->getCanonicalTypeInternal();
Chris Lattnera1923f62008-08-04 07:31:14 +00001725
1726 // If the result has type qualifiers, make sure to canonicalize them as well.
1727 unsigned TypeQuals = T.getCVRQualifiers() | CanType.getCVRQualifiers();
1728 if (TypeQuals == 0) return CanType;
1729
1730 // If the type qualifiers are on an array type, get the canonical type of the
1731 // array with the qualifiers applied to the element type.
1732 ArrayType *AT = dyn_cast<ArrayType>(CanType);
1733 if (!AT)
1734 return CanType.getQualifiedType(TypeQuals);
1735
1736 // Get the canonical version of the element with the extra qualifiers on it.
1737 // This can recursively sink qualifiers through multiple levels of arrays.
1738 QualType NewEltTy=AT->getElementType().getWithAdditionalQualifiers(TypeQuals);
1739 NewEltTy = getCanonicalType(NewEltTy);
1740
1741 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
1742 return getConstantArrayType(NewEltTy, CAT->getSize(),CAT->getSizeModifier(),
1743 CAT->getIndexTypeQualifier());
1744 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
1745 return getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
1746 IAT->getIndexTypeQualifier());
1747
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001748 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
1749 return getDependentSizedArrayType(NewEltTy, DSAT->getSizeExpr(),
1750 DSAT->getSizeModifier(),
1751 DSAT->getIndexTypeQualifier());
1752
Chris Lattnera1923f62008-08-04 07:31:14 +00001753 VariableArrayType *VAT = cast<VariableArrayType>(AT);
1754 return getVariableArrayType(NewEltTy, VAT->getSizeExpr(),
1755 VAT->getSizeModifier(),
1756 VAT->getIndexTypeQualifier());
1757}
1758
Douglas Gregor9054f982009-05-10 22:57:19 +00001759Decl *ASTContext::getCanonicalDecl(Decl *D) {
Douglas Gregordf3e9572009-05-10 22:59:12 +00001760 if (!D)
1761 return 0;
1762
Douglas Gregor9054f982009-05-10 22:57:19 +00001763 if (TagDecl *Tag = dyn_cast<TagDecl>(D)) {
1764 QualType T = getTagDeclType(Tag);
1765 return cast<TagDecl>(cast<TagType>(T.getTypePtr()->CanonicalType)
1766 ->getDecl());
1767 }
1768
1769 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(D)) {
1770 while (Template->getPreviousDeclaration())
1771 Template = Template->getPreviousDeclaration();
1772 return Template;
1773 }
1774
1775 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
1776 while (Function->getPreviousDeclaration())
1777 Function = Function->getPreviousDeclaration();
1778 return const_cast<FunctionDecl *>(Function);
1779 }
1780
1781 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
1782 while (Var->getPreviousDeclaration())
1783 Var = Var->getPreviousDeclaration();
1784 return const_cast<VarDecl *>(Var);
1785 }
1786
1787 return D;
1788}
1789
Douglas Gregorb88ba412009-05-07 06:41:52 +00001790TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
1791 // If this template name refers to a template, the canonical
1792 // template name merely stores the template itself.
1793 if (TemplateDecl *Template = Name.getAsTemplateDecl())
Douglas Gregor9054f982009-05-10 22:57:19 +00001794 return TemplateName(cast<TemplateDecl>(getCanonicalDecl(Template)));
Douglas Gregorb88ba412009-05-07 06:41:52 +00001795
1796 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
1797 assert(DTN && "Non-dependent template names must refer to template decls.");
1798 return DTN->CanonicalTemplateName;
1799}
1800
Douglas Gregord3022602009-03-27 23:10:48 +00001801NestedNameSpecifier *
1802ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
1803 if (!NNS)
1804 return 0;
1805
1806 switch (NNS->getKind()) {
1807 case NestedNameSpecifier::Identifier:
1808 // Canonicalize the prefix but keep the identifier the same.
1809 return NestedNameSpecifier::Create(*this,
1810 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
1811 NNS->getAsIdentifier());
1812
1813 case NestedNameSpecifier::Namespace:
1814 // A namespace is canonical; build a nested-name-specifier with
1815 // this namespace and no prefix.
1816 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
1817
1818 case NestedNameSpecifier::TypeSpec:
1819 case NestedNameSpecifier::TypeSpecWithTemplate: {
1820 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
1821 NestedNameSpecifier *Prefix = 0;
1822
1823 // FIXME: This isn't the right check!
1824 if (T->isDependentType())
1825 Prefix = getCanonicalNestedNameSpecifier(NNS->getPrefix());
1826
1827 return NestedNameSpecifier::Create(*this, Prefix,
1828 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
1829 T.getTypePtr());
1830 }
1831
1832 case NestedNameSpecifier::Global:
1833 // The global specifier is canonical and unique.
1834 return NNS;
1835 }
1836
1837 // Required to silence a GCC warning
1838 return 0;
1839}
1840
Chris Lattnera1923f62008-08-04 07:31:14 +00001841
1842const ArrayType *ASTContext::getAsArrayType(QualType T) {
1843 // Handle the non-qualified case efficiently.
1844 if (T.getCVRQualifiers() == 0) {
1845 // Handle the common positive case fast.
1846 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
1847 return AT;
1848 }
1849
1850 // Handle the common negative case fast, ignoring CVR qualifiers.
1851 QualType CType = T->getCanonicalTypeInternal();
1852
Fariborz Jahanianb60352a2009-02-17 18:27:45 +00001853 // Make sure to look through type qualifiers (like ExtQuals) for the negative
Chris Lattnera1923f62008-08-04 07:31:14 +00001854 // test.
1855 if (!isa<ArrayType>(CType) &&
1856 !isa<ArrayType>(CType.getUnqualifiedType()))
1857 return 0;
1858
1859 // Apply any CVR qualifiers from the array type to the element type. This
1860 // implements C99 6.7.3p8: "If the specification of an array type includes
1861 // any type qualifiers, the element type is so qualified, not the array type."
1862
1863 // If we get here, we either have type qualifiers on the type, or we have
1864 // sugar such as a typedef in the way. If we have type qualifiers on the type
1865 // we must propagate them down into the elemeng type.
1866 unsigned CVRQuals = T.getCVRQualifiers();
1867 unsigned AddrSpace = 0;
1868 Type *Ty = T.getTypePtr();
1869
Fariborz Jahanianb60352a2009-02-17 18:27:45 +00001870 // Rip through ExtQualType's and typedefs to get to a concrete type.
Chris Lattnera1923f62008-08-04 07:31:14 +00001871 while (1) {
Fariborz Jahanianb60352a2009-02-17 18:27:45 +00001872 if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(Ty)) {
1873 AddrSpace = EXTQT->getAddressSpace();
1874 Ty = EXTQT->getBaseType();
Chris Lattnera1923f62008-08-04 07:31:14 +00001875 } else {
1876 T = Ty->getDesugaredType();
1877 if (T.getTypePtr() == Ty && T.getCVRQualifiers() == 0)
1878 break;
1879 CVRQuals |= T.getCVRQualifiers();
1880 Ty = T.getTypePtr();
1881 }
1882 }
1883
1884 // If we have a simple case, just return now.
1885 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
1886 if (ATy == 0 || (AddrSpace == 0 && CVRQuals == 0))
1887 return ATy;
1888
1889 // Otherwise, we have an array and we have qualifiers on it. Push the
1890 // qualifiers into the array element type and return a new array type.
1891 // Get the canonical version of the element with the extra qualifiers on it.
1892 // This can recursively sink qualifiers through multiple levels of arrays.
1893 QualType NewEltTy = ATy->getElementType();
1894 if (AddrSpace)
Fariborz Jahanianb60352a2009-02-17 18:27:45 +00001895 NewEltTy = getAddrSpaceQualType(NewEltTy, AddrSpace);
Chris Lattnera1923f62008-08-04 07:31:14 +00001896 NewEltTy = NewEltTy.getWithAdditionalQualifiers(CVRQuals);
1897
1898 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
1899 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
1900 CAT->getSizeModifier(),
1901 CAT->getIndexTypeQualifier()));
1902 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
1903 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
1904 IAT->getSizeModifier(),
1905 IAT->getIndexTypeQualifier()));
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001906
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001907 if (const DependentSizedArrayType *DSAT
1908 = dyn_cast<DependentSizedArrayType>(ATy))
1909 return cast<ArrayType>(
1910 getDependentSizedArrayType(NewEltTy,
1911 DSAT->getSizeExpr(),
1912 DSAT->getSizeModifier(),
1913 DSAT->getIndexTypeQualifier()));
Chris Lattnera1923f62008-08-04 07:31:14 +00001914
Chris Lattnera1923f62008-08-04 07:31:14 +00001915 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
1916 return cast<ArrayType>(getVariableArrayType(NewEltTy, VAT->getSizeExpr(),
1917 VAT->getSizeModifier(),
1918 VAT->getIndexTypeQualifier()));
Chris Lattner3dae6f42008-04-06 22:41:35 +00001919}
1920
1921
Chris Lattner19eb97e2008-04-02 05:18:44 +00001922/// getArrayDecayedType - Return the properly qualified result of decaying the
1923/// specified array type to a pointer. This operation is non-trivial when
1924/// handling typedefs etc. The canonical type of "T" must be an array type,
1925/// this returns a pointer to a properly qualified element of the array.
1926///
1927/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
1928QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001929 // Get the element type with 'getAsArrayType' so that we don't lose any
1930 // typedefs in the element type of the array. This also handles propagation
1931 // of type qualifiers from the array type into the element type if present
1932 // (C99 6.7.3p8).
1933 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
1934 assert(PrettyArrayType && "Not an array type!");
Chris Lattner19eb97e2008-04-02 05:18:44 +00001935
Chris Lattnera1923f62008-08-04 07:31:14 +00001936 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattner19eb97e2008-04-02 05:18:44 +00001937
1938 // int x[restrict 4] -> int *restrict
Chris Lattnera1923f62008-08-04 07:31:14 +00001939 return PtrTy.getQualifiedType(PrettyArrayType->getIndexTypeQualifier());
Chris Lattner19eb97e2008-04-02 05:18:44 +00001940}
1941
Daniel Dunbar4a0b75c2009-01-05 22:14:37 +00001942QualType ASTContext::getBaseElementType(const VariableArrayType *VAT) {
Anders Carlsson76d19c82008-12-21 03:44:36 +00001943 QualType ElemTy = VAT->getElementType();
1944
1945 if (const VariableArrayType *VAT = getAsVariableArrayType(ElemTy))
1946 return getBaseElementType(VAT);
1947
1948 return ElemTy;
1949}
1950
Chris Lattner4b009652007-07-25 00:24:17 +00001951/// getFloatingRank - Return a relative rank for floating point types.
1952/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerd7135b42008-04-06 23:38:49 +00001953static FloatingRank getFloatingRank(QualType T) {
Christopher Lamb2a72bb32008-02-04 02:31:56 +00001954 if (const ComplexType *CT = T->getAsComplexType())
Chris Lattner4b009652007-07-25 00:24:17 +00001955 return getFloatingRank(CT->getElementType());
Chris Lattnerd7135b42008-04-06 23:38:49 +00001956
Daniel Dunbar4a0b75c2009-01-05 22:14:37 +00001957 assert(T->getAsBuiltinType() && "getFloatingRank(): not a floating type");
Christopher Lamb2a72bb32008-02-04 02:31:56 +00001958 switch (T->getAsBuiltinType()->getKind()) {
Chris Lattnerd7135b42008-04-06 23:38:49 +00001959 default: assert(0 && "getFloatingRank(): not a floating type");
Chris Lattner4b009652007-07-25 00:24:17 +00001960 case BuiltinType::Float: return FloatRank;
1961 case BuiltinType::Double: return DoubleRank;
1962 case BuiltinType::LongDouble: return LongDoubleRank;
1963 }
1964}
1965
Steve Narofffa0c4532007-08-27 01:41:48 +00001966/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
1967/// point or a complex type (based on typeDomain/typeSize).
1968/// 'typeDomain' is a real floating point or complex type.
1969/// 'typeSize' is a real floating point or complex type.
Chris Lattner7794ae22008-04-06 23:58:54 +00001970QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
1971 QualType Domain) const {
1972 FloatingRank EltRank = getFloatingRank(Size);
1973 if (Domain->isComplexType()) {
1974 switch (EltRank) {
Steve Narofffa0c4532007-08-27 01:41:48 +00001975 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Naroff3cf497f2007-08-27 01:27:54 +00001976 case FloatRank: return FloatComplexTy;
1977 case DoubleRank: return DoubleComplexTy;
1978 case LongDoubleRank: return LongDoubleComplexTy;
1979 }
Chris Lattner4b009652007-07-25 00:24:17 +00001980 }
Chris Lattner7794ae22008-04-06 23:58:54 +00001981
1982 assert(Domain->isRealFloatingType() && "Unknown domain!");
1983 switch (EltRank) {
1984 default: assert(0 && "getFloatingRank(): illegal value for rank");
1985 case FloatRank: return FloatTy;
1986 case DoubleRank: return DoubleTy;
1987 case LongDoubleRank: return LongDoubleTy;
Steve Naroff3cf497f2007-08-27 01:27:54 +00001988 }
Chris Lattner4b009652007-07-25 00:24:17 +00001989}
1990
Chris Lattner51285d82008-04-06 23:55:33 +00001991/// getFloatingTypeOrder - Compare the rank of the two specified floating
1992/// point types, ignoring the domain of the type (i.e. 'double' ==
1993/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
1994/// LHS < RHS, return -1.
Chris Lattnerd7135b42008-04-06 23:38:49 +00001995int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
1996 FloatingRank LHSR = getFloatingRank(LHS);
1997 FloatingRank RHSR = getFloatingRank(RHS);
1998
1999 if (LHSR == RHSR)
Steve Naroff45fc9822007-08-27 15:30:22 +00002000 return 0;
Chris Lattnerd7135b42008-04-06 23:38:49 +00002001 if (LHSR > RHSR)
Steve Naroff45fc9822007-08-27 15:30:22 +00002002 return 1;
2003 return -1;
Chris Lattner4b009652007-07-25 00:24:17 +00002004}
2005
Chris Lattnerc1b68db2008-04-06 22:59:24 +00002006/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2007/// routine will assert if passed a built-in type that isn't an integer or enum,
2008/// or if it is not canonicalized.
Eli Friedmanff3fcdf2009-02-13 02:31:07 +00002009unsigned ASTContext::getIntegerRank(Type *T) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +00002010 assert(T->isCanonical() && "T should be canonicalized");
Eli Friedmanff3fcdf2009-02-13 02:31:07 +00002011 if (EnumType* ET = dyn_cast<EnumType>(T))
2012 T = ET->getDecl()->getIntegerType().getTypePtr();
2013
2014 // There are two things which impact the integer rank: the width, and
2015 // the ordering of builtins. The builtin ordering is encoded in the
2016 // bottom three bits; the width is encoded in the bits above that.
Chris Lattnerc46fcdd2009-06-14 01:54:56 +00002017 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T))
Eli Friedmanff3fcdf2009-02-13 02:31:07 +00002018 return FWIT->getWidth() << 3;
Eli Friedmanff3fcdf2009-02-13 02:31:07 +00002019
Chris Lattnerc1b68db2008-04-06 22:59:24 +00002020 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner51285d82008-04-06 23:55:33 +00002021 default: assert(0 && "getIntegerRank(): not a built-in integer");
2022 case BuiltinType::Bool:
Eli Friedmanff3fcdf2009-02-13 02:31:07 +00002023 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner51285d82008-04-06 23:55:33 +00002024 case BuiltinType::Char_S:
2025 case BuiltinType::Char_U:
2026 case BuiltinType::SChar:
2027 case BuiltinType::UChar:
Eli Friedmanff3fcdf2009-02-13 02:31:07 +00002028 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner51285d82008-04-06 23:55:33 +00002029 case BuiltinType::Short:
2030 case BuiltinType::UShort:
Eli Friedmanff3fcdf2009-02-13 02:31:07 +00002031 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner51285d82008-04-06 23:55:33 +00002032 case BuiltinType::Int:
2033 case BuiltinType::UInt:
Eli Friedmanff3fcdf2009-02-13 02:31:07 +00002034 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner51285d82008-04-06 23:55:33 +00002035 case BuiltinType::Long:
2036 case BuiltinType::ULong:
Eli Friedmanff3fcdf2009-02-13 02:31:07 +00002037 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner51285d82008-04-06 23:55:33 +00002038 case BuiltinType::LongLong:
2039 case BuiltinType::ULongLong:
Eli Friedmanff3fcdf2009-02-13 02:31:07 +00002040 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner6cc7e412009-04-30 02:43:43 +00002041 case BuiltinType::Int128:
2042 case BuiltinType::UInt128:
2043 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerc1b68db2008-04-06 22:59:24 +00002044 }
2045}
2046
Chris Lattner51285d82008-04-06 23:55:33 +00002047/// getIntegerTypeOrder - Returns the highest ranked integer type:
2048/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
2049/// LHS < RHS, return -1.
2050int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +00002051 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2052 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner51285d82008-04-06 23:55:33 +00002053 if (LHSC == RHSC) return 0;
Chris Lattner4b009652007-07-25 00:24:17 +00002054
Chris Lattnerc1b68db2008-04-06 22:59:24 +00002055 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2056 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Chris Lattner4b009652007-07-25 00:24:17 +00002057
Chris Lattner51285d82008-04-06 23:55:33 +00002058 unsigned LHSRank = getIntegerRank(LHSC);
2059 unsigned RHSRank = getIntegerRank(RHSC);
Chris Lattner4b009652007-07-25 00:24:17 +00002060
Chris Lattner51285d82008-04-06 23:55:33 +00002061 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2062 if (LHSRank == RHSRank) return 0;
2063 return LHSRank > RHSRank ? 1 : -1;
2064 }
Chris Lattner4b009652007-07-25 00:24:17 +00002065
Chris Lattner51285d82008-04-06 23:55:33 +00002066 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2067 if (LHSUnsigned) {
2068 // If the unsigned [LHS] type is larger, return it.
2069 if (LHSRank >= RHSRank)
2070 return 1;
2071
2072 // If the signed type can represent all values of the unsigned type, it
2073 // wins. Because we are dealing with 2's complement and types that are
2074 // powers of two larger than each other, this is always safe.
2075 return -1;
2076 }
Chris Lattnerc1b68db2008-04-06 22:59:24 +00002077
Chris Lattner51285d82008-04-06 23:55:33 +00002078 // If the unsigned [RHS] type is larger, return it.
2079 if (RHSRank >= LHSRank)
2080 return -1;
2081
2082 // If the signed type can represent all values of the unsigned type, it
2083 // wins. Because we are dealing with 2's complement and types that are
2084 // powers of two larger than each other, this is always safe.
2085 return 1;
Chris Lattner4b009652007-07-25 00:24:17 +00002086}
Anders Carlssone7e7aa22007-08-17 05:31:46 +00002087
2088// getCFConstantStringType - Return the type used for constant CFStrings.
2089QualType ASTContext::getCFConstantStringType() {
2090 if (!CFConstantStringTypeDecl) {
Chris Lattnere4650482008-03-15 06:12:44 +00002091 CFConstantStringTypeDecl =
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002092 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
Ted Kremenek2c984042008-09-05 01:34:33 +00002093 &Idents.get("NSConstantString"));
Anders Carlssonbb2cf512007-11-19 00:25:30 +00002094 QualType FieldTypes[4];
Anders Carlssone7e7aa22007-08-17 05:31:46 +00002095
2096 // const int *isa;
2097 FieldTypes[0] = getPointerType(IntTy.getQualifiedType(QualType::Const));
Anders Carlssonbb2cf512007-11-19 00:25:30 +00002098 // int flags;
2099 FieldTypes[1] = IntTy;
Anders Carlssone7e7aa22007-08-17 05:31:46 +00002100 // const char *str;
Anders Carlssonbb2cf512007-11-19 00:25:30 +00002101 FieldTypes[2] = getPointerType(CharTy.getQualifiedType(QualType::Const));
Anders Carlssone7e7aa22007-08-17 05:31:46 +00002102 // long length;
Anders Carlssonbb2cf512007-11-19 00:25:30 +00002103 FieldTypes[3] = LongTy;
Douglas Gregor8acb7272008-12-11 16:49:14 +00002104
Anders Carlssone7e7aa22007-08-17 05:31:46 +00002105 // Create fields
Douglas Gregor8acb7272008-12-11 16:49:14 +00002106 for (unsigned i = 0; i < 4; ++i) {
2107 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
2108 SourceLocation(), 0,
2109 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002110 /*Mutable=*/false);
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002111 CFConstantStringTypeDecl->addDecl(*this, Field);
Douglas Gregor8acb7272008-12-11 16:49:14 +00002112 }
2113
2114 CFConstantStringTypeDecl->completeDefinition(*this);
Anders Carlssone7e7aa22007-08-17 05:31:46 +00002115 }
2116
2117 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif61ce98c2007-09-11 15:32:40 +00002118}
Anders Carlssonfb5b1e82007-10-11 01:00:40 +00002119
Douglas Gregorbb21d4b2009-04-23 22:29:11 +00002120void ASTContext::setCFConstantStringType(QualType T) {
2121 const RecordType *Rec = T->getAsRecordType();
2122 assert(Rec && "Invalid CFConstantStringType");
2123 CFConstantStringTypeDecl = Rec->getDecl();
2124}
2125
Anders Carlssonf58cac72008-08-30 19:34:46 +00002126QualType ASTContext::getObjCFastEnumerationStateType()
2127{
2128 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor8acb7272008-12-11 16:49:14 +00002129 ObjCFastEnumerationStateTypeDecl =
2130 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2131 &Idents.get("__objcFastEnumerationState"));
2132
Anders Carlssonf58cac72008-08-30 19:34:46 +00002133 QualType FieldTypes[] = {
2134 UnsignedLongTy,
2135 getPointerType(ObjCIdType),
2136 getPointerType(UnsignedLongTy),
2137 getConstantArrayType(UnsignedLongTy,
2138 llvm::APInt(32, 5), ArrayType::Normal, 0)
2139 };
2140
Douglas Gregor8acb7272008-12-11 16:49:14 +00002141 for (size_t i = 0; i < 4; ++i) {
2142 FieldDecl *Field = FieldDecl::Create(*this,
2143 ObjCFastEnumerationStateTypeDecl,
2144 SourceLocation(), 0,
2145 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002146 /*Mutable=*/false);
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002147 ObjCFastEnumerationStateTypeDecl->addDecl(*this, Field);
Douglas Gregor8acb7272008-12-11 16:49:14 +00002148 }
Anders Carlssonf58cac72008-08-30 19:34:46 +00002149
Douglas Gregor8acb7272008-12-11 16:49:14 +00002150 ObjCFastEnumerationStateTypeDecl->completeDefinition(*this);
Anders Carlssonf58cac72008-08-30 19:34:46 +00002151 }
2152
2153 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2154}
2155
Douglas Gregorbb21d4b2009-04-23 22:29:11 +00002156void ASTContext::setObjCFastEnumerationStateType(QualType T) {
2157 const RecordType *Rec = T->getAsRecordType();
2158 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
2159 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
2160}
2161
Anders Carlssone3f02572007-10-29 06:33:42 +00002162// This returns true if a type has been typedefed to BOOL:
2163// typedef <type> BOOL;
Chris Lattnercb034cb2007-10-30 20:27:44 +00002164static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone3f02572007-10-29 06:33:42 +00002165 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner85fb3842008-11-24 03:52:59 +00002166 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
2167 return II->isStr("BOOL");
Anders Carlsson36f07d82007-10-29 05:01:08 +00002168
2169 return false;
2170}
2171
Ted Kremenek42730c52008-01-07 19:49:32 +00002172/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002173/// purpose.
Ted Kremenek42730c52008-01-07 19:49:32 +00002174int ASTContext::getObjCEncodingTypeSize(QualType type) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002175 uint64_t sz = getTypeSize(type);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002176
2177 // Make all integer and enum types at least as large as an int
2178 if (sz > 0 && type->isIntegralType())
Chris Lattner8cd0e932008-03-05 18:54:05 +00002179 sz = std::max(sz, getTypeSize(IntTy));
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002180 // Treat arrays as pointers, since that's how they're passed in.
2181 else if (type->isArrayType())
Chris Lattner8cd0e932008-03-05 18:54:05 +00002182 sz = getTypeSize(VoidPtrTy);
2183 return sz / getTypeSize(CharTy);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002184}
2185
Ted Kremenek42730c52008-01-07 19:49:32 +00002186/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002187/// declaration.
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002188void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnerae430292008-11-19 07:24:05 +00002189 std::string& S) {
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002190 // FIXME: This is not very efficient.
Fariborz Jahanian65e7eb52007-11-01 17:18:37 +00002191 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremenek42730c52008-01-07 19:49:32 +00002192 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002193 // Encode result type.
Daniel Dunbarc9197cd2008-10-17 20:21:44 +00002194 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002195 // Compute size of all parameters.
2196 // Start with computing size of a pointer in number of bytes.
2197 // FIXME: There might(should) be a better way of doing this computation!
2198 SourceLocation Loc;
Chris Lattner8cd0e932008-03-05 18:54:05 +00002199 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002200 // The first two arguments (self and _cmd) are pointers; account for
2201 // their size.
2202 int ParmOffset = 2 * PtrSize;
Chris Lattner5c6b2c62009-02-20 18:43:26 +00002203 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2204 E = Decl->param_end(); PI != E; ++PI) {
2205 QualType PType = (*PI)->getType();
2206 int sz = getObjCEncodingTypeSize(PType);
Ted Kremenek42730c52008-01-07 19:49:32 +00002207 assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002208 ParmOffset += sz;
2209 }
2210 S += llvm::utostr(ParmOffset);
2211 S += "@0:";
2212 S += llvm::utostr(PtrSize);
2213
2214 // Argument types.
2215 ParmOffset = 2 * PtrSize;
Chris Lattner5c6b2c62009-02-20 18:43:26 +00002216 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2217 E = Decl->param_end(); PI != E; ++PI) {
2218 ParmVarDecl *PVDecl = *PI;
Fariborz Jahaniane26cb432008-12-20 23:29:59 +00002219 QualType PType = PVDecl->getOriginalType();
2220 if (const ArrayType *AT =
Steve Naroff78380fb2009-04-14 00:03:58 +00002221 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
2222 // Use array's original type only if it has known number of
2223 // elements.
Steve Naroff6777bf32009-04-14 00:40:09 +00002224 if (!isa<ConstantArrayType>(AT))
Steve Naroff78380fb2009-04-14 00:03:58 +00002225 PType = PVDecl->getType();
2226 } else if (PType->isFunctionType())
2227 PType = PVDecl->getType();
Fariborz Jahanian65e7eb52007-11-01 17:18:37 +00002228 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002229 // 'in', 'inout', etc.
Fariborz Jahaniane26cb432008-12-20 23:29:59 +00002230 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbarc9197cd2008-10-17 20:21:44 +00002231 getObjCEncodingForType(PType, S);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002232 S += llvm::utostr(ParmOffset);
Ted Kremenek42730c52008-01-07 19:49:32 +00002233 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002234 }
2235}
2236
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002237/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian501ef5c2009-01-20 20:04:12 +00002238/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002239/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
2240/// NULL when getting encodings for protocol properties.
Fariborz Jahanian501ef5c2009-01-20 20:04:12 +00002241/// Property attributes are stored as a comma-delimited C string. The simple
2242/// attributes readonly and bycopy are encoded as single characters. The
2243/// parametrized attributes, getter=name, setter=name, and ivar=name, are
2244/// encoded as single characters, followed by an identifier. Property types
2245/// are also encoded as a parametrized attribute. The characters used to encode
2246/// these attributes are defined by the following enumeration:
2247/// @code
2248/// enum PropertyAttributes {
2249/// kPropertyReadOnly = 'R', // property is read-only.
2250/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
2251/// kPropertyByref = '&', // property is a reference to the value last assigned
2252/// kPropertyDynamic = 'D', // property is dynamic
2253/// kPropertyGetter = 'G', // followed by getter selector name
2254/// kPropertySetter = 'S', // followed by setter selector name
2255/// kPropertyInstanceVariable = 'V' // followed by instance variable name
2256/// kPropertyType = 't' // followed by old-style type encoding.
2257/// kPropertyWeak = 'W' // 'weak' property
2258/// kPropertyStrong = 'P' // property GC'able
2259/// kPropertyNonAtomic = 'N' // property non-atomic
2260/// };
2261/// @endcode
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002262void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
2263 const Decl *Container,
Chris Lattnerae430292008-11-19 07:24:05 +00002264 std::string& S) {
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002265 // Collect information from the property implementation decl(s).
2266 bool Dynamic = false;
2267 ObjCPropertyImplDecl *SynthesizePID = 0;
2268
2269 // FIXME: Duplicated code due to poor abstraction.
2270 if (Container) {
2271 if (const ObjCCategoryImplDecl *CID =
2272 dyn_cast<ObjCCategoryImplDecl>(Container)) {
2273 for (ObjCCategoryImplDecl::propimpl_iterator
Douglas Gregorcd19b572009-04-23 01:02:12 +00002274 i = CID->propimpl_begin(*this), e = CID->propimpl_end(*this);
2275 i != e; ++i) {
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002276 ObjCPropertyImplDecl *PID = *i;
2277 if (PID->getPropertyDecl() == PD) {
2278 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2279 Dynamic = true;
2280 } else {
2281 SynthesizePID = PID;
2282 }
2283 }
2284 }
2285 } else {
Chris Lattner2fda0ed2008-10-05 17:34:18 +00002286 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002287 for (ObjCCategoryImplDecl::propimpl_iterator
Douglas Gregorcd19b572009-04-23 01:02:12 +00002288 i = OID->propimpl_begin(*this), e = OID->propimpl_end(*this);
2289 i != e; ++i) {
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002290 ObjCPropertyImplDecl *PID = *i;
2291 if (PID->getPropertyDecl() == PD) {
2292 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2293 Dynamic = true;
2294 } else {
2295 SynthesizePID = PID;
2296 }
2297 }
2298 }
2299 }
2300 }
2301
2302 // FIXME: This is not very efficient.
2303 S = "T";
2304
2305 // Encode result type.
Fariborz Jahanian892d5db2009-01-20 19:14:18 +00002306 // GCC has some special rules regarding encoding of properties which
2307 // closely resembles encoding of ivars.
Daniel Dunbar701c8502009-04-20 06:37:24 +00002308 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian892d5db2009-01-20 19:14:18 +00002309 true /* outermost type */,
2310 true /* encoding for property */);
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002311
2312 if (PD->isReadOnly()) {
2313 S += ",R";
2314 } else {
2315 switch (PD->getSetterKind()) {
2316 case ObjCPropertyDecl::Assign: break;
2317 case ObjCPropertyDecl::Copy: S += ",C"; break;
2318 case ObjCPropertyDecl::Retain: S += ",&"; break;
2319 }
2320 }
2321
2322 // It really isn't clear at all what this means, since properties
2323 // are "dynamic by default".
2324 if (Dynamic)
2325 S += ",D";
2326
Fariborz Jahanian892d5db2009-01-20 19:14:18 +00002327 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
2328 S += ",N";
2329
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002330 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
2331 S += ",G";
Chris Lattner3a8f2942008-11-24 03:33:13 +00002332 S += PD->getGetterName().getAsString();
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002333 }
2334
2335 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
2336 S += ",S";
Chris Lattner3a8f2942008-11-24 03:33:13 +00002337 S += PD->getSetterName().getAsString();
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002338 }
2339
2340 if (SynthesizePID) {
2341 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
2342 S += ",V";
Chris Lattner6c5ec622008-11-24 04:00:27 +00002343 S += OID->getNameAsString();
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002344 }
2345
2346 // FIXME: OBJCGC: weak & strong
2347}
2348
Fariborz Jahaniane07d9ec2008-12-23 19:56:47 +00002349/// getLegacyIntegralTypeEncoding -
2350/// Another legacy compatibility encoding: 32-bit longs are encoded as
Fariborz Jahanian89155952009-02-11 23:59:18 +00002351/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniane07d9ec2008-12-23 19:56:47 +00002352/// 'i' or 'I' instead if encoding a struct field, or a pointer!
2353///
2354void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
2355 if (dyn_cast<TypedefType>(PointeeTy.getTypePtr())) {
2356 if (const BuiltinType *BT = PointeeTy->getAsBuiltinType()) {
Fariborz Jahanian89155952009-02-11 23:59:18 +00002357 if (BT->getKind() == BuiltinType::ULong &&
2358 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniane07d9ec2008-12-23 19:56:47 +00002359 PointeeTy = UnsignedIntTy;
Fariborz Jahanian89155952009-02-11 23:59:18 +00002360 else
2361 if (BT->getKind() == BuiltinType::Long &&
2362 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniane07d9ec2008-12-23 19:56:47 +00002363 PointeeTy = IntTy;
2364 }
2365 }
2366}
2367
Fariborz Jahanian248db262008-01-22 22:44:46 +00002368void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar701c8502009-04-20 06:37:24 +00002369 const FieldDecl *Field) {
Daniel Dunbarf8cfe562008-10-17 07:30:50 +00002370 // We follow the behavior of gcc, expanding structures which are
2371 // directly pointed to, and expanding embedded structures. Note that
2372 // these rules are sufficient to prevent recursive encoding of the
2373 // same type.
Fariborz Jahanian89ed86b2008-12-22 23:22:27 +00002374 getObjCEncodingForTypeImpl(T, S, true, true, Field,
2375 true /* outermost type */);
Daniel Dunbarf8cfe562008-10-17 07:30:50 +00002376}
2377
Fariborz Jahaniand1361952009-01-13 01:18:13 +00002378static void EncodeBitField(const ASTContext *Context, std::string& S,
Daniel Dunbar701c8502009-04-20 06:37:24 +00002379 const FieldDecl *FD) {
Fariborz Jahaniand1361952009-01-13 01:18:13 +00002380 const Expr *E = FD->getBitWidth();
2381 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
2382 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Eli Friedman5255e7a2009-04-26 19:19:15 +00002383 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahaniand1361952009-01-13 01:18:13 +00002384 S += 'b';
2385 S += llvm::utostr(N);
2386}
2387
Daniel Dunbarf8cfe562008-10-17 07:30:50 +00002388void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
2389 bool ExpandPointedToStructures,
2390 bool ExpandStructures,
Daniel Dunbar701c8502009-04-20 06:37:24 +00002391 const FieldDecl *FD,
Fariborz Jahanian892d5db2009-01-20 19:14:18 +00002392 bool OutermostType,
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002393 bool EncodingProperty) {
Anders Carlssone3f02572007-10-29 06:33:42 +00002394 if (const BuiltinType *BT = T->getAsBuiltinType()) {
Fariborz Jahanian0cd547f2008-12-19 23:34:38 +00002395 if (FD && FD->isBitField()) {
Fariborz Jahaniand1361952009-01-13 01:18:13 +00002396 EncodeBitField(this, S, FD);
Anders Carlsson36f07d82007-10-29 05:01:08 +00002397 }
Fariborz Jahanian0cd547f2008-12-19 23:34:38 +00002398 else {
2399 char encoding;
2400 switch (BT->getKind()) {
2401 default: assert(0 && "Unhandled builtin type kind");
2402 case BuiltinType::Void: encoding = 'v'; break;
2403 case BuiltinType::Bool: encoding = 'B'; break;
2404 case BuiltinType::Char_U:
2405 case BuiltinType::UChar: encoding = 'C'; break;
2406 case BuiltinType::UShort: encoding = 'S'; break;
2407 case BuiltinType::UInt: encoding = 'I'; break;
Fariborz Jahanianebd95752009-02-11 22:31:45 +00002408 case BuiltinType::ULong:
2409 encoding =
2410 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
2411 break;
Chris Lattner6cc7e412009-04-30 02:43:43 +00002412 case BuiltinType::UInt128: encoding = 'T'; break;
Fariborz Jahanian0cd547f2008-12-19 23:34:38 +00002413 case BuiltinType::ULongLong: encoding = 'Q'; break;
2414 case BuiltinType::Char_S:
2415 case BuiltinType::SChar: encoding = 'c'; break;
2416 case BuiltinType::Short: encoding = 's'; break;
2417 case BuiltinType::Int: encoding = 'i'; break;
Fariborz Jahanianebd95752009-02-11 22:31:45 +00002418 case BuiltinType::Long:
2419 encoding =
2420 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
2421 break;
Fariborz Jahanian0cd547f2008-12-19 23:34:38 +00002422 case BuiltinType::LongLong: encoding = 'q'; break;
Chris Lattner6cc7e412009-04-30 02:43:43 +00002423 case BuiltinType::Int128: encoding = 't'; break;
Fariborz Jahanian0cd547f2008-12-19 23:34:38 +00002424 case BuiltinType::Float: encoding = 'f'; break;
2425 case BuiltinType::Double: encoding = 'd'; break;
2426 case BuiltinType::LongDouble: encoding = 'd'; break;
2427 }
Anders Carlsson36f07d82007-10-29 05:01:08 +00002428
Fariborz Jahanian0cd547f2008-12-19 23:34:38 +00002429 S += encoding;
2430 }
Anders Carlsson70e16dd2009-04-09 21:55:45 +00002431 } else if (const ComplexType *CT = T->getAsComplexType()) {
2432 S += 'j';
2433 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
2434 false);
2435 } else if (T->isObjCQualifiedIdType()) {
Fariborz Jahanian892d5db2009-01-20 19:14:18 +00002436 getObjCEncodingForTypeImpl(getObjCIdType(), S,
2437 ExpandPointedToStructures,
2438 ExpandStructures, FD);
2439 if (FD || EncodingProperty) {
2440 // Note that we do extended encoding of protocol qualifer list
2441 // Only when doing ivar or property encoding.
Steve Naroffc75c1a82009-06-17 22:40:22 +00002442 const ObjCObjectPointerType *QIDT = T->getAsObjCQualifiedIdType();
Fariborz Jahanian892d5db2009-01-20 19:14:18 +00002443 S += '"';
Steve Naroffc75c1a82009-06-17 22:40:22 +00002444 for (ObjCObjectPointerType::qual_iterator I = QIDT->qual_begin(),
Steve Naroff83418522009-05-27 16:21:00 +00002445 E = QIDT->qual_end(); I != E; ++I) {
Fariborz Jahanian892d5db2009-01-20 19:14:18 +00002446 S += '<';
Steve Naroff83418522009-05-27 16:21:00 +00002447 S += (*I)->getNameAsString();
Fariborz Jahanian892d5db2009-01-20 19:14:18 +00002448 S += '>';
2449 }
2450 S += '"';
2451 }
2452 return;
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00002453 }
2454 else if (const PointerType *PT = T->getAsPointerType()) {
Anders Carlsson36f07d82007-10-29 05:01:08 +00002455 QualType PointeeTy = PT->getPointeeType();
Fariborz Jahaniane07d9ec2008-12-23 19:56:47 +00002456 bool isReadOnly = false;
2457 // For historical/compatibility reasons, the read-only qualifier of the
2458 // pointee gets emitted _before_ the '^'. The read-only qualifier of
2459 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
2460 // Also, do not emit the 'r' for anything but the outermost type!
2461 if (dyn_cast<TypedefType>(T.getTypePtr())) {
2462 if (OutermostType && T.isConstQualified()) {
2463 isReadOnly = true;
2464 S += 'r';
2465 }
2466 }
2467 else if (OutermostType) {
2468 QualType P = PointeeTy;
2469 while (P->getAsPointerType())
2470 P = P->getAsPointerType()->getPointeeType();
2471 if (P.isConstQualified()) {
2472 isReadOnly = true;
2473 S += 'r';
2474 }
2475 }
2476 if (isReadOnly) {
2477 // Another legacy compatibility encoding. Some ObjC qualifier and type
2478 // combinations need to be rearranged.
2479 // Rewrite "in const" from "nr" to "rn"
2480 const char * s = S.c_str();
2481 int len = S.length();
2482 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
2483 std::string replace = "rn";
2484 S.replace(S.end()-2, S.end(), replace);
2485 }
2486 }
Steve Naroff17c03822009-02-12 17:52:19 +00002487 if (isObjCIdStructType(PointeeTy)) {
Fariborz Jahanian80faffa2007-10-30 17:06:23 +00002488 S += '@';
2489 return;
Fariborz Jahanianc8679472008-12-19 00:14:49 +00002490 }
2491 else if (PointeeTy->isObjCInterfaceType()) {
Fariborz Jahanian94675042009-02-16 21:41:04 +00002492 if (!EncodingProperty &&
Fariborz Jahanian6bc0f2d2009-02-16 22:09:26 +00002493 isa<TypedefType>(PointeeTy.getTypePtr())) {
Fariborz Jahaniand3498aa2008-12-23 21:30:15 +00002494 // Another historical/compatibility reason.
2495 // We encode the underlying type which comes out as
2496 // {...};
2497 S += '^';
2498 getObjCEncodingForTypeImpl(PointeeTy, S,
2499 false, ExpandPointedToStructures,
2500 NULL);
2501 return;
2502 }
Fariborz Jahanianc8679472008-12-19 00:14:49 +00002503 S += '@';
Fariborz Jahanian892d5db2009-01-20 19:14:18 +00002504 if (FD || EncodingProperty) {
Fariborz Jahanianc69da272009-02-21 18:23:24 +00002505 const ObjCInterfaceType *OIT =
2506 PointeeTy.getUnqualifiedType()->getAsObjCInterfaceType();
Fariborz Jahanian892d5db2009-01-20 19:14:18 +00002507 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian320ac422008-12-20 19:17:01 +00002508 S += '"';
2509 S += OI->getNameAsCString();
Steve Naroff83418522009-05-27 16:21:00 +00002510 for (ObjCInterfaceType::qual_iterator I = OIT->qual_begin(),
2511 E = OIT->qual_end(); I != E; ++I) {
Fariborz Jahanian892d5db2009-01-20 19:14:18 +00002512 S += '<';
Steve Naroff83418522009-05-27 16:21:00 +00002513 S += (*I)->getNameAsString();
Fariborz Jahanian892d5db2009-01-20 19:14:18 +00002514 S += '>';
2515 }
Fariborz Jahanian320ac422008-12-20 19:17:01 +00002516 S += '"';
2517 }
Fariborz Jahanianc8679472008-12-19 00:14:49 +00002518 return;
Steve Naroff17c03822009-02-12 17:52:19 +00002519 } else if (isObjCClassStructType(PointeeTy)) {
Anders Carlsson7f23e3d2007-10-31 02:53:19 +00002520 S += '#';
2521 return;
Ted Kremenek42730c52008-01-07 19:49:32 +00002522 } else if (isObjCSelType(PointeeTy)) {
Anders Carlsson7f23e3d2007-10-31 02:53:19 +00002523 S += ':';
2524 return;
Fariborz Jahanian80faffa2007-10-30 17:06:23 +00002525 }
Anders Carlsson36f07d82007-10-29 05:01:08 +00002526
2527 if (PointeeTy->isCharType()) {
2528 // char pointer types should be encoded as '*' unless it is a
2529 // type that has been typedef'd to 'BOOL'.
Anders Carlssone3f02572007-10-29 06:33:42 +00002530 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson36f07d82007-10-29 05:01:08 +00002531 S += '*';
2532 return;
2533 }
2534 }
2535
2536 S += '^';
Fariborz Jahaniane07d9ec2008-12-23 19:56:47 +00002537 getLegacyIntegralTypeEncoding(PointeeTy);
2538
2539 getObjCEncodingForTypeImpl(PointeeTy, S,
Daniel Dunbaraa913102008-10-17 16:17:37 +00002540 false, ExpandPointedToStructures,
Fariborz Jahanian0cd547f2008-12-19 23:34:38 +00002541 NULL);
Chris Lattnera1923f62008-08-04 07:31:14 +00002542 } else if (const ArrayType *AT =
2543 // Ignore type qualifiers etc.
2544 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson858c64d2009-02-22 01:38:57 +00002545 if (isa<IncompleteArrayType>(AT)) {
2546 // Incomplete arrays are encoded as a pointer to the array element.
2547 S += '^';
2548
2549 getObjCEncodingForTypeImpl(AT->getElementType(), S,
2550 false, ExpandStructures, FD);
2551 } else {
2552 S += '[';
Anders Carlsson36f07d82007-10-29 05:01:08 +00002553
Anders Carlsson858c64d2009-02-22 01:38:57 +00002554 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
2555 S += llvm::utostr(CAT->getSize().getZExtValue());
2556 else {
2557 //Variable length arrays are encoded as a regular array with 0 elements.
2558 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
2559 S += '0';
2560 }
Anders Carlsson36f07d82007-10-29 05:01:08 +00002561
Anders Carlsson858c64d2009-02-22 01:38:57 +00002562 getObjCEncodingForTypeImpl(AT->getElementType(), S,
2563 false, ExpandStructures, FD);
2564 S += ']';
2565 }
Anders Carlsson5695bb72007-10-30 00:06:20 +00002566 } else if (T->getAsFunctionType()) {
2567 S += '?';
Fariborz Jahanianc8ba2bd2007-11-13 23:21:38 +00002568 } else if (const RecordType *RTy = T->getAsRecordType()) {
Daniel Dunbarf8cfe562008-10-17 07:30:50 +00002569 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbaraa913102008-10-17 16:17:37 +00002570 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar146b2d02008-10-17 06:22:57 +00002571 // Anonymous structures print as '?'
2572 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
2573 S += II->getName();
2574 } else {
2575 S += '?';
2576 }
Daniel Dunbarc9197cd2008-10-17 20:21:44 +00002577 if (ExpandStructures) {
Fariborz Jahanian248db262008-01-22 22:44:46 +00002578 S += '=';
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002579 for (RecordDecl::field_iterator Field = RDecl->field_begin(*this),
2580 FieldEnd = RDecl->field_end(*this);
Douglas Gregor8acb7272008-12-11 16:49:14 +00002581 Field != FieldEnd; ++Field) {
Fariborz Jahanian0cd547f2008-12-19 23:34:38 +00002582 if (FD) {
Daniel Dunbaraa913102008-10-17 16:17:37 +00002583 S += '"';
Douglas Gregor8acb7272008-12-11 16:49:14 +00002584 S += Field->getNameAsString();
Daniel Dunbaraa913102008-10-17 16:17:37 +00002585 S += '"';
2586 }
2587
2588 // Special case bit-fields.
Fariborz Jahanian0cd547f2008-12-19 23:34:38 +00002589 if (Field->isBitField()) {
2590 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
2591 (*Field));
Daniel Dunbaraa913102008-10-17 16:17:37 +00002592 } else {
Fariborz Jahaniane07d9ec2008-12-23 19:56:47 +00002593 QualType qt = Field->getType();
2594 getLegacyIntegralTypeEncoding(qt);
2595 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian0cd547f2008-12-19 23:34:38 +00002596 FD);
Daniel Dunbaraa913102008-10-17 16:17:37 +00002597 }
Fariborz Jahanian248db262008-01-22 22:44:46 +00002598 }
Fariborz Jahanianc8ba2bd2007-11-13 23:21:38 +00002599 }
Daniel Dunbaraa913102008-10-17 16:17:37 +00002600 S += RDecl->isUnion() ? ')' : '}';
Steve Naroff49af3f32007-12-12 22:30:11 +00002601 } else if (T->isEnumeralType()) {
Fariborz Jahaniand1361952009-01-13 01:18:13 +00002602 if (FD && FD->isBitField())
2603 EncodeBitField(this, S, FD);
2604 else
2605 S += 'i';
Steve Naroff62f09f52008-09-24 15:05:44 +00002606 } else if (T->isBlockPointerType()) {
Steve Naroff725e0662009-02-02 18:24:29 +00002607 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Fariborz Jahanian0cd547f2008-12-19 23:34:38 +00002608 } else if (T->isObjCInterfaceType()) {
2609 // @encode(class_name)
2610 ObjCInterfaceDecl *OI = T->getAsObjCInterfaceType()->getDecl();
2611 S += '{';
2612 const IdentifierInfo *II = OI->getIdentifier();
2613 S += II->getName();
2614 S += '=';
Chris Lattner9329cf52009-03-31 08:48:01 +00002615 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian0cd547f2008-12-19 23:34:38 +00002616 CollectObjCIvars(OI, RecFields);
Chris Lattner9329cf52009-03-31 08:48:01 +00002617 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian0cd547f2008-12-19 23:34:38 +00002618 if (RecFields[i]->isBitField())
2619 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2620 RecFields[i]);
2621 else
2622 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2623 FD);
2624 }
2625 S += '}';
2626 }
2627 else
Steve Naroff53b6f4c2008-01-30 19:17:43 +00002628 assert(0 && "@encode for type not implemented!");
Anders Carlsson36f07d82007-10-29 05:01:08 +00002629}
2630
Ted Kremenek42730c52008-01-07 19:49:32 +00002631void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanian65e7eb52007-11-01 17:18:37 +00002632 std::string& S) const {
2633 if (QT & Decl::OBJC_TQ_In)
2634 S += 'n';
2635 if (QT & Decl::OBJC_TQ_Inout)
2636 S += 'N';
2637 if (QT & Decl::OBJC_TQ_Out)
2638 S += 'o';
2639 if (QT & Decl::OBJC_TQ_Bycopy)
2640 S += 'O';
2641 if (QT & Decl::OBJC_TQ_Byref)
2642 S += 'R';
2643 if (QT & Decl::OBJC_TQ_Oneway)
2644 S += 'V';
2645}
2646
Anders Carlssonfb5b1e82007-10-11 01:00:40 +00002647void ASTContext::setBuiltinVaListType(QualType T)
2648{
2649 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
2650
2651 BuiltinVaListType = T;
2652}
2653
Douglas Gregorbb21d4b2009-04-23 22:29:11 +00002654void ASTContext::setObjCIdType(QualType T)
Steve Naroff9d12c902007-10-15 14:41:52 +00002655{
Douglas Gregorbb21d4b2009-04-23 22:29:11 +00002656 ObjCIdType = T;
2657
2658 const TypedefType *TT = T->getAsTypedefType();
2659 if (!TT)
2660 return;
2661
2662 TypedefDecl *TD = TT->getDecl();
Steve Naroff9d12c902007-10-15 14:41:52 +00002663
2664 // typedef struct objc_object *id;
2665 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
Fariborz Jahaniande939672009-01-16 19:58:32 +00002666 // User error - caller will issue diagnostics.
2667 if (!ptr)
2668 return;
Steve Naroff9d12c902007-10-15 14:41:52 +00002669 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
Fariborz Jahaniande939672009-01-16 19:58:32 +00002670 // User error - caller will issue diagnostics.
2671 if (!rec)
2672 return;
Steve Naroff9d12c902007-10-15 14:41:52 +00002673 IdStructType = rec;
2674}
2675
Douglas Gregorbb21d4b2009-04-23 22:29:11 +00002676void ASTContext::setObjCSelType(QualType T)
Fariborz Jahanianf807c202007-10-16 20:40:23 +00002677{
Douglas Gregorbb21d4b2009-04-23 22:29:11 +00002678 ObjCSelType = T;
2679
2680 const TypedefType *TT = T->getAsTypedefType();
2681 if (!TT)
2682 return;
2683 TypedefDecl *TD = TT->getDecl();
Fariborz Jahanianf807c202007-10-16 20:40:23 +00002684
2685 // typedef struct objc_selector *SEL;
2686 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
Fariborz Jahaniande939672009-01-16 19:58:32 +00002687 if (!ptr)
2688 return;
Fariborz Jahanianf807c202007-10-16 20:40:23 +00002689 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
Fariborz Jahaniande939672009-01-16 19:58:32 +00002690 if (!rec)
2691 return;
Fariborz Jahanianf807c202007-10-16 20:40:23 +00002692 SelStructType = rec;
2693}
2694
Ted Kremenek42730c52008-01-07 19:49:32 +00002695void ASTContext::setObjCProtoType(QualType QT)
Fariborz Jahanianb391e6e2007-10-17 16:58:11 +00002696{
Ted Kremenek42730c52008-01-07 19:49:32 +00002697 ObjCProtoType = QT;
Fariborz Jahanianb391e6e2007-10-17 16:58:11 +00002698}
2699
Douglas Gregorbb21d4b2009-04-23 22:29:11 +00002700void ASTContext::setObjCClassType(QualType T)
Anders Carlsson7f23e3d2007-10-31 02:53:19 +00002701{
Douglas Gregorbb21d4b2009-04-23 22:29:11 +00002702 ObjCClassType = T;
2703
2704 const TypedefType *TT = T->getAsTypedefType();
2705 if (!TT)
2706 return;
2707 TypedefDecl *TD = TT->getDecl();
Anders Carlsson7f23e3d2007-10-31 02:53:19 +00002708
2709 // typedef struct objc_class *Class;
2710 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
2711 assert(ptr && "'Class' incorrectly typed");
2712 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
2713 assert(rec && "'Class' incorrectly typed");
2714 ClassStructType = rec;
2715}
2716
Ted Kremenek42730c52008-01-07 19:49:32 +00002717void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
2718 assert(ObjCConstantStringType.isNull() &&
Steve Narofff2e30312007-10-15 23:35:17 +00002719 "'NSConstantString' type already set!");
2720
Ted Kremenek42730c52008-01-07 19:49:32 +00002721 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff2e30312007-10-15 23:35:17 +00002722}
2723
Douglas Gregordd13e842009-03-30 22:58:21 +00002724/// \brief Retrieve the template name that represents a qualified
2725/// template name such as \c std::vector.
2726TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
2727 bool TemplateKeyword,
2728 TemplateDecl *Template) {
2729 llvm::FoldingSetNodeID ID;
2730 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
2731
2732 void *InsertPos = 0;
2733 QualifiedTemplateName *QTN =
2734 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
2735 if (!QTN) {
2736 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
2737 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
2738 }
2739
2740 return TemplateName(QTN);
2741}
2742
2743/// \brief Retrieve the template name that represents a dependent
2744/// template name such as \c MetaFun::template apply.
2745TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
2746 const IdentifierInfo *Name) {
2747 assert(NNS->isDependent() && "Nested name specifier must be dependent");
2748
2749 llvm::FoldingSetNodeID ID;
2750 DependentTemplateName::Profile(ID, NNS, Name);
2751
2752 void *InsertPos = 0;
2753 DependentTemplateName *QTN =
2754 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
2755
2756 if (QTN)
2757 return TemplateName(QTN);
2758
2759 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2760 if (CanonNNS == NNS) {
2761 QTN = new (*this,4) DependentTemplateName(NNS, Name);
2762 } else {
2763 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
2764 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
2765 }
2766
2767 DependentTemplateNames.InsertNode(QTN, InsertPos);
2768 return TemplateName(QTN);
2769}
2770
Douglas Gregorc6507e42008-11-03 14:12:49 +00002771/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorbb66b412008-11-03 15:57:00 +00002772/// TargetInfo, produce the corresponding type. The unsigned @p Type
2773/// is actually a value of type @c TargetInfo::IntType.
2774QualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorc6507e42008-11-03 14:12:49 +00002775 switch (Type) {
2776 case TargetInfo::NoInt: return QualType();
2777 case TargetInfo::SignedShort: return ShortTy;
2778 case TargetInfo::UnsignedShort: return UnsignedShortTy;
2779 case TargetInfo::SignedInt: return IntTy;
2780 case TargetInfo::UnsignedInt: return UnsignedIntTy;
2781 case TargetInfo::SignedLong: return LongTy;
2782 case TargetInfo::UnsignedLong: return UnsignedLongTy;
2783 case TargetInfo::SignedLongLong: return LongLongTy;
2784 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
2785 }
2786
2787 assert(false && "Unhandled TargetInfo::IntType value");
Daniel Dunbar7b0dcc22008-11-11 01:16:00 +00002788 return QualType();
Douglas Gregorc6507e42008-11-03 14:12:49 +00002789}
Ted Kremenek118930e2008-07-24 23:58:27 +00002790
2791//===----------------------------------------------------------------------===//
2792// Type Predicates.
2793//===----------------------------------------------------------------------===//
2794
Fariborz Jahanian82f54962009-01-13 23:34:40 +00002795/// isObjCNSObjectType - Return true if this is an NSObject object using
2796/// NSObject attribute on a c-style pointer type.
2797/// FIXME - Make it work directly on types.
2798///
2799bool ASTContext::isObjCNSObjectType(QualType Ty) const {
2800 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
2801 if (TypedefDecl *TD = TDT->getDecl())
Douglas Gregor98da6ae2009-06-18 16:11:24 +00002802 if (TD->getAttr<ObjCNSObjectAttr>(*const_cast<ASTContext*>(this)))
Fariborz Jahanian82f54962009-01-13 23:34:40 +00002803 return true;
2804 }
2805 return false;
2806}
2807
Ted Kremenek118930e2008-07-24 23:58:27 +00002808/// isObjCObjectPointerType - Returns true if type is an Objective-C pointer
2809/// to an object type. This includes "id" and "Class" (two 'special' pointers
2810/// to struct), Interface* (pointer to ObjCInterfaceType) and id<P> (qualified
2811/// ID type).
2812bool ASTContext::isObjCObjectPointerType(QualType Ty) const {
Steve Naroff6805fc42009-02-23 18:36:16 +00002813 if (Ty->isObjCQualifiedIdType())
Ted Kremenek118930e2008-07-24 23:58:27 +00002814 return true;
2815
Steve Naroffd9e00802008-10-21 18:24:04 +00002816 // Blocks are objects.
2817 if (Ty->isBlockPointerType())
2818 return true;
2819
2820 // All other object types are pointers.
Chris Lattnera008d172009-04-12 23:51:02 +00002821 const PointerType *PT = Ty->getAsPointerType();
2822 if (PT == 0)
Ted Kremenek118930e2008-07-24 23:58:27 +00002823 return false;
2824
Chris Lattnera008d172009-04-12 23:51:02 +00002825 // If this a pointer to an interface (e.g. NSString*), it is ok.
2826 if (PT->getPointeeType()->isObjCInterfaceType() ||
2827 // If is has NSObject attribute, OK as well.
2828 isObjCNSObjectType(Ty))
2829 return true;
2830
Ted Kremenek118930e2008-07-24 23:58:27 +00002831 // Check to see if this is 'id' or 'Class', both of which are typedefs for
2832 // pointer types. This looks for the typedef specifically, not for the
Chris Lattnera008d172009-04-12 23:51:02 +00002833 // underlying type. Iteratively strip off typedefs so that we can handle
2834 // typedefs of typedefs.
2835 while (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
2836 if (Ty.getUnqualifiedType() == getObjCIdType() ||
2837 Ty.getUnqualifiedType() == getObjCClassType())
2838 return true;
2839
2840 Ty = TDT->getDecl()->getUnderlyingType();
2841 }
Ted Kremenek118930e2008-07-24 23:58:27 +00002842
Chris Lattnera008d172009-04-12 23:51:02 +00002843 return false;
Ted Kremenek118930e2008-07-24 23:58:27 +00002844}
2845
Fariborz Jahanianb8ca6ff2009-02-18 21:49:28 +00002846/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
2847/// garbage collection attribute.
2848///
2849QualType::GCAttrTypes ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
Chris Lattner18b5a9a2009-02-18 22:53:11 +00002850 QualType::GCAttrTypes GCAttrs = QualType::GCNone;
Fariborz Jahanianb8ca6ff2009-02-18 21:49:28 +00002851 if (getLangOptions().ObjC1 &&
2852 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattner18b5a9a2009-02-18 22:53:11 +00002853 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanianb8ca6ff2009-02-18 21:49:28 +00002854 // Default behavious under objective-c's gc is for objective-c pointers
Fariborz Jahanianbbd4ca92009-02-19 23:36:06 +00002855 // (or pointers to them) be treated as though they were declared
2856 // as __strong.
2857 if (GCAttrs == QualType::GCNone) {
2858 if (isObjCObjectPointerType(Ty))
2859 GCAttrs = QualType::Strong;
2860 else if (Ty->isPointerType())
2861 return getObjCGCAttrKind(Ty->getAsPointerType()->getPointeeType());
2862 }
Fariborz Jahaniand7b01972009-04-11 00:00:54 +00002863 // Non-pointers have none gc'able attribute regardless of the attribute
2864 // set on them.
Fariborz Jahanian717e4fa2009-06-02 18:32:00 +00002865 else if (!Ty->isPointerType() && !isObjCObjectPointerType(Ty))
Fariborz Jahaniand7b01972009-04-11 00:00:54 +00002866 return QualType::GCNone;
Fariborz Jahanianb8ca6ff2009-02-18 21:49:28 +00002867 }
Chris Lattner18b5a9a2009-02-18 22:53:11 +00002868 return GCAttrs;
Fariborz Jahanianb8ca6ff2009-02-18 21:49:28 +00002869}
2870
Chris Lattner6ff358b2008-04-07 06:51:04 +00002871//===----------------------------------------------------------------------===//
2872// Type Compatibility Testing
2873//===----------------------------------------------------------------------===//
Chris Lattner5003e8b2007-11-01 05:03:41 +00002874
Chris Lattner6ff358b2008-04-07 06:51:04 +00002875/// areCompatVectorTypes - Return true if the two specified vector types are
2876/// compatible.
2877static bool areCompatVectorTypes(const VectorType *LHS,
2878 const VectorType *RHS) {
2879 assert(LHS->isCanonical() && RHS->isCanonical());
2880 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner2fda0ed2008-10-05 17:34:18 +00002881 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ff358b2008-04-07 06:51:04 +00002882}
2883
Eli Friedman0d9549b2008-08-22 00:56:42 +00002884/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ff358b2008-04-07 06:51:04 +00002885/// compatible for assignment from RHS to LHS. This handles validation of any
2886/// protocol qualifiers on the LHS or RHS.
2887///
Eli Friedman0d9549b2008-08-22 00:56:42 +00002888bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
2889 const ObjCInterfaceType *RHS) {
Chris Lattner6ff358b2008-04-07 06:51:04 +00002890 // Verify that the base decls are compatible: the RHS must be a subclass of
2891 // the LHS.
2892 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
2893 return false;
2894
2895 // RHS must have a superset of the protocols in the LHS. If the LHS is not
2896 // protocol qualified at all, then we are good.
2897 if (!isa<ObjCQualifiedInterfaceType>(LHS))
2898 return true;
2899
2900 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
2901 // isn't a superset.
2902 if (!isa<ObjCQualifiedInterfaceType>(RHS))
2903 return true; // FIXME: should return false!
2904
2905 // Finally, we must have two protocol-qualified interfaces.
2906 const ObjCQualifiedInterfaceType *LHSP =cast<ObjCQualifiedInterfaceType>(LHS);
2907 const ObjCQualifiedInterfaceType *RHSP =cast<ObjCQualifiedInterfaceType>(RHS);
Chris Lattner6ff358b2008-04-07 06:51:04 +00002908
Steve Naroff98e71b82009-03-01 16:12:44 +00002909 // All LHS protocols must have a presence on the RHS.
2910 assert(LHSP->qual_begin() != LHSP->qual_end() && "Empty LHS protocol list?");
Chris Lattner6ff358b2008-04-07 06:51:04 +00002911
Steve Naroff98e71b82009-03-01 16:12:44 +00002912 for (ObjCQualifiedInterfaceType::qual_iterator LHSPI = LHSP->qual_begin(),
2913 LHSPE = LHSP->qual_end();
2914 LHSPI != LHSPE; LHSPI++) {
2915 bool RHSImplementsProtocol = false;
2916
2917 // If the RHS doesn't implement the protocol on the left, the types
2918 // are incompatible.
2919 for (ObjCQualifiedInterfaceType::qual_iterator RHSPI = RHSP->qual_begin(),
2920 RHSPE = RHSP->qual_end();
2921 !RHSImplementsProtocol && (RHSPI != RHSPE); RHSPI++) {
2922 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier()))
2923 RHSImplementsProtocol = true;
2924 }
2925 // FIXME: For better diagnostics, consider passing back the protocol name.
2926 if (!RHSImplementsProtocol)
2927 return false;
Chris Lattner6ff358b2008-04-07 06:51:04 +00002928 }
Steve Naroff98e71b82009-03-01 16:12:44 +00002929 // The RHS implements all protocols listed on the LHS.
2930 return true;
Chris Lattner6ff358b2008-04-07 06:51:04 +00002931}
2932
Steve Naroff17c03822009-02-12 17:52:19 +00002933bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
2934 // get the "pointed to" types
2935 const PointerType *LHSPT = LHS->getAsPointerType();
2936 const PointerType *RHSPT = RHS->getAsPointerType();
2937
2938 if (!LHSPT || !RHSPT)
2939 return false;
2940
2941 QualType lhptee = LHSPT->getPointeeType();
2942 QualType rhptee = RHSPT->getPointeeType();
2943 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2944 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2945 // ID acts sort of like void* for ObjC interfaces
2946 if (LHSIface && isObjCIdStructType(rhptee))
2947 return true;
2948 if (RHSIface && isObjCIdStructType(lhptee))
2949 return true;
2950 if (!LHSIface || !RHSIface)
2951 return false;
2952 return canAssignObjCInterfaces(LHSIface, RHSIface) ||
2953 canAssignObjCInterfaces(RHSIface, LHSIface);
2954}
2955
Steve Naroff85f0dc52007-10-15 20:41:53 +00002956/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
2957/// both shall have the identically qualified version of a compatible type.
2958/// C99 6.2.7p1: Two types have compatible types if their types are the
2959/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman0d9549b2008-08-22 00:56:42 +00002960bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
2961 return !mergeTypes(LHS, RHS).isNull();
2962}
2963
2964QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
2965 const FunctionType *lbase = lhs->getAsFunctionType();
2966 const FunctionType *rbase = rhs->getAsFunctionType();
Douglas Gregor4fa58902009-02-26 23:50:07 +00002967 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
2968 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman0d9549b2008-08-22 00:56:42 +00002969 bool allLTypes = true;
2970 bool allRTypes = true;
2971
2972 // Check return type
2973 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
2974 if (retType.isNull()) return QualType();
Chris Lattner2fda0ed2008-10-05 17:34:18 +00002975 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
2976 allLTypes = false;
2977 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
2978 allRTypes = false;
Eli Friedman0d9549b2008-08-22 00:56:42 +00002979
2980 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl2767d882009-05-27 22:11:52 +00002981 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
2982 "C++ shouldn't be here");
Eli Friedman0d9549b2008-08-22 00:56:42 +00002983 unsigned lproto_nargs = lproto->getNumArgs();
2984 unsigned rproto_nargs = rproto->getNumArgs();
2985
2986 // Compatible functions must have the same number of arguments
2987 if (lproto_nargs != rproto_nargs)
2988 return QualType();
2989
2990 // Variadic and non-variadic functions aren't compatible
2991 if (lproto->isVariadic() != rproto->isVariadic())
2992 return QualType();
2993
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002994 if (lproto->getTypeQuals() != rproto->getTypeQuals())
2995 return QualType();
2996
Eli Friedman0d9549b2008-08-22 00:56:42 +00002997 // Check argument compatibility
2998 llvm::SmallVector<QualType, 10> types;
2999 for (unsigned i = 0; i < lproto_nargs; i++) {
3000 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
3001 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
3002 QualType argtype = mergeTypes(largtype, rargtype);
3003 if (argtype.isNull()) return QualType();
3004 types.push_back(argtype);
Chris Lattner2fda0ed2008-10-05 17:34:18 +00003005 if (getCanonicalType(argtype) != getCanonicalType(largtype))
3006 allLTypes = false;
3007 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
3008 allRTypes = false;
Eli Friedman0d9549b2008-08-22 00:56:42 +00003009 }
3010 if (allLTypes) return lhs;
3011 if (allRTypes) return rhs;
3012 return getFunctionType(retType, types.begin(), types.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00003013 lproto->isVariadic(), lproto->getTypeQuals());
Eli Friedman0d9549b2008-08-22 00:56:42 +00003014 }
3015
3016 if (lproto) allRTypes = false;
3017 if (rproto) allLTypes = false;
3018
Douglas Gregor4fa58902009-02-26 23:50:07 +00003019 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman0d9549b2008-08-22 00:56:42 +00003020 if (proto) {
Sebastian Redl2767d882009-05-27 22:11:52 +00003021 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman0d9549b2008-08-22 00:56:42 +00003022 if (proto->isVariadic()) return QualType();
3023 // Check that the types are compatible with the types that
3024 // would result from default argument promotions (C99 6.7.5.3p15).
3025 // The only types actually affected are promotable integer
3026 // types and floats, which would be passed as a different
3027 // type depending on whether the prototype is visible.
3028 unsigned proto_nargs = proto->getNumArgs();
3029 for (unsigned i = 0; i < proto_nargs; ++i) {
3030 QualType argTy = proto->getArgType(i);
3031 if (argTy->isPromotableIntegerType() ||
3032 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
3033 return QualType();
3034 }
3035
3036 if (allLTypes) return lhs;
3037 if (allRTypes) return rhs;
3038 return getFunctionType(retType, proto->arg_type_begin(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00003039 proto->getNumArgs(), lproto->isVariadic(),
3040 lproto->getTypeQuals());
Eli Friedman0d9549b2008-08-22 00:56:42 +00003041 }
3042
3043 if (allLTypes) return lhs;
3044 if (allRTypes) return rhs;
Douglas Gregor4fa58902009-02-26 23:50:07 +00003045 return getFunctionNoProtoType(retType);
Eli Friedman0d9549b2008-08-22 00:56:42 +00003046}
3047
3048QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
Bill Wendling6a9d8542007-12-03 07:33:35 +00003049 // C++ [expr]: If an expression initially has the type "reference to T", the
3050 // type is adjusted to "T" prior to any further analysis, the expression
3051 // designates the object or function denoted by the reference, and the
Sebastian Redlce6fff02009-03-16 23:22:08 +00003052 // expression is an lvalue unless the reference is an rvalue reference and
3053 // the expression is a function call (possibly inside parentheses).
Eli Friedman0d9549b2008-08-22 00:56:42 +00003054 // FIXME: C++ shouldn't be going through here! The rules are different
3055 // enough that they should be handled separately.
Sebastian Redlce6fff02009-03-16 23:22:08 +00003056 // FIXME: Merging of lvalue and rvalue references is incorrect. C++ *really*
3057 // shouldn't be going through here!
Eli Friedman0d9549b2008-08-22 00:56:42 +00003058 if (const ReferenceType *RT = LHS->getAsReferenceType())
Chris Lattner855fed42008-04-07 04:07:56 +00003059 LHS = RT->getPointeeType();
Eli Friedman0d9549b2008-08-22 00:56:42 +00003060 if (const ReferenceType *RT = RHS->getAsReferenceType())
Chris Lattner855fed42008-04-07 04:07:56 +00003061 RHS = RT->getPointeeType();
Chris Lattnerd47d6042008-04-07 05:37:56 +00003062
Eli Friedman0d9549b2008-08-22 00:56:42 +00003063 QualType LHSCan = getCanonicalType(LHS),
3064 RHSCan = getCanonicalType(RHS);
3065
3066 // If two types are identical, they are compatible.
3067 if (LHSCan == RHSCan)
3068 return LHS;
3069
3070 // If the qualifiers are different, the types aren't compatible
Eli Friedman94fcc9a2009-02-27 23:04:43 +00003071 // Note that we handle extended qualifiers later, in the
3072 // case for ExtQualType.
3073 if (LHSCan.getCVRQualifiers() != RHSCan.getCVRQualifiers())
Eli Friedman0d9549b2008-08-22 00:56:42 +00003074 return QualType();
3075
Eli Friedmanaeae1ce2009-06-01 01:22:52 +00003076 Type::TypeClass LHSClass = LHSCan->getTypeClass();
3077 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman0d9549b2008-08-22 00:56:42 +00003078
Chris Lattnerc38d4522008-01-14 05:45:46 +00003079 // We want to consider the two function types to be the same for these
3080 // comparisons, just force one to the other.
3081 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
3082 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman398837e2008-02-12 08:23:06 +00003083
Eli Friedmande43bf62009-06-02 05:28:56 +00003084 // Strip off objc_gc attributes off the top level so they can be merged.
3085 // This is a complete mess, but the attribute itself doesn't make much sense.
Fariborz Jahanian85d91262009-06-02 01:40:22 +00003086 if (RHSClass == Type::ExtQual) {
Eli Friedmande43bf62009-06-02 05:28:56 +00003087 QualType::GCAttrTypes GCAttr = RHSCan.getObjCGCAttr();
3088 if (GCAttr != QualType::GCNone) {
Fariborz Jahanian562d0ee2009-06-02 20:58:58 +00003089 QualType::GCAttrTypes GCLHSAttr = LHSCan.getObjCGCAttr();
Fariborz Jahanian717e4fa2009-06-02 18:32:00 +00003090 // __weak attribute must appear on both declarations.
Fariborz Jahanian562d0ee2009-06-02 20:58:58 +00003091 // __strong attribue is redundant if other decl is an objective-c
3092 // object pointer (or decorated with __strong attribute); otherwise
3093 // issue error.
3094 if ((GCAttr == QualType::Weak && GCLHSAttr != GCAttr) ||
3095 (GCAttr == QualType::Strong && GCLHSAttr != GCAttr &&
3096 LHSCan->isPointerType() && !isObjCObjectPointerType(LHSCan) &&
3097 !isObjCIdStructType(LHSCan->getAsPointerType()->getPointeeType())))
Fariborz Jahanian717e4fa2009-06-02 18:32:00 +00003098 return QualType();
3099
Eli Friedmande43bf62009-06-02 05:28:56 +00003100 RHS = QualType(cast<ExtQualType>(RHS.getDesugaredType())->getBaseType(),
3101 RHS.getCVRQualifiers());
3102 QualType Result = mergeTypes(LHS, RHS);
Fariborz Jahanian717e4fa2009-06-02 18:32:00 +00003103 if (!Result.isNull()) {
3104 if (Result.getObjCGCAttr() == QualType::GCNone)
3105 Result = getObjCGCQualType(Result, GCAttr);
3106 else if (Result.getObjCGCAttr() != GCAttr)
3107 Result = QualType();
3108 }
Eli Friedmande43bf62009-06-02 05:28:56 +00003109 return Result;
3110 }
Fariborz Jahanian85d91262009-06-02 01:40:22 +00003111 }
Fariborz Jahanian85d91262009-06-02 01:40:22 +00003112 if (LHSClass == Type::ExtQual) {
Eli Friedmande43bf62009-06-02 05:28:56 +00003113 QualType::GCAttrTypes GCAttr = LHSCan.getObjCGCAttr();
3114 if (GCAttr != QualType::GCNone) {
Fariborz Jahanian717e4fa2009-06-02 18:32:00 +00003115 QualType::GCAttrTypes GCRHSAttr = RHSCan.getObjCGCAttr();
3116 // __weak attribute must appear on both declarations. __strong
Fariborz Jahanian562d0ee2009-06-02 20:58:58 +00003117 // __strong attribue is redundant if other decl is an objective-c
3118 // object pointer (or decorated with __strong attribute); otherwise
3119 // issue error.
3120 if ((GCAttr == QualType::Weak && GCRHSAttr != GCAttr) ||
3121 (GCAttr == QualType::Strong && GCRHSAttr != GCAttr &&
3122 RHSCan->isPointerType() && !isObjCObjectPointerType(RHSCan) &&
3123 !isObjCIdStructType(RHSCan->getAsPointerType()->getPointeeType())))
Fariborz Jahanian717e4fa2009-06-02 18:32:00 +00003124 return QualType();
Fariborz Jahanian562d0ee2009-06-02 20:58:58 +00003125
Eli Friedmande43bf62009-06-02 05:28:56 +00003126 LHS = QualType(cast<ExtQualType>(LHS.getDesugaredType())->getBaseType(),
3127 LHS.getCVRQualifiers());
3128 QualType Result = mergeTypes(LHS, RHS);
Fariborz Jahanian717e4fa2009-06-02 18:32:00 +00003129 if (!Result.isNull()) {
3130 if (Result.getObjCGCAttr() == QualType::GCNone)
3131 Result = getObjCGCQualType(Result, GCAttr);
3132 else if (Result.getObjCGCAttr() != GCAttr)
3133 Result = QualType();
3134 }
Eli Friedman430d9f12009-06-02 07:45:37 +00003135 return Result;
Eli Friedmande43bf62009-06-02 05:28:56 +00003136 }
Fariborz Jahanian85d91262009-06-02 01:40:22 +00003137 }
3138
Eli Friedman398837e2008-02-12 08:23:06 +00003139 // Same as above for arrays
Chris Lattnerb5709e22008-04-07 05:43:21 +00003140 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
3141 LHSClass = Type::ConstantArray;
3142 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
3143 RHSClass = Type::ConstantArray;
Steve Naroff85f0dc52007-10-15 20:41:53 +00003144
Nate Begemanaf6ed502008-04-18 23:10:10 +00003145 // Canonicalize ExtVector -> Vector.
3146 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
3147 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Chris Lattnerb5709e22008-04-07 05:43:21 +00003148
Chris Lattner7cdcb252008-04-07 06:38:24 +00003149 // Consider qualified interfaces and interfaces the same.
3150 if (LHSClass == Type::ObjCQualifiedInterface) LHSClass = Type::ObjCInterface;
3151 if (RHSClass == Type::ObjCQualifiedInterface) RHSClass = Type::ObjCInterface;
Eli Friedman0d9549b2008-08-22 00:56:42 +00003152
Chris Lattnerb5709e22008-04-07 05:43:21 +00003153 // If the canonical type classes don't match.
Chris Lattnerc38d4522008-01-14 05:45:46 +00003154 if (LHSClass != RHSClass) {
Steve Naroff0bbc1352009-02-21 16:18:07 +00003155 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
3156 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
Fariborz Jahanian0dc684e2009-04-15 21:54:48 +00003157
Steve Naroff0773c582009-04-14 15:11:46 +00003158 // 'id' and 'Class' act sort of like void* for ObjC interfaces
3159 if (LHSIface && (isObjCIdStructType(RHS) || isObjCClassStructType(RHS)))
Steve Naroff0bbc1352009-02-21 16:18:07 +00003160 return LHS;
Steve Naroff0773c582009-04-14 15:11:46 +00003161 if (RHSIface && (isObjCIdStructType(LHS) || isObjCClassStructType(LHS)))
Steve Naroff0bbc1352009-02-21 16:18:07 +00003162 return RHS;
3163
Steve Naroff28ceff72008-12-10 22:14:21 +00003164 // ID is compatible with all qualified id types.
3165 if (LHS->isObjCQualifiedIdType()) {
3166 if (const PointerType *PT = RHS->getAsPointerType()) {
3167 QualType pType = PT->getPointeeType();
Steve Naroff0773c582009-04-14 15:11:46 +00003168 if (isObjCIdStructType(pType) || isObjCClassStructType(pType))
Steve Naroff28ceff72008-12-10 22:14:21 +00003169 return LHS;
3170 // FIXME: need to use ObjCQualifiedIdTypesAreCompatible(LHS, RHS, true).
3171 // Unfortunately, this API is part of Sema (which we don't have access
3172 // to. Need to refactor. The following check is insufficient, since we
3173 // need to make sure the class implements the protocol.
3174 if (pType->isObjCInterfaceType())
3175 return LHS;
3176 }
3177 }
3178 if (RHS->isObjCQualifiedIdType()) {
3179 if (const PointerType *PT = LHS->getAsPointerType()) {
3180 QualType pType = PT->getPointeeType();
Steve Naroff0773c582009-04-14 15:11:46 +00003181 if (isObjCIdStructType(pType) || isObjCClassStructType(pType))
Steve Naroff28ceff72008-12-10 22:14:21 +00003182 return RHS;
3183 // FIXME: need to use ObjCQualifiedIdTypesAreCompatible(LHS, RHS, true).
3184 // Unfortunately, this API is part of Sema (which we don't have access
3185 // to. Need to refactor. The following check is insufficient, since we
3186 // need to make sure the class implements the protocol.
3187 if (pType->isObjCInterfaceType())
3188 return RHS;
3189 }
3190 }
Chris Lattnerc38d4522008-01-14 05:45:46 +00003191 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
3192 // a signed integer type, or an unsigned integer type.
Eli Friedman0d9549b2008-08-22 00:56:42 +00003193 if (const EnumType* ETy = LHS->getAsEnumType()) {
3194 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
3195 return RHS;
Eli Friedmanad6c06c2008-02-12 08:46:17 +00003196 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00003197 if (const EnumType* ETy = RHS->getAsEnumType()) {
3198 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
3199 return LHS;
Eli Friedmanad6c06c2008-02-12 08:46:17 +00003200 }
Chris Lattnerc38d4522008-01-14 05:45:46 +00003201
Eli Friedman0d9549b2008-08-22 00:56:42 +00003202 return QualType();
Steve Naroff85f0dc52007-10-15 20:41:53 +00003203 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00003204
Steve Naroffc88babe2008-01-09 22:43:08 +00003205 // The canonical type classes match.
Chris Lattnerc38d4522008-01-14 05:45:46 +00003206 switch (LHSClass) {
Douglas Gregor4fa58902009-02-26 23:50:07 +00003207#define TYPE(Class, Base)
3208#define ABSTRACT_TYPE(Class, Base)
3209#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3210#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3211#include "clang/AST/TypeNodes.def"
3212 assert(false && "Non-canonical and dependent types shouldn't get here");
3213 return QualType();
3214
Sebastian Redlce6fff02009-03-16 23:22:08 +00003215 case Type::LValueReference:
3216 case Type::RValueReference:
Douglas Gregor4fa58902009-02-26 23:50:07 +00003217 case Type::MemberPointer:
3218 assert(false && "C++ should never be in mergeTypes");
3219 return QualType();
3220
3221 case Type::IncompleteArray:
3222 case Type::VariableArray:
3223 case Type::FunctionProto:
3224 case Type::ExtVector:
3225 case Type::ObjCQualifiedInterface:
3226 assert(false && "Types are eliminated above");
3227 return QualType();
3228
Chris Lattnerc38d4522008-01-14 05:45:46 +00003229 case Type::Pointer:
Eli Friedman0d9549b2008-08-22 00:56:42 +00003230 {
3231 // Merge two pointer types, while trying to preserve typedef info
3232 QualType LHSPointee = LHS->getAsPointerType()->getPointeeType();
3233 QualType RHSPointee = RHS->getAsPointerType()->getPointeeType();
3234 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
3235 if (ResultType.isNull()) return QualType();
Eli Friedmande43bf62009-06-02 05:28:56 +00003236 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner2fda0ed2008-10-05 17:34:18 +00003237 return LHS;
Eli Friedmande43bf62009-06-02 05:28:56 +00003238 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner2fda0ed2008-10-05 17:34:18 +00003239 return RHS;
Eli Friedman0d9549b2008-08-22 00:56:42 +00003240 return getPointerType(ResultType);
3241 }
Steve Naroff09e1b9e2008-12-10 17:49:55 +00003242 case Type::BlockPointer:
3243 {
3244 // Merge two block pointer types, while trying to preserve typedef info
3245 QualType LHSPointee = LHS->getAsBlockPointerType()->getPointeeType();
3246 QualType RHSPointee = RHS->getAsBlockPointerType()->getPointeeType();
3247 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
3248 if (ResultType.isNull()) return QualType();
3249 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
3250 return LHS;
3251 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
3252 return RHS;
3253 return getBlockPointerType(ResultType);
3254 }
Chris Lattnerc38d4522008-01-14 05:45:46 +00003255 case Type::ConstantArray:
Eli Friedman0d9549b2008-08-22 00:56:42 +00003256 {
3257 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
3258 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
3259 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
3260 return QualType();
3261
3262 QualType LHSElem = getAsArrayType(LHS)->getElementType();
3263 QualType RHSElem = getAsArrayType(RHS)->getElementType();
3264 QualType ResultType = mergeTypes(LHSElem, RHSElem);
3265 if (ResultType.isNull()) return QualType();
Chris Lattner2fda0ed2008-10-05 17:34:18 +00003266 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3267 return LHS;
3268 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3269 return RHS;
Eli Friedmanc91a3f32008-08-22 01:48:21 +00003270 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
3271 ArrayType::ArraySizeModifier(), 0);
3272 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
3273 ArrayType::ArraySizeModifier(), 0);
Eli Friedman0d9549b2008-08-22 00:56:42 +00003274 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
3275 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner2fda0ed2008-10-05 17:34:18 +00003276 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3277 return LHS;
3278 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3279 return RHS;
Eli Friedman0d9549b2008-08-22 00:56:42 +00003280 if (LVAT) {
3281 // FIXME: This isn't correct! But tricky to implement because
3282 // the array's size has to be the size of LHS, but the type
3283 // has to be different.
3284 return LHS;
3285 }
3286 if (RVAT) {
3287 // FIXME: This isn't correct! But tricky to implement because
3288 // the array's size has to be the size of RHS, but the type
3289 // has to be different.
3290 return RHS;
3291 }
Eli Friedmanc91a3f32008-08-22 01:48:21 +00003292 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
3293 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Chris Lattner2fda0ed2008-10-05 17:34:18 +00003294 return getIncompleteArrayType(ResultType, ArrayType::ArraySizeModifier(),0);
Eli Friedman0d9549b2008-08-22 00:56:42 +00003295 }
Chris Lattnerc38d4522008-01-14 05:45:46 +00003296 case Type::FunctionNoProto:
Eli Friedman0d9549b2008-08-22 00:56:42 +00003297 return mergeFunctionTypes(LHS, RHS);
Douglas Gregor4fa58902009-02-26 23:50:07 +00003298 case Type::Record:
Douglas Gregor4fa58902009-02-26 23:50:07 +00003299 case Type::Enum:
Eli Friedman0d9549b2008-08-22 00:56:42 +00003300 // FIXME: Why are these compatible?
Steve Naroff17c03822009-02-12 17:52:19 +00003301 if (isObjCIdStructType(LHS) && isObjCClassStructType(RHS)) return LHS;
3302 if (isObjCClassStructType(LHS) && isObjCIdStructType(RHS)) return LHS;
Eli Friedman0d9549b2008-08-22 00:56:42 +00003303 return QualType();
Chris Lattnerc38d4522008-01-14 05:45:46 +00003304 case Type::Builtin:
Chris Lattnerd1240fa2008-04-07 05:55:38 +00003305 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman0d9549b2008-08-22 00:56:42 +00003306 return QualType();
Daniel Dunbar457f33d2009-01-28 21:22:12 +00003307 case Type::Complex:
3308 // Distinct complex types are incompatible.
3309 return QualType();
Chris Lattnerd1240fa2008-04-07 05:55:38 +00003310 case Type::Vector:
Eli Friedman94fcc9a2009-02-27 23:04:43 +00003311 // FIXME: The merged type should be an ExtVector!
Eli Friedman0d9549b2008-08-22 00:56:42 +00003312 if (areCompatVectorTypes(LHS->getAsVectorType(), RHS->getAsVectorType()))
3313 return LHS;
Chris Lattner2fda0ed2008-10-05 17:34:18 +00003314 return QualType();
Cédric Venet23536132009-02-21 17:14:49 +00003315 case Type::ObjCInterface: {
Steve Naroff0bbc1352009-02-21 16:18:07 +00003316 // Check if the interfaces are assignment compatible.
Eli Friedman94fcc9a2009-02-27 23:04:43 +00003317 // FIXME: This should be type compatibility, e.g. whether
3318 // "LHS x; RHS x;" at global scope is legal.
Steve Naroff0bbc1352009-02-21 16:18:07 +00003319 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
3320 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
3321 if (LHSIface && RHSIface &&
3322 canAssignObjCInterfaces(LHSIface, RHSIface))
3323 return LHS;
3324
Eli Friedman0d9549b2008-08-22 00:56:42 +00003325 return QualType();
Cédric Venet23536132009-02-21 17:14:49 +00003326 }
Steve Naroffc75c1a82009-06-17 22:40:22 +00003327 case Type::ObjCObjectPointer:
3328 // FIXME: finish
Steve Naroff28ceff72008-12-10 22:14:21 +00003329 // Distinct qualified id's are not compatible.
3330 return QualType();
Eli Friedman94fcc9a2009-02-27 23:04:43 +00003331 case Type::FixedWidthInt:
3332 // Distinct fixed-width integers are not compatible.
3333 return QualType();
Eli Friedman94fcc9a2009-02-27 23:04:43 +00003334 case Type::ExtQual:
3335 // FIXME: ExtQual types can be compatible even if they're not
3336 // identical!
3337 return QualType();
3338 // First attempt at an implementation, but I'm not really sure it's
3339 // right...
3340#if 0
3341 ExtQualType* LQual = cast<ExtQualType>(LHSCan);
3342 ExtQualType* RQual = cast<ExtQualType>(RHSCan);
3343 if (LQual->getAddressSpace() != RQual->getAddressSpace() ||
3344 LQual->getObjCGCAttr() != RQual->getObjCGCAttr())
3345 return QualType();
3346 QualType LHSBase, RHSBase, ResultType, ResCanUnqual;
3347 LHSBase = QualType(LQual->getBaseType(), 0);
3348 RHSBase = QualType(RQual->getBaseType(), 0);
3349 ResultType = mergeTypes(LHSBase, RHSBase);
3350 if (ResultType.isNull()) return QualType();
3351 ResCanUnqual = getCanonicalType(ResultType).getUnqualifiedType();
3352 if (LHSCan.getUnqualifiedType() == ResCanUnqual)
3353 return LHS;
3354 if (RHSCan.getUnqualifiedType() == ResCanUnqual)
3355 return RHS;
3356 ResultType = getAddrSpaceQualType(ResultType, LQual->getAddressSpace());
3357 ResultType = getObjCGCQualType(ResultType, LQual->getObjCGCAttr());
3358 ResultType.setCVRQualifiers(LHSCan.getCVRQualifiers());
3359 return ResultType;
3360#endif
Douglas Gregordd13e842009-03-30 22:58:21 +00003361
3362 case Type::TemplateSpecialization:
3363 assert(false && "Dependent types have no size");
3364 break;
Steve Naroff85f0dc52007-10-15 20:41:53 +00003365 }
Douglas Gregor4fa58902009-02-26 23:50:07 +00003366
3367 return QualType();
Steve Naroff85f0dc52007-10-15 20:41:53 +00003368}
Ted Kremenek738e6c02007-10-31 17:10:13 +00003369
Chris Lattner1d78a862008-04-07 07:01:58 +00003370//===----------------------------------------------------------------------===//
Eli Friedman0832dbc2008-06-28 06:23:08 +00003371// Integer Predicates
3372//===----------------------------------------------------------------------===//
Chris Lattner74f67012009-01-16 07:15:35 +00003373
Eli Friedman0832dbc2008-06-28 06:23:08 +00003374unsigned ASTContext::getIntWidth(QualType T) {
3375 if (T == BoolTy)
3376 return 1;
Eli Friedmanff3fcdf2009-02-13 02:31:07 +00003377 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T)) {
3378 return FWIT->getWidth();
3379 }
3380 // For builtin types, just use the standard type sizing method
Eli Friedman0832dbc2008-06-28 06:23:08 +00003381 return (unsigned)getTypeSize(T);
3382}
3383
3384QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
3385 assert(T->isSignedIntegerType() && "Unexpected type");
3386 if (const EnumType* ETy = T->getAsEnumType())
3387 T = ETy->getDecl()->getIntegerType();
3388 const BuiltinType* BTy = T->getAsBuiltinType();
3389 assert (BTy && "Unexpected signed integer type");
3390 switch (BTy->getKind()) {
3391 case BuiltinType::Char_S:
3392 case BuiltinType::SChar:
3393 return UnsignedCharTy;
3394 case BuiltinType::Short:
3395 return UnsignedShortTy;
3396 case BuiltinType::Int:
3397 return UnsignedIntTy;
3398 case BuiltinType::Long:
3399 return UnsignedLongTy;
3400 case BuiltinType::LongLong:
3401 return UnsignedLongLongTy;
Chris Lattner6cc7e412009-04-30 02:43:43 +00003402 case BuiltinType::Int128:
3403 return UnsignedInt128Ty;
Eli Friedman0832dbc2008-06-28 06:23:08 +00003404 default:
3405 assert(0 && "Unexpected signed integer type");
3406 return QualType();
3407 }
3408}
3409
Douglas Gregorc34897d2009-04-09 22:27:44 +00003410ExternalASTSource::~ExternalASTSource() { }
3411
3412void ExternalASTSource::PrintStats() { }
Chris Lattner260ad502009-06-14 00:45:47 +00003413
3414
3415//===----------------------------------------------------------------------===//
3416// Builtin Type Computation
3417//===----------------------------------------------------------------------===//
3418
3419/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
3420/// pointer over the consumed characters. This returns the resultant type.
3421static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
3422 ASTContext::GetBuiltinTypeError &Error,
3423 bool AllowTypeModifiers = true) {
3424 // Modifiers.
3425 int HowLong = 0;
3426 bool Signed = false, Unsigned = false;
3427
3428 // Read the modifiers first.
3429 bool Done = false;
3430 while (!Done) {
3431 switch (*Str++) {
3432 default: Done = true; --Str; break;
3433 case 'S':
3434 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
3435 assert(!Signed && "Can't use 'S' modifier multiple times!");
3436 Signed = true;
3437 break;
3438 case 'U':
3439 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
3440 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
3441 Unsigned = true;
3442 break;
3443 case 'L':
3444 assert(HowLong <= 2 && "Can't have LLLL modifier");
3445 ++HowLong;
3446 break;
3447 }
3448 }
3449
3450 QualType Type;
3451
3452 // Read the base type.
3453 switch (*Str++) {
3454 default: assert(0 && "Unknown builtin type letter!");
3455 case 'v':
3456 assert(HowLong == 0 && !Signed && !Unsigned &&
3457 "Bad modifiers used with 'v'!");
3458 Type = Context.VoidTy;
3459 break;
3460 case 'f':
3461 assert(HowLong == 0 && !Signed && !Unsigned &&
3462 "Bad modifiers used with 'f'!");
3463 Type = Context.FloatTy;
3464 break;
3465 case 'd':
3466 assert(HowLong < 2 && !Signed && !Unsigned &&
3467 "Bad modifiers used with 'd'!");
3468 if (HowLong)
3469 Type = Context.LongDoubleTy;
3470 else
3471 Type = Context.DoubleTy;
3472 break;
3473 case 's':
3474 assert(HowLong == 0 && "Bad modifiers used with 's'!");
3475 if (Unsigned)
3476 Type = Context.UnsignedShortTy;
3477 else
3478 Type = Context.ShortTy;
3479 break;
3480 case 'i':
3481 if (HowLong == 3)
3482 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
3483 else if (HowLong == 2)
3484 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
3485 else if (HowLong == 1)
3486 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
3487 else
3488 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
3489 break;
3490 case 'c':
3491 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
3492 if (Signed)
3493 Type = Context.SignedCharTy;
3494 else if (Unsigned)
3495 Type = Context.UnsignedCharTy;
3496 else
3497 Type = Context.CharTy;
3498 break;
3499 case 'b': // boolean
3500 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
3501 Type = Context.BoolTy;
3502 break;
3503 case 'z': // size_t.
3504 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
3505 Type = Context.getSizeType();
3506 break;
3507 case 'F':
3508 Type = Context.getCFConstantStringType();
3509 break;
3510 case 'a':
3511 Type = Context.getBuiltinVaListType();
3512 assert(!Type.isNull() && "builtin va list type not initialized!");
3513 break;
3514 case 'A':
3515 // This is a "reference" to a va_list; however, what exactly
3516 // this means depends on how va_list is defined. There are two
3517 // different kinds of va_list: ones passed by value, and ones
3518 // passed by reference. An example of a by-value va_list is
3519 // x86, where va_list is a char*. An example of by-ref va_list
3520 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
3521 // we want this argument to be a char*&; for x86-64, we want
3522 // it to be a __va_list_tag*.
3523 Type = Context.getBuiltinVaListType();
3524 assert(!Type.isNull() && "builtin va list type not initialized!");
3525 if (Type->isArrayType()) {
3526 Type = Context.getArrayDecayedType(Type);
3527 } else {
3528 Type = Context.getLValueReferenceType(Type);
3529 }
3530 break;
3531 case 'V': {
3532 char *End;
3533
3534 unsigned NumElements = strtoul(Str, &End, 10);
3535 assert(End != Str && "Missing vector size");
3536
3537 Str = End;
3538
3539 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
3540 Type = Context.getVectorType(ElementType, NumElements);
3541 break;
3542 }
3543 case 'P': {
3544 IdentifierInfo *II = &Context.Idents.get("FILE");
3545 DeclContext::lookup_result Lookup
3546 = Context.getTranslationUnitDecl()->lookup(Context, II);
3547 if (Lookup.first != Lookup.second && isa<TypeDecl>(*Lookup.first)) {
3548 Type = Context.getTypeDeclType(cast<TypeDecl>(*Lookup.first));
3549 break;
3550 }
3551 else {
3552 Error = ASTContext::GE_Missing_FILE;
3553 return QualType();
3554 }
3555 }
3556 }
3557
3558 if (!AllowTypeModifiers)
3559 return Type;
3560
3561 Done = false;
3562 while (!Done) {
3563 switch (*Str++) {
3564 default: Done = true; --Str; break;
3565 case '*':
3566 Type = Context.getPointerType(Type);
3567 break;
3568 case '&':
3569 Type = Context.getLValueReferenceType(Type);
3570 break;
3571 // FIXME: There's no way to have a built-in with an rvalue ref arg.
3572 case 'C':
3573 Type = Type.getQualifiedType(QualType::Const);
3574 break;
3575 }
3576 }
3577
3578 return Type;
3579}
3580
3581/// GetBuiltinType - Return the type for the specified builtin.
3582QualType ASTContext::GetBuiltinType(unsigned id,
3583 GetBuiltinTypeError &Error) {
3584 const char *TypeStr = BuiltinInfo.GetTypeString(id);
3585
3586 llvm::SmallVector<QualType, 8> ArgTypes;
3587
3588 Error = GE_None;
3589 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
3590 if (Error != GE_None)
3591 return QualType();
3592 while (TypeStr[0] && TypeStr[0] != '.') {
3593 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
3594 if (Error != GE_None)
3595 return QualType();
3596
3597 // Do array -> pointer decay. The builtin should use the decayed type.
3598 if (Ty->isArrayType())
3599 Ty = getArrayDecayedType(Ty);
3600
3601 ArgTypes.push_back(Ty);
3602 }
3603
3604 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
3605 "'.' should only occur at end of builtin type list!");
3606
3607 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
3608 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
3609 return getFunctionNoProtoType(ResType);
3610 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
3611 TypeStr[0] == '.', 0);
3612}