blob: fc1e0a2062752ad5a07c1c28d66c79c6705aaf4f [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"
19#include "clang/AST/RecordLayout.h"
Chris Lattnerb09b31d2009-03-28 03:45:20 +000020#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000021#include "clang/Basic/TargetInfo.h"
Anders Carlsson36f07d82007-10-29 05:01:08 +000022#include "llvm/ADT/StringExtras.h"
Ted Kremenek738e6c02007-10-31 17:10:13 +000023#include "llvm/Bitcode/Serialize.h"
24#include "llvm/Bitcode/Deserialize.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,
Steve Naroff207b9ec2009-01-27 23:20:32 +000036 bool FreeMem, unsigned size_reserve) :
Douglas Gregor1e589cc2009-03-26 23:50:42 +000037 GlobalNestedNameSpecifier(0), CFConstantStringTypeDecl(0),
38 ObjCFastEnumerationStateTypeDecl(0), SourceMgr(SM), LangOpts(LOpts),
Chris Lattner9c18fde2009-03-28 01:44:40 +000039 FreeMemory(FreeMem), Target(t), Idents(idents), Selectors(sels) {
Daniel Dunbarde300732008-08-11 04:54:23 +000040 if (size_reserve > 0) Types.reserve(size_reserve);
41 InitBuiltinTypes();
Chris Lattner911b8672009-03-13 22:38:49 +000042 BuiltinInfo.InitializeBuiltins(idents, Target, LangOpts.NoBuiltin);
Daniel Dunbarde300732008-08-11 04:54:23 +000043 TUDecl = TranslationUnitDecl::Create(*this);
44}
45
Chris Lattner4b009652007-07-25 00:24:17 +000046ASTContext::~ASTContext() {
47 // Deallocate all the types.
48 while (!Types.empty()) {
Ted Kremenekdb4d5972008-05-21 16:38:54 +000049 Types.back()->Destroy(*this);
Chris Lattner4b009652007-07-25 00:24:17 +000050 Types.pop_back();
51 }
Eli Friedman65489b72008-05-27 03:08:09 +000052
Nuno Lopes355a8682008-12-17 22:30:25 +000053 {
54 llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
55 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end();
56 while (I != E) {
57 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
58 delete R;
59 }
60 }
61
62 {
63 llvm::DenseMap<const ObjCInterfaceDecl*, const ASTRecordLayout*>::iterator
64 I = ASTObjCInterfaces.begin(), E = ASTObjCInterfaces.end();
65 while (I != E) {
66 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
67 delete R;
68 }
69 }
70
71 {
Chris Lattner608c1e32009-03-31 09:24:30 +000072 llvm::DenseMap<const ObjCInterfaceDecl*, RecordDecl*>::iterator
Nuno Lopes355a8682008-12-17 22:30:25 +000073 I = ASTRecordForInterface.begin(), E = ASTRecordForInterface.end();
74 while (I != E) {
Chris Lattner608c1e32009-03-31 09:24:30 +000075 RecordDecl *R = (I++)->second;
Nuno Lopes355a8682008-12-17 22:30:25 +000076 R->Destroy(*this);
77 }
78 }
79
Douglas Gregor1e589cc2009-03-26 23:50:42 +000080 // Destroy nested-name-specifiers.
Douglas Gregor3c4eae52009-03-27 23:54:10 +000081 for (llvm::FoldingSet<NestedNameSpecifier>::iterator
82 NNS = NestedNameSpecifiers.begin(),
83 NNSEnd = NestedNameSpecifiers.end();
Douglas Gregorbccd97c2009-03-27 23:25:45 +000084 NNS != NNSEnd;
Douglas Gregor3c4eae52009-03-27 23:54:10 +000085 /* Increment in loop */)
86 (*NNS++).Destroy(*this);
Douglas Gregor1e589cc2009-03-26 23:50:42 +000087
88 if (GlobalNestedNameSpecifier)
89 GlobalNestedNameSpecifier->Destroy(*this);
90
Eli Friedman65489b72008-05-27 03:08:09 +000091 TUDecl->Destroy(*this);
Chris Lattner4b009652007-07-25 00:24:17 +000092}
93
94void ASTContext::PrintStats() const {
95 fprintf(stderr, "*** AST Context Stats:\n");
96 fprintf(stderr, " %d types total.\n", (int)Types.size());
97 unsigned NumBuiltin = 0, NumPointer = 0, NumArray = 0, NumFunctionP = 0;
Daniel Dunbar47677342008-09-26 03:23:00 +000098 unsigned NumVector = 0, NumComplex = 0, NumBlockPointer = 0;
Sebastian Redlce6fff02009-03-16 23:22:08 +000099 unsigned NumFunctionNP = 0, NumTypeName = 0, NumTagged = 0;
100 unsigned NumLValueReference = 0, NumRValueReference = 0, NumMemberPointer = 0;
101
Chris Lattner4b009652007-07-25 00:24:17 +0000102 unsigned NumTagStruct = 0, NumTagUnion = 0, NumTagEnum = 0, NumTagClass = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +0000103 unsigned NumObjCInterfaces = 0, NumObjCQualifiedInterfaces = 0;
104 unsigned NumObjCQualifiedIds = 0;
Douglas Gregor4fa58902009-02-26 23:50:07 +0000105 unsigned NumTypeOfTypes = 0, NumTypeOfExprTypes = 0;
Chris Lattner4b009652007-07-25 00:24:17 +0000106
107 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
108 Type *T = Types[i];
109 if (isa<BuiltinType>(T))
110 ++NumBuiltin;
111 else if (isa<PointerType>(T))
112 ++NumPointer;
Daniel Dunbar47677342008-09-26 03:23:00 +0000113 else if (isa<BlockPointerType>(T))
114 ++NumBlockPointer;
Sebastian Redlce6fff02009-03-16 23:22:08 +0000115 else if (isa<LValueReferenceType>(T))
116 ++NumLValueReference;
117 else if (isa<RValueReferenceType>(T))
118 ++NumRValueReference;
Sebastian Redl75555032009-01-24 21:16:55 +0000119 else if (isa<MemberPointerType>(T))
120 ++NumMemberPointer;
Chris Lattner4b009652007-07-25 00:24:17 +0000121 else if (isa<ComplexType>(T))
122 ++NumComplex;
123 else if (isa<ArrayType>(T))
124 ++NumArray;
125 else if (isa<VectorType>(T))
126 ++NumVector;
Douglas Gregor4fa58902009-02-26 23:50:07 +0000127 else if (isa<FunctionNoProtoType>(T))
Chris Lattner4b009652007-07-25 00:24:17 +0000128 ++NumFunctionNP;
Douglas Gregor4fa58902009-02-26 23:50:07 +0000129 else if (isa<FunctionProtoType>(T))
Chris Lattner4b009652007-07-25 00:24:17 +0000130 ++NumFunctionP;
131 else if (isa<TypedefType>(T))
132 ++NumTypeName;
133 else if (TagType *TT = dyn_cast<TagType>(T)) {
134 ++NumTagged;
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +0000135 switch (TT->getDecl()->getTagKind()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000136 default: assert(0 && "Unknown tagged type!");
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +0000137 case TagDecl::TK_struct: ++NumTagStruct; break;
138 case TagDecl::TK_union: ++NumTagUnion; break;
139 case TagDecl::TK_class: ++NumTagClass; break;
140 case TagDecl::TK_enum: ++NumTagEnum; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000141 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000142 } else if (isa<ObjCInterfaceType>(T))
143 ++NumObjCInterfaces;
144 else if (isa<ObjCQualifiedInterfaceType>(T))
145 ++NumObjCQualifiedInterfaces;
146 else if (isa<ObjCQualifiedIdType>(T))
147 ++NumObjCQualifiedIds;
Steve Naroffe0430632008-05-21 15:59:22 +0000148 else if (isa<TypeOfType>(T))
149 ++NumTypeOfTypes;
Douglas Gregor4fa58902009-02-26 23:50:07 +0000150 else if (isa<TypeOfExprType>(T))
151 ++NumTypeOfExprTypes;
Steve Naroff948fd372007-09-17 14:16:13 +0000152 else {
Chris Lattner8a35b462007-12-12 06:43:05 +0000153 QualType(T, 0).dump();
Chris Lattner4b009652007-07-25 00:24:17 +0000154 assert(0 && "Unknown type!");
155 }
156 }
157
158 fprintf(stderr, " %d builtin types\n", NumBuiltin);
159 fprintf(stderr, " %d pointer types\n", NumPointer);
Daniel Dunbar47677342008-09-26 03:23:00 +0000160 fprintf(stderr, " %d block pointer types\n", NumBlockPointer);
Sebastian Redlce6fff02009-03-16 23:22:08 +0000161 fprintf(stderr, " %d lvalue reference types\n", NumLValueReference);
162 fprintf(stderr, " %d rvalue reference types\n", NumRValueReference);
Sebastian Redl75555032009-01-24 21:16:55 +0000163 fprintf(stderr, " %d member pointer types\n", NumMemberPointer);
Chris Lattner4b009652007-07-25 00:24:17 +0000164 fprintf(stderr, " %d complex types\n", NumComplex);
165 fprintf(stderr, " %d array types\n", NumArray);
166 fprintf(stderr, " %d vector types\n", NumVector);
167 fprintf(stderr, " %d function types with proto\n", NumFunctionP);
168 fprintf(stderr, " %d function types with no proto\n", NumFunctionNP);
169 fprintf(stderr, " %d typename (typedef) types\n", NumTypeName);
170 fprintf(stderr, " %d tagged types\n", NumTagged);
171 fprintf(stderr, " %d struct types\n", NumTagStruct);
172 fprintf(stderr, " %d union types\n", NumTagUnion);
173 fprintf(stderr, " %d class types\n", NumTagClass);
174 fprintf(stderr, " %d enum types\n", NumTagEnum);
Ted Kremenek42730c52008-01-07 19:49:32 +0000175 fprintf(stderr, " %d interface types\n", NumObjCInterfaces);
Chris Lattner8a35b462007-12-12 06:43:05 +0000176 fprintf(stderr, " %d protocol qualified interface types\n",
Ted Kremenek42730c52008-01-07 19:49:32 +0000177 NumObjCQualifiedInterfaces);
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000178 fprintf(stderr, " %d protocol qualified id types\n",
Ted Kremenek42730c52008-01-07 19:49:32 +0000179 NumObjCQualifiedIds);
Steve Naroffe0430632008-05-21 15:59:22 +0000180 fprintf(stderr, " %d typeof types\n", NumTypeOfTypes);
Douglas Gregor4fa58902009-02-26 23:50:07 +0000181 fprintf(stderr, " %d typeof exprs\n", NumTypeOfExprTypes);
Sebastian Redlce6fff02009-03-16 23:22:08 +0000182
Chris Lattner4b009652007-07-25 00:24:17 +0000183 fprintf(stderr, "Total bytes = %d\n", int(NumBuiltin*sizeof(BuiltinType)+
184 NumPointer*sizeof(PointerType)+NumArray*sizeof(ArrayType)+
185 NumComplex*sizeof(ComplexType)+NumVector*sizeof(VectorType)+
Sebastian Redlce6fff02009-03-16 23:22:08 +0000186 NumLValueReference*sizeof(LValueReferenceType)+
187 NumRValueReference*sizeof(RValueReferenceType)+
Sebastian Redl75555032009-01-24 21:16:55 +0000188 NumMemberPointer*sizeof(MemberPointerType)+
Douglas Gregor4fa58902009-02-26 23:50:07 +0000189 NumFunctionP*sizeof(FunctionProtoType)+
190 NumFunctionNP*sizeof(FunctionNoProtoType)+
Steve Naroffe0430632008-05-21 15:59:22 +0000191 NumTypeName*sizeof(TypedefType)+NumTagged*sizeof(TagType)+
Douglas Gregor4fa58902009-02-26 23:50:07 +0000192 NumTypeOfTypes*sizeof(TypeOfType)+NumTypeOfExprTypes*sizeof(TypeOfExprType)));
Chris Lattner4b009652007-07-25 00:24:17 +0000193}
194
195
196void ASTContext::InitBuiltinType(QualType &R, BuiltinType::Kind K) {
Steve Naroff93fd2112009-01-27 22:08:43 +0000197 Types.push_back((R = QualType(new (*this,8) BuiltinType(K),0)).getTypePtr());
Chris Lattner4b009652007-07-25 00:24:17 +0000198}
199
Chris Lattner4b009652007-07-25 00:24:17 +0000200void ASTContext::InitBuiltinTypes() {
201 assert(VoidTy.isNull() && "Context reinitialized?");
202
203 // C99 6.2.5p19.
204 InitBuiltinType(VoidTy, BuiltinType::Void);
205
206 // C99 6.2.5p2.
207 InitBuiltinType(BoolTy, BuiltinType::Bool);
208 // C99 6.2.5p3.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000209 if (Target.isCharSigned())
Chris Lattner4b009652007-07-25 00:24:17 +0000210 InitBuiltinType(CharTy, BuiltinType::Char_S);
211 else
212 InitBuiltinType(CharTy, BuiltinType::Char_U);
213 // C99 6.2.5p4.
214 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
215 InitBuiltinType(ShortTy, BuiltinType::Short);
216 InitBuiltinType(IntTy, BuiltinType::Int);
217 InitBuiltinType(LongTy, BuiltinType::Long);
218 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
219
220 // C99 6.2.5p6.
221 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
222 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
223 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
224 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
225 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
226
227 // C99 6.2.5p10.
228 InitBuiltinType(FloatTy, BuiltinType::Float);
229 InitBuiltinType(DoubleTy, BuiltinType::Double);
230 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argiris Kirtzidis1ed03e72008-08-09 16:51:54 +0000231
Chris Lattnere1dafe72009-02-26 23:43:47 +0000232 if (LangOpts.CPlusPlus) // C++ 3.9.1p5
233 InitBuiltinType(WCharTy, BuiltinType::WChar);
234 else // C99
235 WCharTy = getFromTargetType(Target.getWCharType());
Argiris Kirtzidis1ed03e72008-08-09 16:51:54 +0000236
Douglas Gregord2baafd2008-10-21 16:13:35 +0000237 // Placeholder type for functions.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000238 InitBuiltinType(OverloadTy, BuiltinType::Overload);
239
240 // Placeholder type for type-dependent expressions whose type is
241 // completely unknown. No code should ever check a type against
242 // DependentTy and users should never see it; however, it is here to
243 // help diagnose failures to properly check for type-dependent
244 // expressions.
245 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000246
Chris Lattner4b009652007-07-25 00:24:17 +0000247 // C99 6.2.5p11.
248 FloatComplexTy = getComplexType(FloatTy);
249 DoubleComplexTy = getComplexType(DoubleTy);
250 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000251
Steve Naroff9d12c902007-10-15 14:41:52 +0000252 BuiltinVaListType = QualType();
Ted Kremenek42730c52008-01-07 19:49:32 +0000253 ObjCIdType = QualType();
Steve Naroff9d12c902007-10-15 14:41:52 +0000254 IdStructType = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +0000255 ObjCClassType = QualType();
Anders Carlsson7f23e3d2007-10-31 02:53:19 +0000256 ClassStructType = 0;
257
Ted Kremenek42730c52008-01-07 19:49:32 +0000258 ObjCConstantStringType = QualType();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +0000259
260 // void * type
261 VoidPtrTy = getPointerType(VoidTy);
Chris Lattner4b009652007-07-25 00:24:17 +0000262}
263
264//===----------------------------------------------------------------------===//
265// Type Sizing and Analysis
266//===----------------------------------------------------------------------===//
267
Chris Lattner2a674dc2008-06-30 18:32:54 +0000268/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
269/// scalar floating point type.
270const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
271 const BuiltinType *BT = T->getAsBuiltinType();
272 assert(BT && "Not a floating point type!");
273 switch (BT->getKind()) {
274 default: assert(0 && "Not a floating point type!");
275 case BuiltinType::Float: return Target.getFloatFormat();
276 case BuiltinType::Double: return Target.getDoubleFormat();
277 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
278 }
279}
280
Chris Lattnerbd3153e2009-01-24 21:53:27 +0000281/// getDeclAlign - Return a conservative estimate of the alignment of the
282/// specified decl. Note that bitfields do not have a valid alignment, so
283/// this method will assert on them.
Daniel Dunbar96d1f1b2009-02-17 22:16:19 +0000284unsigned ASTContext::getDeclAlignInBytes(const Decl *D) {
Eli Friedman0ee57322009-02-22 02:56:25 +0000285 unsigned Align = Target.getCharWidth();
286
287 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
288 Align = std::max(Align, AA->getAlignment());
289
Chris Lattnerbd3153e2009-01-24 21:53:27 +0000290 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
291 QualType T = VD->getType();
292 // Incomplete or function types default to 1.
Eli Friedman0ee57322009-02-22 02:56:25 +0000293 if (!T->isIncompleteType() && !T->isFunctionType()) {
294 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
295 T = cast<ArrayType>(T)->getElementType();
296
297 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
298 }
Chris Lattnerbd3153e2009-01-24 21:53:27 +0000299 }
Eli Friedman0ee57322009-02-22 02:56:25 +0000300
301 return Align / Target.getCharWidth();
Chris Lattnerbd3153e2009-01-24 21:53:27 +0000302}
Chris Lattner2a674dc2008-06-30 18:32:54 +0000303
Chris Lattner4b009652007-07-25 00:24:17 +0000304/// getTypeSize - Return the size of the specified type, in bits. This method
305/// does not work on incomplete types.
306std::pair<uint64_t, unsigned>
Daniel Dunbar7d6a5d22008-11-08 05:48:37 +0000307ASTContext::getTypeInfo(const Type *T) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +0000308 T = getCanonicalType(T);
Mike Stump44d1f402009-02-27 18:32:39 +0000309 uint64_t Width=0;
310 unsigned Align=8;
Chris Lattner4b009652007-07-25 00:24:17 +0000311 switch (T->getTypeClass()) {
Douglas Gregor4fa58902009-02-26 23:50:07 +0000312#define TYPE(Class, Base)
313#define ABSTRACT_TYPE(Class, Base)
314#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
315#define DEPENDENT_TYPE(Class, Base) case Type::Class:
316#include "clang/AST/TypeNodes.def"
317 assert(false && "Should not see non-canonical or dependent types");
318 break;
319
Chris Lattner4b009652007-07-25 00:24:17 +0000320 case Type::FunctionNoProto:
321 case Type::FunctionProto:
Douglas Gregor4fa58902009-02-26 23:50:07 +0000322 case Type::IncompleteArray:
Chris Lattner4b009652007-07-25 00:24:17 +0000323 assert(0 && "Incomplete types have no size!");
Steve Naroff83c13012007-08-30 01:06:46 +0000324 case Type::VariableArray:
325 assert(0 && "VLAs not implemented yet!");
326 case Type::ConstantArray: {
Daniel Dunbar7d6a5d22008-11-08 05:48:37 +0000327 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Steve Naroff83c13012007-08-30 01:06:46 +0000328
Chris Lattner8cd0e932008-03-05 18:54:05 +0000329 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000330 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner4b009652007-07-25 00:24:17 +0000331 Align = EltInfo.second;
332 break;
Christopher Lamb82c758b2007-12-29 05:10:55 +0000333 }
Nate Begemanaf6ed502008-04-18 23:10:10 +0000334 case Type::ExtVector:
Chris Lattner4b009652007-07-25 00:24:17 +0000335 case Type::Vector: {
336 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner8cd0e932008-03-05 18:54:05 +0000337 getTypeInfo(cast<VectorType>(T)->getElementType());
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000338 Width = EltInfo.first*cast<VectorType>(T)->getNumElements();
Eli Friedman5949a022008-05-30 09:31:38 +0000339 Align = Width;
Nate Begeman7903d052009-01-18 06:42:49 +0000340 // If the alignment is not a power of 2, round up to the next power of 2.
341 // This happens for non-power-of-2 length vectors.
342 // FIXME: this should probably be a target property.
343 Align = 1 << llvm::Log2_32_Ceil(Align);
Chris Lattner4b009652007-07-25 00:24:17 +0000344 break;
345 }
346
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000347 case Type::Builtin:
Chris Lattner4b009652007-07-25 00:24:17 +0000348 switch (cast<BuiltinType>(T)->getKind()) {
349 default: assert(0 && "Unknown builtin type!");
350 case BuiltinType::Void:
351 assert(0 && "Incomplete types have no size!");
Chris Lattnerb66237b2007-12-19 19:23:28 +0000352 case BuiltinType::Bool:
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000353 Width = Target.getBoolWidth();
354 Align = Target.getBoolAlign();
Chris Lattnerb66237b2007-12-19 19:23:28 +0000355 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000356 case BuiltinType::Char_S:
357 case BuiltinType::Char_U:
358 case BuiltinType::UChar:
Chris Lattnerb66237b2007-12-19 19:23:28 +0000359 case BuiltinType::SChar:
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000360 Width = Target.getCharWidth();
361 Align = Target.getCharAlign();
Chris Lattnerb66237b2007-12-19 19:23:28 +0000362 break;
Argiris Kirtzidis1ed03e72008-08-09 16:51:54 +0000363 case BuiltinType::WChar:
364 Width = Target.getWCharWidth();
365 Align = Target.getWCharAlign();
366 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000367 case BuiltinType::UShort:
Chris Lattnerb66237b2007-12-19 19:23:28 +0000368 case BuiltinType::Short:
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000369 Width = Target.getShortWidth();
370 Align = Target.getShortAlign();
Chris Lattnerb66237b2007-12-19 19:23:28 +0000371 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000372 case BuiltinType::UInt:
Chris Lattnerb66237b2007-12-19 19:23:28 +0000373 case BuiltinType::Int:
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000374 Width = Target.getIntWidth();
375 Align = Target.getIntAlign();
Chris Lattnerb66237b2007-12-19 19:23:28 +0000376 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000377 case BuiltinType::ULong:
Chris Lattnerb66237b2007-12-19 19:23:28 +0000378 case BuiltinType::Long:
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000379 Width = Target.getLongWidth();
380 Align = Target.getLongAlign();
Chris Lattnerb66237b2007-12-19 19:23:28 +0000381 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000382 case BuiltinType::ULongLong:
Chris Lattnerb66237b2007-12-19 19:23:28 +0000383 case BuiltinType::LongLong:
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000384 Width = Target.getLongLongWidth();
385 Align = Target.getLongLongAlign();
Chris Lattnerb66237b2007-12-19 19:23:28 +0000386 break;
387 case BuiltinType::Float:
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000388 Width = Target.getFloatWidth();
389 Align = Target.getFloatAlign();
Chris Lattnerb66237b2007-12-19 19:23:28 +0000390 break;
391 case BuiltinType::Double:
Chris Lattner1d78a862008-04-07 07:01:58 +0000392 Width = Target.getDoubleWidth();
393 Align = Target.getDoubleAlign();
Chris Lattnerb66237b2007-12-19 19:23:28 +0000394 break;
395 case BuiltinType::LongDouble:
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000396 Width = Target.getLongDoubleWidth();
397 Align = Target.getLongDoubleAlign();
Chris Lattnerb66237b2007-12-19 19:23:28 +0000398 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000399 }
400 break;
Eli Friedmanff3fcdf2009-02-13 02:31:07 +0000401 case Type::FixedWidthInt:
402 // FIXME: This isn't precisely correct; the width/alignment should depend
403 // on the available types for the target
404 Width = cast<FixedWidthIntType>(T)->getWidth();
Chris Lattnere9174982009-02-15 21:20:13 +0000405 Width = std::max(llvm::NextPowerOf2(Width - 1), (uint64_t)8);
Eli Friedmanff3fcdf2009-02-13 02:31:07 +0000406 Align = Width;
407 break;
Fariborz Jahanianb60352a2009-02-17 18:27:45 +0000408 case Type::ExtQual:
Chris Lattner8cd0e932008-03-05 18:54:05 +0000409 // FIXME: Pointers into different addr spaces could have different sizes and
410 // alignment requirements: getPointerInfo should take an AddrSpace.
Fariborz Jahanianb60352a2009-02-17 18:27:45 +0000411 return getTypeInfo(QualType(cast<ExtQualType>(T)->getBaseType(), 0));
Ted Kremenek42730c52008-01-07 19:49:32 +0000412 case Type::ObjCQualifiedId:
Eli Friedman2f6d70d2009-02-22 04:02:33 +0000413 case Type::ObjCQualifiedClass:
Douglas Gregor4fa58902009-02-26 23:50:07 +0000414 case Type::ObjCQualifiedInterface:
Chris Lattner1d78a862008-04-07 07:01:58 +0000415 Width = Target.getPointerWidth(0);
Chris Lattner461a6c52008-03-08 08:34:58 +0000416 Align = Target.getPointerAlign(0);
Chris Lattnerb66237b2007-12-19 19:23:28 +0000417 break;
Steve Naroff62f09f52008-09-24 15:05:44 +0000418 case Type::BlockPointer: {
419 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
420 Width = Target.getPointerWidth(AS);
421 Align = Target.getPointerAlign(AS);
422 break;
423 }
Chris Lattner461a6c52008-03-08 08:34:58 +0000424 case Type::Pointer: {
425 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner1d78a862008-04-07 07:01:58 +0000426 Width = Target.getPointerWidth(AS);
Chris Lattner461a6c52008-03-08 08:34:58 +0000427 Align = Target.getPointerAlign(AS);
428 break;
429 }
Sebastian Redlce6fff02009-03-16 23:22:08 +0000430 case Type::LValueReference:
431 case Type::RValueReference:
Chris Lattner4b009652007-07-25 00:24:17 +0000432 // "When applied to a reference or a reference type, the result is the size
433 // of the referenced type." C++98 5.3.3p2: expr.sizeof.
Chris Lattnerb66237b2007-12-19 19:23:28 +0000434 // FIXME: This is wrong for struct layout: a reference in a struct has
435 // pointer size.
Chris Lattnercfac88d2008-04-02 17:35:06 +0000436 return getTypeInfo(cast<ReferenceType>(T)->getPointeeType());
Sebastian Redl75555032009-01-24 21:16:55 +0000437 case Type::MemberPointer: {
Sebastian Redl18cffee2009-01-24 23:29:36 +0000438 // FIXME: This is not only platform- but also ABI-dependent. We follow
Sebastian Redl75555032009-01-24 21:16:55 +0000439 // the GCC ABI, where pointers to data are one pointer large, pointers to
440 // functions two pointers. But if we want to support ABI compatibility with
Sebastian Redl18cffee2009-01-24 23:29:36 +0000441 // other compilers too, we need to delegate this completely to TargetInfo
442 // or some ABI abstraction layer.
Sebastian Redl75555032009-01-24 21:16:55 +0000443 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
444 unsigned AS = Pointee.getAddressSpace();
445 Width = Target.getPointerWidth(AS);
446 if (Pointee->isFunctionType())
447 Width *= 2;
448 Align = Target.getPointerAlign(AS);
449 // GCC aligns at single pointer width.
450 }
Chris Lattner4b009652007-07-25 00:24:17 +0000451 case Type::Complex: {
452 // Complex types have the same alignment as their elements, but twice the
453 // size.
454 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner8cd0e932008-03-05 18:54:05 +0000455 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000456 Width = EltInfo.first*2;
Chris Lattner4b009652007-07-25 00:24:17 +0000457 Align = EltInfo.second;
458 break;
459 }
Devang Patel4b6bf702008-06-04 21:54:36 +0000460 case Type::ObjCInterface: {
Daniel Dunbar7d6a5d22008-11-08 05:48:37 +0000461 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel4b6bf702008-06-04 21:54:36 +0000462 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
463 Width = Layout.getSize();
464 Align = Layout.getAlignment();
465 break;
466 }
Douglas Gregor4fa58902009-02-26 23:50:07 +0000467 case Type::Record:
Douglas Gregor4fa58902009-02-26 23:50:07 +0000468 case Type::Enum: {
Daniel Dunbar7d6a5d22008-11-08 05:48:37 +0000469 const TagType *TT = cast<TagType>(T);
470
471 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattnerfd799692008-08-09 21:35:13 +0000472 Width = 1;
473 Align = 1;
474 break;
475 }
476
Daniel Dunbar7d6a5d22008-11-08 05:48:37 +0000477 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner2bf1d6c2008-04-06 22:05:18 +0000478 return getTypeInfo(ET->getDecl()->getIntegerType());
479
Daniel Dunbar7d6a5d22008-11-08 05:48:37 +0000480 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner2bf1d6c2008-04-06 22:05:18 +0000481 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
482 Width = Layout.getSize();
483 Align = Layout.getAlignment();
Chris Lattner4b009652007-07-25 00:24:17 +0000484 break;
485 }
Douglas Gregordd13e842009-03-30 22:58:21 +0000486
487 case Type::TemplateSpecialization:
488 assert(false && "Dependent types have no size");
489 break;
Chris Lattner2bf1d6c2008-04-06 22:05:18 +0000490 }
Chris Lattner4b009652007-07-25 00:24:17 +0000491
492 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000493 return std::make_pair(Width, Align);
Chris Lattner4b009652007-07-25 00:24:17 +0000494}
495
Chris Lattner83165b52009-01-27 18:08:34 +0000496/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
497/// type for the current target in bits. This can be different than the ABI
498/// alignment in cases where it is beneficial for performance to overalign
499/// a data type.
500unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
501 unsigned ABIAlign = getTypeAlign(T);
502
503 // Doubles should be naturally aligned if possible.
Daniel Dunbarc61a8002009-02-18 19:59:32 +0000504 if (T->isSpecificBuiltinType(BuiltinType::Double))
505 return std::max(ABIAlign, 64U);
Chris Lattner83165b52009-01-27 18:08:34 +0000506
507 return ABIAlign;
508}
509
510
Devang Patelbfe323c2008-06-04 21:22:16 +0000511/// LayoutField - Field layout.
512void ASTRecordLayout::LayoutField(const FieldDecl *FD, unsigned FieldNo,
Daniel Dunbar2cb762f2008-10-16 02:34:03 +0000513 bool IsUnion, unsigned StructPacking,
Devang Patelbfe323c2008-06-04 21:22:16 +0000514 ASTContext &Context) {
Daniel Dunbar2cb762f2008-10-16 02:34:03 +0000515 unsigned FieldPacking = StructPacking;
Devang Patelbfe323c2008-06-04 21:22:16 +0000516 uint64_t FieldOffset = IsUnion ? 0 : Size;
517 uint64_t FieldSize;
518 unsigned FieldAlign;
Daniel Dunbar2cb762f2008-10-16 02:34:03 +0000519
520 // FIXME: Should this override struct packing? Probably we want to
521 // take the minimum?
522 if (const PackedAttr *PA = FD->getAttr<PackedAttr>())
523 FieldPacking = PA->getAlignment();
Devang Patelbfe323c2008-06-04 21:22:16 +0000524
525 if (const Expr *BitWidthExpr = FD->getBitWidth()) {
526 // TODO: Need to check this algorithm on other targets!
527 // (tested on Linux-X86)
Daniel Dunbar7cbcbf42008-08-13 23:47:13 +0000528 FieldSize =
529 BitWidthExpr->getIntegerConstantExprValue(Context).getZExtValue();
Devang Patelbfe323c2008-06-04 21:22:16 +0000530
531 std::pair<uint64_t, unsigned> FieldInfo =
532 Context.getTypeInfo(FD->getType());
533 uint64_t TypeSize = FieldInfo.first;
534
Daniel Dunbar2cb762f2008-10-16 02:34:03 +0000535 // Determine the alignment of this bitfield. The packing
536 // attributes define a maximum and the alignment attribute defines
537 // a minimum.
538 // FIXME: What is the right behavior when the specified alignment
539 // is smaller than the specified packing?
Devang Patelbfe323c2008-06-04 21:22:16 +0000540 FieldAlign = FieldInfo.second;
Daniel Dunbar2cb762f2008-10-16 02:34:03 +0000541 if (FieldPacking)
542 FieldAlign = std::min(FieldAlign, FieldPacking);
Devang Patelbfe323c2008-06-04 21:22:16 +0000543 if (const AlignedAttr *AA = FD->getAttr<AlignedAttr>())
544 FieldAlign = std::max(FieldAlign, AA->getAlignment());
545
546 // Check if we need to add padding to give the field the correct
547 // alignment.
548 if (FieldSize == 0 || (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize)
549 FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1);
550
551 // Padding members don't affect overall alignment
552 if (!FD->getIdentifier())
553 FieldAlign = 1;
554 } else {
Chris Lattnerfd799692008-08-09 21:35:13 +0000555 if (FD->getType()->isIncompleteArrayType()) {
556 // This is a flexible array member; we can't directly
Devang Patelbfe323c2008-06-04 21:22:16 +0000557 // query getTypeInfo about these, so we figure it out here.
558 // Flexible array members don't have any size, but they
559 // have to be aligned appropriately for their element type.
560 FieldSize = 0;
Chris Lattnera1923f62008-08-04 07:31:14 +0000561 const ArrayType* ATy = Context.getAsArrayType(FD->getType());
Devang Patelbfe323c2008-06-04 21:22:16 +0000562 FieldAlign = Context.getTypeAlign(ATy->getElementType());
563 } else {
564 std::pair<uint64_t, unsigned> FieldInfo =
565 Context.getTypeInfo(FD->getType());
566 FieldSize = FieldInfo.first;
567 FieldAlign = FieldInfo.second;
568 }
569
Daniel Dunbar2cb762f2008-10-16 02:34:03 +0000570 // Determine the alignment of this bitfield. The packing
571 // attributes define a maximum and the alignment attribute defines
572 // a minimum. Additionally, the packing alignment must be at least
573 // a byte for non-bitfields.
574 //
575 // FIXME: What is the right behavior when the specified alignment
576 // is smaller than the specified packing?
577 if (FieldPacking)
578 FieldAlign = std::min(FieldAlign, std::max(8U, FieldPacking));
Devang Patelbfe323c2008-06-04 21:22:16 +0000579 if (const AlignedAttr *AA = FD->getAttr<AlignedAttr>())
580 FieldAlign = std::max(FieldAlign, AA->getAlignment());
581
582 // Round up the current record size to the field's alignment boundary.
583 FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1);
584 }
585
586 // Place this field at the current location.
587 FieldOffsets[FieldNo] = FieldOffset;
588
589 // Reserve space for this field.
590 if (IsUnion) {
591 Size = std::max(Size, FieldSize);
592 } else {
593 Size = FieldOffset + FieldSize;
594 }
595
596 // Remember max struct/class alignment.
597 Alignment = std::max(Alignment, FieldAlign);
598}
599
Fariborz Jahaniana2c97df2009-03-05 20:08:48 +0000600void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
Chris Lattner9329cf52009-03-31 08:48:01 +0000601 llvm::SmallVectorImpl<FieldDecl*> &Fields) const {
Fariborz Jahanian0556b152008-12-17 21:40:49 +0000602 const ObjCInterfaceDecl *SuperClass = OI->getSuperClass();
603 if (SuperClass)
604 CollectObjCIvars(SuperClass, Fields);
605 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
606 E = OI->ivar_end(); I != E; ++I) {
Chris Lattner9329cf52009-03-31 08:48:01 +0000607 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahanian0556b152008-12-17 21:40:49 +0000608 if (!IVDecl->isInvalidDecl())
609 Fields.push_back(cast<FieldDecl>(IVDecl));
610 }
Fariborz Jahanianc625fa92009-03-31 00:06:29 +0000611 // look into properties.
612 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
613 E = OI->prop_end(); I != E; ++I) {
Chris Lattner9329cf52009-03-31 08:48:01 +0000614 if (ObjCIvarDecl *IV = (*I)->getPropertyIvarDecl())
Fariborz Jahanianc625fa92009-03-31 00:06:29 +0000615 Fields.push_back(cast<FieldDecl>(IV));
616 }
Fariborz Jahanian0556b152008-12-17 21:40:49 +0000617}
618
619/// addRecordToClass - produces record info. for the class for its
620/// ivars and all those inherited.
621///
Chris Lattner9329cf52009-03-31 08:48:01 +0000622const RecordDecl *ASTContext::addRecordToClass(const ObjCInterfaceDecl *D) {
Chris Lattner608c1e32009-03-31 09:24:30 +0000623 RecordDecl *&RD = ASTRecordForInterface[D];
624 if (RD) {
625 // If we have a record decl already and it is either a definition or if 'D'
626 // is still a forward declaration, return it.
627 if (RD->isDefinition() || D->isForwardDecl())
628 return RD;
629 }
630
631 // If D is a forward declaration, then just make a forward struct decl.
632 if (D->isForwardDecl())
633 return RD = RecordDecl::Create(*this, TagDecl::TK_struct, 0,
634 D->getLocation(),
635 D->getIdentifier());
Chris Lattner9329cf52009-03-31 08:48:01 +0000636
637 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian0556b152008-12-17 21:40:49 +0000638 CollectObjCIvars(D, RecFields);
Chris Lattner608c1e32009-03-31 09:24:30 +0000639
640 if (RD == 0)
641 RD = RecordDecl::Create(*this, TagDecl::TK_struct, 0, D->getLocation(),
642 D->getIdentifier());
Fariborz Jahanian0556b152008-12-17 21:40:49 +0000643 /// FIXME! Can do collection of ivars and adding to the record while
644 /// doing it.
Chris Lattner41b780c2009-03-31 08:58:42 +0000645 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Chris Lattner608c1e32009-03-31 09:24:30 +0000646 RD->addDecl(FieldDecl::Create(*this, RD,
647 RecFields[i]->getLocation(),
648 RecFields[i]->getIdentifier(),
649 RecFields[i]->getType(),
650 RecFields[i]->getBitWidth(), false));
Fariborz Jahanian0556b152008-12-17 21:40:49 +0000651 }
Chris Lattner9329cf52009-03-31 08:48:01 +0000652
Chris Lattner608c1e32009-03-31 09:24:30 +0000653 RD->completeDefinition(*this);
Fariborz Jahanian0556b152008-12-17 21:40:49 +0000654 return RD;
655}
Devang Patel4b6bf702008-06-04 21:54:36 +0000656
Fariborz Jahanianea944842008-12-18 17:29:46 +0000657/// setFieldDecl - maps a field for the given Ivar reference node.
658//
659void ASTContext::setFieldDecl(const ObjCInterfaceDecl *OI,
660 const ObjCIvarDecl *Ivar,
661 const ObjCIvarRefExpr *MRef) {
Chris Lattner04f4db72009-03-31 08:31:13 +0000662 ASTFieldForIvarRef[MRef] = OI->lookupFieldDeclForIvar(*this, Ivar);
Fariborz Jahanianea944842008-12-18 17:29:46 +0000663}
664
Chris Lattner2fda0ed2008-10-05 17:34:18 +0000665/// getASTObjcInterfaceLayout - Get or compute information about the layout of
666/// the specified Objective C, which indicates its size and ivar
Devang Patel4b6bf702008-06-04 21:54:36 +0000667/// position information.
668const ASTRecordLayout &
669ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
670 // Look up this layout, if already laid out, return what we have.
671 const ASTRecordLayout *&Entry = ASTObjCInterfaces[D];
672 if (Entry) return *Entry;
673
674 // Allocate and assign into ASTRecordLayouts here. The "Entry" reference can
675 // be invalidated (dangle) if the ASTRecordLayouts hashtable is inserted into.
Devang Patel8682d882008-06-06 02:14:01 +0000676 ASTRecordLayout *NewEntry = NULL;
677 unsigned FieldCount = D->ivar_size();
678 if (ObjCInterfaceDecl *SD = D->getSuperClass()) {
679 FieldCount++;
680 const ASTRecordLayout &SL = getASTObjCInterfaceLayout(SD);
681 unsigned Alignment = SL.getAlignment();
682 uint64_t Size = SL.getSize();
683 NewEntry = new ASTRecordLayout(Size, Alignment);
684 NewEntry->InitializeLayout(FieldCount);
Chris Lattner2fda0ed2008-10-05 17:34:18 +0000685 // Super class is at the beginning of the layout.
686 NewEntry->SetFieldOffset(0, 0);
Devang Patel8682d882008-06-06 02:14:01 +0000687 } else {
688 NewEntry = new ASTRecordLayout();
689 NewEntry->InitializeLayout(FieldCount);
690 }
Devang Patel4b6bf702008-06-04 21:54:36 +0000691 Entry = NewEntry;
692
Daniel Dunbar2cb762f2008-10-16 02:34:03 +0000693 unsigned StructPacking = 0;
694 if (const PackedAttr *PA = D->getAttr<PackedAttr>())
695 StructPacking = PA->getAlignment();
Devang Patel4b6bf702008-06-04 21:54:36 +0000696
697 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>())
698 NewEntry->SetAlignment(std::max(NewEntry->getAlignment(),
699 AA->getAlignment()));
700
701 // Layout each ivar sequentially.
702 unsigned i = 0;
703 for (ObjCInterfaceDecl::ivar_iterator IVI = D->ivar_begin(),
704 IVE = D->ivar_end(); IVI != IVE; ++IVI) {
705 const ObjCIvarDecl* Ivar = (*IVI);
Daniel Dunbar2cb762f2008-10-16 02:34:03 +0000706 NewEntry->LayoutField(Ivar, i++, false, StructPacking, *this);
Devang Patel4b6bf702008-06-04 21:54:36 +0000707 }
Fariborz Jahanianfbf44642009-03-31 18:11:23 +0000708 // Also synthesized ivars
709 for (ObjCInterfaceDecl::prop_iterator I = D->prop_begin(),
710 E = D->prop_end(); I != E; ++I) {
711 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
712 NewEntry->LayoutField(Ivar, i++, false, StructPacking, *this);
713 }
Devang Patel4b6bf702008-06-04 21:54:36 +0000714
715 // Finally, round the size of the total struct up to the alignment of the
716 // struct itself.
717 NewEntry->FinalizeLayout();
718 return *NewEntry;
719}
720
Devang Patel7a78e432007-11-01 19:11:01 +0000721/// getASTRecordLayout - Get or compute information about the layout of the
Chris Lattner4b009652007-07-25 00:24:17 +0000722/// specified record (struct/union/class), which indicates its size and field
723/// position information.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000724const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
Ted Kremenek46a837c2008-09-05 17:16:31 +0000725 D = D->getDefinition(*this);
726 assert(D && "Cannot get layout of forward declarations!");
Eli Friedman5949a022008-05-30 09:31:38 +0000727
Chris Lattner4b009652007-07-25 00:24:17 +0000728 // Look up this layout, if already laid out, return what we have.
Devang Patel7a78e432007-11-01 19:11:01 +0000729 const ASTRecordLayout *&Entry = ASTRecordLayouts[D];
Chris Lattner4b009652007-07-25 00:24:17 +0000730 if (Entry) return *Entry;
Eli Friedman5949a022008-05-30 09:31:38 +0000731
Devang Patel7a78e432007-11-01 19:11:01 +0000732 // Allocate and assign into ASTRecordLayouts here. The "Entry" reference can
733 // be invalidated (dangle) if the ASTRecordLayouts hashtable is inserted into.
734 ASTRecordLayout *NewEntry = new ASTRecordLayout();
Chris Lattner4b009652007-07-25 00:24:17 +0000735 Entry = NewEntry;
Eli Friedman5949a022008-05-30 09:31:38 +0000736
Douglas Gregor39677622008-12-11 20:41:00 +0000737 // FIXME: Avoid linear walk through the fields, if possible.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000738 NewEntry->InitializeLayout(std::distance(D->field_begin(), D->field_end()));
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +0000739 bool IsUnion = D->isUnion();
Chris Lattner4b009652007-07-25 00:24:17 +0000740
Daniel Dunbar2cb762f2008-10-16 02:34:03 +0000741 unsigned StructPacking = 0;
742 if (const PackedAttr *PA = D->getAttr<PackedAttr>())
743 StructPacking = PA->getAlignment();
744
Eli Friedman5949a022008-05-30 09:31:38 +0000745 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>())
Devang Patelbfe323c2008-06-04 21:22:16 +0000746 NewEntry->SetAlignment(std::max(NewEntry->getAlignment(),
747 AA->getAlignment()));
Anders Carlsson058237f2008-02-18 07:13:09 +0000748
Eli Friedman5949a022008-05-30 09:31:38 +0000749 // Layout each field, for now, just sequentially, respecting alignment. In
750 // the future, this will need to be tweakable by targets.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000751 unsigned FieldIdx = 0;
Douglas Gregor5d764842009-01-09 17:18:27 +0000752 for (RecordDecl::field_iterator Field = D->field_begin(),
753 FieldEnd = D->field_end();
Douglas Gregor8acb7272008-12-11 16:49:14 +0000754 Field != FieldEnd; (void)++Field, ++FieldIdx)
755 NewEntry->LayoutField(*Field, FieldIdx, IsUnion, StructPacking, *this);
Eli Friedman5949a022008-05-30 09:31:38 +0000756
757 // Finally, round the size of the total struct up to the alignment of the
758 // struct itself.
Devang Patelbfe323c2008-06-04 21:22:16 +0000759 NewEntry->FinalizeLayout();
Chris Lattner4b009652007-07-25 00:24:17 +0000760 return *NewEntry;
761}
762
Chris Lattner4b009652007-07-25 00:24:17 +0000763//===----------------------------------------------------------------------===//
764// Type creation/memoization methods
765//===----------------------------------------------------------------------===//
766
Fariborz Jahanianb60352a2009-02-17 18:27:45 +0000767QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +0000768 QualType CanT = getCanonicalType(T);
769 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner35fef522008-02-20 20:55:12 +0000770 return T;
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000771
772 // If we are composing extended qualifiers together, merge together into one
773 // ExtQualType node.
774 unsigned CVRQuals = T.getCVRQualifiers();
775 QualType::GCAttrTypes GCAttr = QualType::GCNone;
776 Type *TypeNode = T.getTypePtr();
Chris Lattner35fef522008-02-20 20:55:12 +0000777
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000778 if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
779 // If this type already has an address space specified, it cannot get
780 // another one.
781 assert(EQT->getAddressSpace() == 0 &&
782 "Type cannot be in multiple addr spaces!");
783 GCAttr = EQT->getObjCGCAttr();
784 TypeNode = EQT->getBaseType();
785 }
Chris Lattner35fef522008-02-20 20:55:12 +0000786
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000787 // Check if we've already instantiated this type.
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000788 llvm::FoldingSetNodeID ID;
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000789 ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000790 void *InsertPos = 0;
Fariborz Jahanianb60352a2009-02-17 18:27:45 +0000791 if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000792 return QualType(EXTQy, CVRQuals);
793
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000794 // If the base type isn't canonical, this won't be a canonical type either,
795 // so fill in the canonical type field.
796 QualType Canonical;
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000797 if (!TypeNode->isCanonical()) {
Fariborz Jahanianb60352a2009-02-17 18:27:45 +0000798 Canonical = getAddrSpaceQualType(CanT, AddressSpace);
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000799
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000800 // Update InsertPos, the previous call could have invalidated it.
Fariborz Jahanianb60352a2009-02-17 18:27:45 +0000801 ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattner578a37e2008-10-12 00:26:57 +0000802 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000803 }
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000804 ExtQualType *New =
805 new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
Fariborz Jahanianb60352a2009-02-17 18:27:45 +0000806 ExtQualTypes.InsertNode(New, InsertPos);
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000807 Types.push_back(New);
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000808 return QualType(New, CVRQuals);
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000809}
810
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000811QualType ASTContext::getObjCGCQualType(QualType T,
812 QualType::GCAttrTypes GCAttr) {
Fariborz Jahanianaf238092009-02-18 05:09:49 +0000813 QualType CanT = getCanonicalType(T);
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000814 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahanianaf238092009-02-18 05:09:49 +0000815 return T;
816
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000817 // If we are composing extended qualifiers together, merge together into one
818 // ExtQualType node.
819 unsigned CVRQuals = T.getCVRQualifiers();
820 Type *TypeNode = T.getTypePtr();
821 unsigned AddressSpace = 0;
822
823 if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
824 // If this type already has an address space specified, it cannot get
825 // another one.
826 assert(EQT->getObjCGCAttr() == QualType::GCNone &&
827 "Type cannot be in multiple addr spaces!");
828 AddressSpace = EQT->getAddressSpace();
829 TypeNode = EQT->getBaseType();
830 }
Fariborz Jahanianaf238092009-02-18 05:09:49 +0000831
832 // Check if we've already instantiated an gc qual'd type of this type.
833 llvm::FoldingSetNodeID ID;
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000834 ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
Fariborz Jahanianaf238092009-02-18 05:09:49 +0000835 void *InsertPos = 0;
836 if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000837 return QualType(EXTQy, CVRQuals);
Fariborz Jahanianaf238092009-02-18 05:09:49 +0000838
839 // If the base type isn't canonical, this won't be a canonical type either,
840 // so fill in the canonical type field.
Eli Friedman94fcc9a2009-02-27 23:04:43 +0000841 // FIXME: Isn't this also not canonical if the base type is a array
842 // or pointer type? I can't find any documentation for objc_gc, though...
Fariborz Jahanianaf238092009-02-18 05:09:49 +0000843 QualType Canonical;
844 if (!T->isCanonical()) {
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000845 Canonical = getObjCGCQualType(CanT, GCAttr);
Fariborz Jahanianaf238092009-02-18 05:09:49 +0000846
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000847 // Update InsertPos, the previous call could have invalidated it.
Fariborz Jahanianaf238092009-02-18 05:09:49 +0000848 ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
849 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
850 }
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000851 ExtQualType *New =
852 new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
Fariborz Jahanianaf238092009-02-18 05:09:49 +0000853 ExtQualTypes.InsertNode(New, InsertPos);
854 Types.push_back(New);
Chris Lattner18b5a9a2009-02-18 22:53:11 +0000855 return QualType(New, CVRQuals);
Fariborz Jahanianaf238092009-02-18 05:09:49 +0000856}
Chris Lattner4b009652007-07-25 00:24:17 +0000857
858/// getComplexType - Return the uniqued reference to the type for a complex
859/// number with the specified element type.
860QualType ASTContext::getComplexType(QualType T) {
861 // Unique pointers, to guarantee there is only one pointer of a particular
862 // structure.
863 llvm::FoldingSetNodeID ID;
864 ComplexType::Profile(ID, T);
865
866 void *InsertPos = 0;
867 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
868 return QualType(CT, 0);
869
870 // If the pointee type isn't canonical, this won't be a canonical type either,
871 // so fill in the canonical type field.
872 QualType Canonical;
873 if (!T->isCanonical()) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +0000874 Canonical = getComplexType(getCanonicalType(T));
Chris Lattner4b009652007-07-25 00:24:17 +0000875
876 // Get the new insert position for the node we care about.
877 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattner578a37e2008-10-12 00:26:57 +0000878 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner4b009652007-07-25 00:24:17 +0000879 }
Steve Naroff93fd2112009-01-27 22:08:43 +0000880 ComplexType *New = new (*this,8) ComplexType(T, Canonical);
Chris Lattner4b009652007-07-25 00:24:17 +0000881 Types.push_back(New);
882 ComplexTypes.InsertNode(New, InsertPos);
883 return QualType(New, 0);
884}
885
Eli Friedmanff3fcdf2009-02-13 02:31:07 +0000886QualType ASTContext::getFixedWidthIntType(unsigned Width, bool Signed) {
887 llvm::DenseMap<unsigned, FixedWidthIntType*> &Map = Signed ?
888 SignedFixedWidthIntTypes : UnsignedFixedWidthIntTypes;
889 FixedWidthIntType *&Entry = Map[Width];
890 if (!Entry)
891 Entry = new FixedWidthIntType(Width, Signed);
892 return QualType(Entry, 0);
893}
Chris Lattner4b009652007-07-25 00:24:17 +0000894
895/// getPointerType - Return the uniqued reference to the type for a pointer to
896/// the specified type.
897QualType ASTContext::getPointerType(QualType T) {
898 // Unique pointers, to guarantee there is only one pointer of a particular
899 // structure.
900 llvm::FoldingSetNodeID ID;
901 PointerType::Profile(ID, T);
902
903 void *InsertPos = 0;
904 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
905 return QualType(PT, 0);
906
907 // If the pointee type isn't canonical, this won't be a canonical type either,
908 // so fill in the canonical type field.
909 QualType Canonical;
910 if (!T->isCanonical()) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +0000911 Canonical = getPointerType(getCanonicalType(T));
Chris Lattner4b009652007-07-25 00:24:17 +0000912
913 // Get the new insert position for the node we care about.
914 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattner578a37e2008-10-12 00:26:57 +0000915 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner4b009652007-07-25 00:24:17 +0000916 }
Steve Naroff93fd2112009-01-27 22:08:43 +0000917 PointerType *New = new (*this,8) PointerType(T, Canonical);
Chris Lattner4b009652007-07-25 00:24:17 +0000918 Types.push_back(New);
919 PointerTypes.InsertNode(New, InsertPos);
920 return QualType(New, 0);
921}
922
Steve Naroff7aa54752008-08-27 16:04:49 +0000923/// getBlockPointerType - Return the uniqued reference to the type for
924/// a pointer to the specified block.
925QualType ASTContext::getBlockPointerType(QualType T) {
Steve Narofffd5b19d2008-08-28 19:20:44 +0000926 assert(T->isFunctionType() && "block of function types only");
927 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff7aa54752008-08-27 16:04:49 +0000928 // structure.
929 llvm::FoldingSetNodeID ID;
930 BlockPointerType::Profile(ID, T);
931
932 void *InsertPos = 0;
933 if (BlockPointerType *PT =
934 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
935 return QualType(PT, 0);
936
Steve Narofffd5b19d2008-08-28 19:20:44 +0000937 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff7aa54752008-08-27 16:04:49 +0000938 // type either so fill in the canonical type field.
939 QualType Canonical;
940 if (!T->isCanonical()) {
941 Canonical = getBlockPointerType(getCanonicalType(T));
942
943 // Get the new insert position for the node we care about.
944 BlockPointerType *NewIP =
945 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattner578a37e2008-10-12 00:26:57 +0000946 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff7aa54752008-08-27 16:04:49 +0000947 }
Steve Naroff93fd2112009-01-27 22:08:43 +0000948 BlockPointerType *New = new (*this,8) BlockPointerType(T, Canonical);
Steve Naroff7aa54752008-08-27 16:04:49 +0000949 Types.push_back(New);
950 BlockPointerTypes.InsertNode(New, InsertPos);
951 return QualType(New, 0);
952}
953
Sebastian Redlce6fff02009-03-16 23:22:08 +0000954/// getLValueReferenceType - Return the uniqued reference to the type for an
955/// lvalue reference to the specified type.
956QualType ASTContext::getLValueReferenceType(QualType T) {
Chris Lattner4b009652007-07-25 00:24:17 +0000957 // Unique pointers, to guarantee there is only one pointer of a particular
958 // structure.
959 llvm::FoldingSetNodeID ID;
960 ReferenceType::Profile(ID, T);
961
962 void *InsertPos = 0;
Sebastian Redlce6fff02009-03-16 23:22:08 +0000963 if (LValueReferenceType *RT =
964 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattner4b009652007-07-25 00:24:17 +0000965 return QualType(RT, 0);
Sebastian Redlce6fff02009-03-16 23:22:08 +0000966
Chris Lattner4b009652007-07-25 00:24:17 +0000967 // If the referencee type isn't canonical, this won't be a canonical type
968 // either, so fill in the canonical type field.
969 QualType Canonical;
970 if (!T->isCanonical()) {
Sebastian Redlce6fff02009-03-16 23:22:08 +0000971 Canonical = getLValueReferenceType(getCanonicalType(T));
972
Chris Lattner4b009652007-07-25 00:24:17 +0000973 // Get the new insert position for the node we care about.
Sebastian Redlce6fff02009-03-16 23:22:08 +0000974 LValueReferenceType *NewIP =
975 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattner578a37e2008-10-12 00:26:57 +0000976 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner4b009652007-07-25 00:24:17 +0000977 }
978
Sebastian Redlce6fff02009-03-16 23:22:08 +0000979 LValueReferenceType *New = new (*this,8) LValueReferenceType(T, Canonical);
Chris Lattner4b009652007-07-25 00:24:17 +0000980 Types.push_back(New);
Sebastian Redlce6fff02009-03-16 23:22:08 +0000981 LValueReferenceTypes.InsertNode(New, InsertPos);
982 return QualType(New, 0);
983}
984
985/// getRValueReferenceType - Return the uniqued reference to the type for an
986/// rvalue reference to the specified type.
987QualType ASTContext::getRValueReferenceType(QualType T) {
988 // Unique pointers, to guarantee there is only one pointer of a particular
989 // structure.
990 llvm::FoldingSetNodeID ID;
991 ReferenceType::Profile(ID, T);
992
993 void *InsertPos = 0;
994 if (RValueReferenceType *RT =
995 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
996 return QualType(RT, 0);
997
998 // If the referencee type isn't canonical, this won't be a canonical type
999 // either, so fill in the canonical type field.
1000 QualType Canonical;
1001 if (!T->isCanonical()) {
1002 Canonical = getRValueReferenceType(getCanonicalType(T));
1003
1004 // Get the new insert position for the node we care about.
1005 RValueReferenceType *NewIP =
1006 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1007 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1008 }
1009
1010 RValueReferenceType *New = new (*this,8) RValueReferenceType(T, Canonical);
1011 Types.push_back(New);
1012 RValueReferenceTypes.InsertNode(New, InsertPos);
Chris Lattner4b009652007-07-25 00:24:17 +00001013 return QualType(New, 0);
1014}
1015
Sebastian Redl75555032009-01-24 21:16:55 +00001016/// getMemberPointerType - Return the uniqued reference to the type for a
1017/// member pointer to the specified type, in the specified class.
1018QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls)
1019{
1020 // Unique pointers, to guarantee there is only one pointer of a particular
1021 // structure.
1022 llvm::FoldingSetNodeID ID;
1023 MemberPointerType::Profile(ID, T, Cls);
1024
1025 void *InsertPos = 0;
1026 if (MemberPointerType *PT =
1027 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1028 return QualType(PT, 0);
1029
1030 // If the pointee or class type isn't canonical, this won't be a canonical
1031 // type either, so fill in the canonical type field.
1032 QualType Canonical;
1033 if (!T->isCanonical()) {
1034 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1035
1036 // Get the new insert position for the node we care about.
1037 MemberPointerType *NewIP =
1038 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1039 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1040 }
Steve Naroff93fd2112009-01-27 22:08:43 +00001041 MemberPointerType *New = new (*this,8) MemberPointerType(T, Cls, Canonical);
Sebastian Redl75555032009-01-24 21:16:55 +00001042 Types.push_back(New);
1043 MemberPointerTypes.InsertNode(New, InsertPos);
1044 return QualType(New, 0);
1045}
1046
Steve Naroff83c13012007-08-30 01:06:46 +00001047/// getConstantArrayType - Return the unique reference to the type for an
1048/// array of the specified element type.
1049QualType ASTContext::getConstantArrayType(QualType EltTy,
Steve Naroff24c9b982007-08-30 18:10:14 +00001050 const llvm::APInt &ArySize,
1051 ArrayType::ArraySizeModifier ASM,
1052 unsigned EltTypeQuals) {
Chris Lattner4b009652007-07-25 00:24:17 +00001053 llvm::FoldingSetNodeID ID;
Chris Lattner3f7a8f12009-02-19 17:31:02 +00001054 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Chris Lattner4b009652007-07-25 00:24:17 +00001055
1056 void *InsertPos = 0;
Ted Kremenek738e6c02007-10-31 17:10:13 +00001057 if (ConstantArrayType *ATP =
1058 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattner4b009652007-07-25 00:24:17 +00001059 return QualType(ATP, 0);
1060
1061 // If the element type isn't canonical, this won't be a canonical type either,
1062 // so fill in the canonical type field.
1063 QualType Canonical;
1064 if (!EltTy->isCanonical()) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001065 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroff24c9b982007-08-30 18:10:14 +00001066 ASM, EltTypeQuals);
Chris Lattner4b009652007-07-25 00:24:17 +00001067 // Get the new insert position for the node we care about.
Ted Kremenek738e6c02007-10-31 17:10:13 +00001068 ConstantArrayType *NewIP =
1069 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattner578a37e2008-10-12 00:26:57 +00001070 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner4b009652007-07-25 00:24:17 +00001071 }
1072
Ted Kremenekc70e7d02009-01-19 21:31:22 +00001073 ConstantArrayType *New =
Steve Naroff93fd2112009-01-27 22:08:43 +00001074 new(*this,8)ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek738e6c02007-10-31 17:10:13 +00001075 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner4b009652007-07-25 00:24:17 +00001076 Types.push_back(New);
1077 return QualType(New, 0);
1078}
1079
Steve Naroffe2579e32007-08-30 18:14:25 +00001080/// getVariableArrayType - Returns a non-unique reference to the type for a
1081/// variable array of the specified element type.
Steve Naroff24c9b982007-08-30 18:10:14 +00001082QualType ASTContext::getVariableArrayType(QualType EltTy, Expr *NumElts,
1083 ArrayType::ArraySizeModifier ASM,
1084 unsigned EltTypeQuals) {
Eli Friedman8ff07782008-02-15 18:16:39 +00001085 // Since we don't unique expressions, it isn't possible to unique VLA's
1086 // that have an expression provided for their size.
1087
Ted Kremenekc70e7d02009-01-19 21:31:22 +00001088 VariableArrayType *New =
Steve Naroff93fd2112009-01-27 22:08:43 +00001089 new(*this,8)VariableArrayType(EltTy,QualType(), NumElts, ASM, EltTypeQuals);
Eli Friedman8ff07782008-02-15 18:16:39 +00001090
1091 VariableArrayTypes.push_back(New);
1092 Types.push_back(New);
1093 return QualType(New, 0);
1094}
1095
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001096/// getDependentSizedArrayType - Returns a non-unique reference to
1097/// the type for a dependently-sized array of the specified element
1098/// type. FIXME: We will need these to be uniqued, or at least
1099/// comparable, at some point.
1100QualType ASTContext::getDependentSizedArrayType(QualType EltTy, Expr *NumElts,
1101 ArrayType::ArraySizeModifier ASM,
1102 unsigned EltTypeQuals) {
1103 assert((NumElts->isTypeDependent() || NumElts->isValueDependent()) &&
1104 "Size must be type- or value-dependent!");
1105
1106 // Since we don't unique expressions, it isn't possible to unique
1107 // dependently-sized array types.
1108
Ted Kremenekc70e7d02009-01-19 21:31:22 +00001109 DependentSizedArrayType *New =
Steve Naroff93fd2112009-01-27 22:08:43 +00001110 new (*this,8) DependentSizedArrayType(EltTy, QualType(), NumElts,
1111 ASM, EltTypeQuals);
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001112
1113 DependentSizedArrayTypes.push_back(New);
1114 Types.push_back(New);
1115 return QualType(New, 0);
1116}
1117
Eli Friedman8ff07782008-02-15 18:16:39 +00001118QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1119 ArrayType::ArraySizeModifier ASM,
1120 unsigned EltTypeQuals) {
1121 llvm::FoldingSetNodeID ID;
Chris Lattner3f7a8f12009-02-19 17:31:02 +00001122 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedman8ff07782008-02-15 18:16:39 +00001123
1124 void *InsertPos = 0;
1125 if (IncompleteArrayType *ATP =
1126 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1127 return QualType(ATP, 0);
1128
1129 // If the element type isn't canonical, this won't be a canonical type
1130 // either, so fill in the canonical type field.
1131 QualType Canonical;
1132
1133 if (!EltTy->isCanonical()) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001134 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek3793e1a2007-10-29 23:37:31 +00001135 ASM, EltTypeQuals);
Eli Friedman8ff07782008-02-15 18:16:39 +00001136
1137 // Get the new insert position for the node we care about.
1138 IncompleteArrayType *NewIP =
1139 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattner578a37e2008-10-12 00:26:57 +00001140 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek3793e1a2007-10-29 23:37:31 +00001141 }
Eli Friedman8ff07782008-02-15 18:16:39 +00001142
Steve Naroff93fd2112009-01-27 22:08:43 +00001143 IncompleteArrayType *New = new (*this,8) IncompleteArrayType(EltTy, Canonical,
Ted Kremenekc70e7d02009-01-19 21:31:22 +00001144 ASM, EltTypeQuals);
Eli Friedman8ff07782008-02-15 18:16:39 +00001145
1146 IncompleteArrayTypes.InsertNode(New, InsertPos);
1147 Types.push_back(New);
1148 return QualType(New, 0);
Steve Naroff83c13012007-08-30 01:06:46 +00001149}
1150
Chris Lattner4b009652007-07-25 00:24:17 +00001151/// getVectorType - Return the unique reference to a vector type of
1152/// the specified element type and size. VectorType must be a built-in type.
1153QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) {
1154 BuiltinType *baseType;
1155
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001156 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Chris Lattner4b009652007-07-25 00:24:17 +00001157 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
1158
1159 // Check if we've already instantiated a vector of this type.
1160 llvm::FoldingSetNodeID ID;
1161 VectorType::Profile(ID, vecType, NumElts, Type::Vector);
1162 void *InsertPos = 0;
1163 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1164 return QualType(VTP, 0);
1165
1166 // If the element type isn't canonical, this won't be a canonical type either,
1167 // so fill in the canonical type field.
1168 QualType Canonical;
1169 if (!vecType->isCanonical()) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001170 Canonical = getVectorType(getCanonicalType(vecType), NumElts);
Chris Lattner4b009652007-07-25 00:24:17 +00001171
1172 // Get the new insert position for the node we care about.
1173 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattner578a37e2008-10-12 00:26:57 +00001174 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner4b009652007-07-25 00:24:17 +00001175 }
Steve Naroff93fd2112009-01-27 22:08:43 +00001176 VectorType *New = new (*this,8) VectorType(vecType, NumElts, Canonical);
Chris Lattner4b009652007-07-25 00:24:17 +00001177 VectorTypes.InsertNode(New, InsertPos);
1178 Types.push_back(New);
1179 return QualType(New, 0);
1180}
1181
Nate Begemanaf6ed502008-04-18 23:10:10 +00001182/// getExtVectorType - Return the unique reference to an extended vector type of
Chris Lattner4b009652007-07-25 00:24:17 +00001183/// the specified element type and size. VectorType must be a built-in type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00001184QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Chris Lattner4b009652007-07-25 00:24:17 +00001185 BuiltinType *baseType;
1186
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001187 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begemanaf6ed502008-04-18 23:10:10 +00001188 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Chris Lattner4b009652007-07-25 00:24:17 +00001189
1190 // Check if we've already instantiated a vector of this type.
1191 llvm::FoldingSetNodeID ID;
Nate Begemanaf6ed502008-04-18 23:10:10 +00001192 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector);
Chris Lattner4b009652007-07-25 00:24:17 +00001193 void *InsertPos = 0;
1194 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1195 return QualType(VTP, 0);
1196
1197 // If the element type isn't canonical, this won't be a canonical type either,
1198 // so fill in the canonical type field.
1199 QualType Canonical;
1200 if (!vecType->isCanonical()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001201 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Chris Lattner4b009652007-07-25 00:24:17 +00001202
1203 // Get the new insert position for the node we care about.
1204 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattner578a37e2008-10-12 00:26:57 +00001205 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner4b009652007-07-25 00:24:17 +00001206 }
Steve Naroff93fd2112009-01-27 22:08:43 +00001207 ExtVectorType *New = new (*this,8) ExtVectorType(vecType, NumElts, Canonical);
Chris Lattner4b009652007-07-25 00:24:17 +00001208 VectorTypes.InsertNode(New, InsertPos);
1209 Types.push_back(New);
1210 return QualType(New, 0);
1211}
1212
Douglas Gregor4fa58902009-02-26 23:50:07 +00001213/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattner4b009652007-07-25 00:24:17 +00001214///
Douglas Gregor4fa58902009-02-26 23:50:07 +00001215QualType ASTContext::getFunctionNoProtoType(QualType ResultTy) {
Chris Lattner4b009652007-07-25 00:24:17 +00001216 // Unique functions, to guarantee there is only one function of a particular
1217 // structure.
1218 llvm::FoldingSetNodeID ID;
Douglas Gregor4fa58902009-02-26 23:50:07 +00001219 FunctionNoProtoType::Profile(ID, ResultTy);
Chris Lattner4b009652007-07-25 00:24:17 +00001220
1221 void *InsertPos = 0;
Douglas Gregor4fa58902009-02-26 23:50:07 +00001222 if (FunctionNoProtoType *FT =
1223 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattner4b009652007-07-25 00:24:17 +00001224 return QualType(FT, 0);
1225
1226 QualType Canonical;
1227 if (!ResultTy->isCanonical()) {
Douglas Gregor4fa58902009-02-26 23:50:07 +00001228 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy));
Chris Lattner4b009652007-07-25 00:24:17 +00001229
1230 // Get the new insert position for the node we care about.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001231 FunctionNoProtoType *NewIP =
1232 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattner578a37e2008-10-12 00:26:57 +00001233 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner4b009652007-07-25 00:24:17 +00001234 }
1235
Douglas Gregor4fa58902009-02-26 23:50:07 +00001236 FunctionNoProtoType *New =new(*this,8)FunctionNoProtoType(ResultTy,Canonical);
Chris Lattner4b009652007-07-25 00:24:17 +00001237 Types.push_back(New);
Douglas Gregor4fa58902009-02-26 23:50:07 +00001238 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Chris Lattner4b009652007-07-25 00:24:17 +00001239 return QualType(New, 0);
1240}
1241
1242/// getFunctionType - Return a normal function type with a typed argument
1243/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner2fda0ed2008-10-05 17:34:18 +00001244QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argiris Kirtzidis4b269b42008-10-24 21:46:40 +00001245 unsigned NumArgs, bool isVariadic,
1246 unsigned TypeQuals) {
Chris Lattner4b009652007-07-25 00:24:17 +00001247 // Unique functions, to guarantee there is only one function of a particular
1248 // structure.
1249 llvm::FoldingSetNodeID ID;
Douglas Gregor4fa58902009-02-26 23:50:07 +00001250 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Argiris Kirtzidis4b269b42008-10-24 21:46:40 +00001251 TypeQuals);
Chris Lattner4b009652007-07-25 00:24:17 +00001252
1253 void *InsertPos = 0;
Douglas Gregor4fa58902009-02-26 23:50:07 +00001254 if (FunctionProtoType *FTP =
1255 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattner4b009652007-07-25 00:24:17 +00001256 return QualType(FTP, 0);
1257
1258 // Determine whether the type being created is already canonical or not.
1259 bool isCanonical = ResultTy->isCanonical();
1260 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
1261 if (!ArgArray[i]->isCanonical())
1262 isCanonical = false;
1263
1264 // If this type isn't canonical, get the canonical version of it.
1265 QualType Canonical;
1266 if (!isCanonical) {
1267 llvm::SmallVector<QualType, 16> CanonicalArgs;
1268 CanonicalArgs.reserve(NumArgs);
1269 for (unsigned i = 0; i != NumArgs; ++i)
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001270 CanonicalArgs.push_back(getCanonicalType(ArgArray[i]));
Chris Lattner4b009652007-07-25 00:24:17 +00001271
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001272 Canonical = getFunctionType(getCanonicalType(ResultTy),
Chris Lattner4b009652007-07-25 00:24:17 +00001273 &CanonicalArgs[0], NumArgs,
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00001274 isVariadic, TypeQuals);
Chris Lattner4b009652007-07-25 00:24:17 +00001275
1276 // Get the new insert position for the node we care about.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001277 FunctionProtoType *NewIP =
1278 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattner578a37e2008-10-12 00:26:57 +00001279 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Chris Lattner4b009652007-07-25 00:24:17 +00001280 }
1281
Douglas Gregor4fa58902009-02-26 23:50:07 +00001282 // FunctionProtoType objects are allocated with extra bytes after them
Ted Kremenekc70e7d02009-01-19 21:31:22 +00001283 // for a variable size array (for parameter types) at the end of them.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001284 FunctionProtoType *FTP =
1285 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
Steve Naroff207b9ec2009-01-27 23:20:32 +00001286 NumArgs*sizeof(QualType), 8);
Douglas Gregor4fa58902009-02-26 23:50:07 +00001287 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Argiris Kirtzidis4b269b42008-10-24 21:46:40 +00001288 TypeQuals, Canonical);
Chris Lattner4b009652007-07-25 00:24:17 +00001289 Types.push_back(FTP);
Douglas Gregor4fa58902009-02-26 23:50:07 +00001290 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Chris Lattner4b009652007-07-25 00:24:17 +00001291 return QualType(FTP, 0);
1292}
1293
Douglas Gregor1d661552008-04-13 21:07:44 +00001294/// getTypeDeclType - Return the unique reference to the type for the
1295/// specified type declaration.
Ted Kremenek46a837c2008-09-05 17:16:31 +00001296QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) {
Argiris Kirtzidiseeec5482008-10-16 16:50:47 +00001297 assert(Decl && "Passed null for Decl param");
Douglas Gregor1d661552008-04-13 21:07:44 +00001298 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1299
Argiris Kirtzidiseeec5482008-10-16 16:50:47 +00001300 if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor1d661552008-04-13 21:07:44 +00001301 return getTypedefType(Typedef);
Douglas Gregora4918772009-02-05 23:33:38 +00001302 else if (isa<TemplateTypeParmDecl>(Decl)) {
1303 assert(false && "Template type parameter types are always available.");
1304 } else if (ObjCInterfaceDecl *ObjCInterface = dyn_cast<ObjCInterfaceDecl>(Decl))
Douglas Gregor1d661552008-04-13 21:07:44 +00001305 return getObjCInterfaceType(ObjCInterface);
Argiris Kirtzidisea29d1e2008-08-07 20:55:28 +00001306
Douglas Gregor2e047592009-02-28 01:32:25 +00001307 if (RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Ted Kremenekc70e7d02009-01-19 21:31:22 +00001308 if (PrevDecl)
1309 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Naroff93fd2112009-01-27 22:08:43 +00001310 else
1311 Decl->TypeForDecl = new (*this,8) RecordType(Record);
Ted Kremenek46a837c2008-09-05 17:16:31 +00001312 }
Ted Kremenekc70e7d02009-01-19 21:31:22 +00001313 else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
1314 if (PrevDecl)
1315 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Naroff93fd2112009-01-27 22:08:43 +00001316 else
1317 Decl->TypeForDecl = new (*this,8) EnumType(Enum);
Ted Kremenekc70e7d02009-01-19 21:31:22 +00001318 }
Argiris Kirtzidisea29d1e2008-08-07 20:55:28 +00001319 else
Douglas Gregor1d661552008-04-13 21:07:44 +00001320 assert(false && "TypeDecl without a type?");
Argiris Kirtzidisea29d1e2008-08-07 20:55:28 +00001321
Ted Kremenek46a837c2008-09-05 17:16:31 +00001322 if (!PrevDecl) Types.push_back(Decl->TypeForDecl);
Argiris Kirtzidisea29d1e2008-08-07 20:55:28 +00001323 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor1d661552008-04-13 21:07:44 +00001324}
1325
Chris Lattner4b009652007-07-25 00:24:17 +00001326/// getTypedefType - Return the unique reference to the type for the
1327/// specified typename decl.
1328QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
1329 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1330
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001331 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
Douglas Gregor4fa58902009-02-26 23:50:07 +00001332 Decl->TypeForDecl = new(*this,8) TypedefType(Type::Typedef, Decl, Canonical);
Chris Lattner4b009652007-07-25 00:24:17 +00001333 Types.push_back(Decl->TypeForDecl);
1334 return QualType(Decl->TypeForDecl, 0);
1335}
1336
Ted Kremenek42730c52008-01-07 19:49:32 +00001337/// getObjCInterfaceType - Return the unique reference to the type for the
Steve Naroff81f1bba2007-09-06 21:24:23 +00001338/// specified ObjC interface decl.
Ted Kremenek42730c52008-01-07 19:49:32 +00001339QualType ASTContext::getObjCInterfaceType(ObjCInterfaceDecl *Decl) {
Steve Naroff81f1bba2007-09-06 21:24:23 +00001340 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1341
Steve Naroff93fd2112009-01-27 22:08:43 +00001342 Decl->TypeForDecl = new(*this,8) ObjCInterfaceType(Type::ObjCInterface, Decl);
Steve Naroff81f1bba2007-09-06 21:24:23 +00001343 Types.push_back(Decl->TypeForDecl);
1344 return QualType(Decl->TypeForDecl, 0);
1345}
1346
Douglas Gregora4918772009-02-05 23:33:38 +00001347/// \brief Retrieve the template type parameter type for a template
1348/// parameter with the given depth, index, and (optionally) name.
1349QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
1350 IdentifierInfo *Name) {
1351 llvm::FoldingSetNodeID ID;
1352 TemplateTypeParmType::Profile(ID, Depth, Index, Name);
1353 void *InsertPos = 0;
1354 TemplateTypeParmType *TypeParm
1355 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1356
1357 if (TypeParm)
1358 return QualType(TypeParm, 0);
1359
1360 if (Name)
1361 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, Name,
1362 getTemplateTypeParmType(Depth, Index));
1363 else
1364 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index);
1365
1366 Types.push_back(TypeParm);
1367 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1368
1369 return QualType(TypeParm, 0);
1370}
1371
Douglas Gregor8e458f42009-02-09 18:46:07 +00001372QualType
Douglas Gregordd13e842009-03-30 22:58:21 +00001373ASTContext::getTemplateSpecializationType(TemplateName Template,
1374 const TemplateArgument *Args,
1375 unsigned NumArgs,
1376 QualType Canon) {
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001377 if (!Canon.isNull())
1378 Canon = getCanonicalType(Canon);
Douglas Gregor9c7825b2009-02-26 22:19:44 +00001379
Douglas Gregor8e458f42009-02-09 18:46:07 +00001380 llvm::FoldingSetNodeID ID;
Douglas Gregordd13e842009-03-30 22:58:21 +00001381 TemplateSpecializationType::Profile(ID, Template, Args, NumArgs);
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001382
Douglas Gregor8e458f42009-02-09 18:46:07 +00001383 void *InsertPos = 0;
Douglas Gregordd13e842009-03-30 22:58:21 +00001384 TemplateSpecializationType *Spec
1385 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor8e458f42009-02-09 18:46:07 +00001386
1387 if (Spec)
1388 return QualType(Spec, 0);
1389
Douglas Gregordd13e842009-03-30 22:58:21 +00001390 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregorf9ff4b12009-03-09 23:48:35 +00001391 sizeof(TemplateArgument) * NumArgs),
1392 8);
Douglas Gregordd13e842009-03-30 22:58:21 +00001393 Spec = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, Canon);
Douglas Gregor8e458f42009-02-09 18:46:07 +00001394 Types.push_back(Spec);
Douglas Gregordd13e842009-03-30 22:58:21 +00001395 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
Douglas Gregor8e458f42009-02-09 18:46:07 +00001396
1397 return QualType(Spec, 0);
1398}
1399
Douglas Gregor734b4ba2009-03-19 00:18:19 +00001400QualType
Douglas Gregor1e589cc2009-03-26 23:50:42 +00001401ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
Douglas Gregor734b4ba2009-03-19 00:18:19 +00001402 QualType NamedType) {
1403 llvm::FoldingSetNodeID ID;
Douglas Gregor1e589cc2009-03-26 23:50:42 +00001404 QualifiedNameType::Profile(ID, NNS, NamedType);
Douglas Gregor734b4ba2009-03-19 00:18:19 +00001405
1406 void *InsertPos = 0;
1407 QualifiedNameType *T
1408 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
1409 if (T)
1410 return QualType(T, 0);
1411
Douglas Gregor1e589cc2009-03-26 23:50:42 +00001412 T = new (*this) QualifiedNameType(NNS, NamedType,
1413 getCanonicalType(NamedType));
Douglas Gregor734b4ba2009-03-19 00:18:19 +00001414 Types.push_back(T);
1415 QualifiedNameTypes.InsertNode(T, InsertPos);
1416 return QualType(T, 0);
1417}
1418
Douglas Gregord3022602009-03-27 23:10:48 +00001419QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1420 const IdentifierInfo *Name,
1421 QualType Canon) {
1422 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1423
1424 if (Canon.isNull()) {
1425 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1426 if (CanonNNS != NNS)
1427 Canon = getTypenameType(CanonNNS, Name);
1428 }
1429
1430 llvm::FoldingSetNodeID ID;
1431 TypenameType::Profile(ID, NNS, Name);
1432
1433 void *InsertPos = 0;
1434 TypenameType *T
1435 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1436 if (T)
1437 return QualType(T, 0);
1438
1439 T = new (*this) TypenameType(NNS, Name, Canon);
1440 Types.push_back(T);
1441 TypenameTypes.InsertNode(T, InsertPos);
1442 return QualType(T, 0);
1443}
1444
Douglas Gregor77da5802009-04-01 00:28:59 +00001445QualType
1446ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1447 const TemplateSpecializationType *TemplateId,
1448 QualType Canon) {
1449 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1450
1451 if (Canon.isNull()) {
1452 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1453 QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
1454 if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
1455 const TemplateSpecializationType *CanonTemplateId
1456 = CanonType->getAsTemplateSpecializationType();
1457 assert(CanonTemplateId &&
1458 "Canonical type must also be a template specialization type");
1459 Canon = getTypenameType(CanonNNS, CanonTemplateId);
1460 }
1461 }
1462
1463 llvm::FoldingSetNodeID ID;
1464 TypenameType::Profile(ID, NNS, TemplateId);
1465
1466 void *InsertPos = 0;
1467 TypenameType *T
1468 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1469 if (T)
1470 return QualType(T, 0);
1471
1472 T = new (*this) TypenameType(NNS, TemplateId, Canon);
1473 Types.push_back(T);
1474 TypenameTypes.InsertNode(T, InsertPos);
1475 return QualType(T, 0);
1476}
1477
Chris Lattnere1352302008-04-07 04:56:42 +00001478/// CmpProtocolNames - Comparison predicate for sorting protocols
1479/// alphabetically.
1480static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
1481 const ObjCProtocolDecl *RHS) {
Douglas Gregor24afd4a2008-11-17 14:58:09 +00001482 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere1352302008-04-07 04:56:42 +00001483}
1484
1485static void SortAndUniqueProtocols(ObjCProtocolDecl **&Protocols,
1486 unsigned &NumProtocols) {
1487 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
1488
1489 // Sort protocols, keyed by name.
1490 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
1491
1492 // Remove duplicates.
1493 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
1494 NumProtocols = ProtocolsEnd-Protocols;
1495}
1496
1497
Chris Lattnerb0c6a1f2008-04-07 04:44:08 +00001498/// getObjCQualifiedInterfaceType - Return a ObjCQualifiedInterfaceType type for
1499/// the given interface decl and the conforming protocol list.
Ted Kremenek42730c52008-01-07 19:49:32 +00001500QualType ASTContext::getObjCQualifiedInterfaceType(ObjCInterfaceDecl *Decl,
1501 ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
Chris Lattnere1352302008-04-07 04:56:42 +00001502 // Sort the protocol list alphabetically to canonicalize it.
1503 SortAndUniqueProtocols(Protocols, NumProtocols);
1504
Fariborz Jahanian91193f62007-10-11 00:55:41 +00001505 llvm::FoldingSetNodeID ID;
Chris Lattner7cdcb252008-04-07 06:38:24 +00001506 ObjCQualifiedInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
Fariborz Jahanian91193f62007-10-11 00:55:41 +00001507
1508 void *InsertPos = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +00001509 if (ObjCQualifiedInterfaceType *QT =
1510 ObjCQualifiedInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahanian91193f62007-10-11 00:55:41 +00001511 return QualType(QT, 0);
1512
1513 // No Match;
Ted Kremenek42730c52008-01-07 19:49:32 +00001514 ObjCQualifiedInterfaceType *QType =
Steve Naroff93fd2112009-01-27 22:08:43 +00001515 new (*this,8) ObjCQualifiedInterfaceType(Decl, Protocols, NumProtocols);
Ted Kremenekc70e7d02009-01-19 21:31:22 +00001516
Fariborz Jahanian91193f62007-10-11 00:55:41 +00001517 Types.push_back(QType);
Ted Kremenek42730c52008-01-07 19:49:32 +00001518 ObjCQualifiedInterfaceTypes.InsertNode(QType, InsertPos);
Fariborz Jahanian91193f62007-10-11 00:55:41 +00001519 return QualType(QType, 0);
1520}
1521
Chris Lattnere1352302008-04-07 04:56:42 +00001522/// getObjCQualifiedIdType - Return an ObjCQualifiedIdType for the 'id' decl
1523/// and the conforming protocol list.
Chris Lattner4a68fe02008-07-26 00:46:50 +00001524QualType ASTContext::getObjCQualifiedIdType(ObjCProtocolDecl **Protocols,
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001525 unsigned NumProtocols) {
Chris Lattnere1352302008-04-07 04:56:42 +00001526 // Sort the protocol list alphabetically to canonicalize it.
1527 SortAndUniqueProtocols(Protocols, NumProtocols);
1528
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001529 llvm::FoldingSetNodeID ID;
Ted Kremenek42730c52008-01-07 19:49:32 +00001530 ObjCQualifiedIdType::Profile(ID, Protocols, NumProtocols);
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001531
1532 void *InsertPos = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +00001533 if (ObjCQualifiedIdType *QT =
Chris Lattner4a68fe02008-07-26 00:46:50 +00001534 ObjCQualifiedIdTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001535 return QualType(QT, 0);
1536
1537 // No Match;
Ted Kremenekc70e7d02009-01-19 21:31:22 +00001538 ObjCQualifiedIdType *QType =
Steve Naroff93fd2112009-01-27 22:08:43 +00001539 new (*this,8) ObjCQualifiedIdType(Protocols, NumProtocols);
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001540 Types.push_back(QType);
Ted Kremenek42730c52008-01-07 19:49:32 +00001541 ObjCQualifiedIdTypes.InsertNode(QType, InsertPos);
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001542 return QualType(QType, 0);
1543}
1544
Douglas Gregor4fa58902009-02-26 23:50:07 +00001545/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
1546/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff0604dd92007-08-01 18:02:17 +00001547/// multiple declarations that refer to "typeof(x)" all contain different
1548/// DeclRefExpr's. This doesn't effect the type checker, since it operates
1549/// on canonical type's (which are always unique).
Douglas Gregor4fa58902009-02-26 23:50:07 +00001550QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001551 QualType Canonical = getCanonicalType(tofExpr->getType());
Douglas Gregor4fa58902009-02-26 23:50:07 +00001552 TypeOfExprType *toe = new (*this,8) TypeOfExprType(tofExpr, Canonical);
Steve Naroff0604dd92007-08-01 18:02:17 +00001553 Types.push_back(toe);
1554 return QualType(toe, 0);
Steve Naroff7cbb1462007-07-31 12:34:36 +00001555}
1556
Steve Naroff0604dd92007-08-01 18:02:17 +00001557/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
1558/// TypeOfType AST's. The only motivation to unique these nodes would be
1559/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
1560/// an issue. This doesn't effect the type checker, since it operates
1561/// on canonical type's (which are always unique).
Steve Naroff7cbb1462007-07-31 12:34:36 +00001562QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001563 QualType Canonical = getCanonicalType(tofType);
Steve Naroff93fd2112009-01-27 22:08:43 +00001564 TypeOfType *tot = new (*this,8) TypeOfType(tofType, Canonical);
Steve Naroff0604dd92007-08-01 18:02:17 +00001565 Types.push_back(tot);
1566 return QualType(tot, 0);
Steve Naroff7cbb1462007-07-31 12:34:36 +00001567}
1568
Chris Lattner4b009652007-07-25 00:24:17 +00001569/// getTagDeclType - Return the unique reference to the type for the
1570/// specified TagDecl (struct/union/class/enum) decl.
1571QualType ASTContext::getTagDeclType(TagDecl *Decl) {
Ted Kremenekae8fa032007-11-26 21:16:01 +00001572 assert (Decl);
Douglas Gregor1d661552008-04-13 21:07:44 +00001573 return getTypeDeclType(Decl);
Chris Lattner4b009652007-07-25 00:24:17 +00001574}
1575
1576/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
1577/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
1578/// needs to agree with the definition in <stddef.h>.
1579QualType ASTContext::getSizeType() const {
Douglas Gregorc6507e42008-11-03 14:12:49 +00001580 return getFromTargetType(Target.getSizeType());
Chris Lattner4b009652007-07-25 00:24:17 +00001581}
1582
Argiris Kirtzidis1ed03e72008-08-09 16:51:54 +00001583/// getSignedWCharType - Return the type of "signed wchar_t".
1584/// Used when in C++, as a GCC extension.
1585QualType ASTContext::getSignedWCharType() const {
1586 // FIXME: derive from "Target" ?
1587 return WCharTy;
1588}
1589
1590/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
1591/// Used when in C++, as a GCC extension.
1592QualType ASTContext::getUnsignedWCharType() const {
1593 // FIXME: derive from "Target" ?
1594 return UnsignedIntTy;
1595}
1596
Chris Lattner4b009652007-07-25 00:24:17 +00001597/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
1598/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
1599QualType ASTContext::getPointerDiffType() const {
Douglas Gregorc6507e42008-11-03 14:12:49 +00001600 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner4b009652007-07-25 00:24:17 +00001601}
1602
Chris Lattner19eb97e2008-04-02 05:18:44 +00001603//===----------------------------------------------------------------------===//
1604// Type Operators
1605//===----------------------------------------------------------------------===//
1606
Chris Lattner3dae6f42008-04-06 22:41:35 +00001607/// getCanonicalType - Return the canonical (structural) type corresponding to
1608/// the specified potentially non-canonical type. The non-canonical version
1609/// of a type may have many "decorated" versions of types. Decorators can
1610/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
1611/// to be free of any of these, allowing two canonical types to be compared
1612/// for exact equality with a simple pointer comparison.
1613QualType ASTContext::getCanonicalType(QualType T) {
1614 QualType CanType = T.getTypePtr()->getCanonicalTypeInternal();
Chris Lattnera1923f62008-08-04 07:31:14 +00001615
1616 // If the result has type qualifiers, make sure to canonicalize them as well.
1617 unsigned TypeQuals = T.getCVRQualifiers() | CanType.getCVRQualifiers();
1618 if (TypeQuals == 0) return CanType;
1619
1620 // If the type qualifiers are on an array type, get the canonical type of the
1621 // array with the qualifiers applied to the element type.
1622 ArrayType *AT = dyn_cast<ArrayType>(CanType);
1623 if (!AT)
1624 return CanType.getQualifiedType(TypeQuals);
1625
1626 // Get the canonical version of the element with the extra qualifiers on it.
1627 // This can recursively sink qualifiers through multiple levels of arrays.
1628 QualType NewEltTy=AT->getElementType().getWithAdditionalQualifiers(TypeQuals);
1629 NewEltTy = getCanonicalType(NewEltTy);
1630
1631 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
1632 return getConstantArrayType(NewEltTy, CAT->getSize(),CAT->getSizeModifier(),
1633 CAT->getIndexTypeQualifier());
1634 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
1635 return getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
1636 IAT->getIndexTypeQualifier());
1637
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001638 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
1639 return getDependentSizedArrayType(NewEltTy, DSAT->getSizeExpr(),
1640 DSAT->getSizeModifier(),
1641 DSAT->getIndexTypeQualifier());
1642
Chris Lattnera1923f62008-08-04 07:31:14 +00001643 VariableArrayType *VAT = cast<VariableArrayType>(AT);
1644 return getVariableArrayType(NewEltTy, VAT->getSizeExpr(),
1645 VAT->getSizeModifier(),
1646 VAT->getIndexTypeQualifier());
1647}
1648
Douglas Gregord3022602009-03-27 23:10:48 +00001649NestedNameSpecifier *
1650ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
1651 if (!NNS)
1652 return 0;
1653
1654 switch (NNS->getKind()) {
1655 case NestedNameSpecifier::Identifier:
1656 // Canonicalize the prefix but keep the identifier the same.
1657 return NestedNameSpecifier::Create(*this,
1658 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
1659 NNS->getAsIdentifier());
1660
1661 case NestedNameSpecifier::Namespace:
1662 // A namespace is canonical; build a nested-name-specifier with
1663 // this namespace and no prefix.
1664 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
1665
1666 case NestedNameSpecifier::TypeSpec:
1667 case NestedNameSpecifier::TypeSpecWithTemplate: {
1668 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
1669 NestedNameSpecifier *Prefix = 0;
1670
1671 // FIXME: This isn't the right check!
1672 if (T->isDependentType())
1673 Prefix = getCanonicalNestedNameSpecifier(NNS->getPrefix());
1674
1675 return NestedNameSpecifier::Create(*this, Prefix,
1676 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
1677 T.getTypePtr());
1678 }
1679
1680 case NestedNameSpecifier::Global:
1681 // The global specifier is canonical and unique.
1682 return NNS;
1683 }
1684
1685 // Required to silence a GCC warning
1686 return 0;
1687}
1688
Chris Lattnera1923f62008-08-04 07:31:14 +00001689
1690const ArrayType *ASTContext::getAsArrayType(QualType T) {
1691 // Handle the non-qualified case efficiently.
1692 if (T.getCVRQualifiers() == 0) {
1693 // Handle the common positive case fast.
1694 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
1695 return AT;
1696 }
1697
1698 // Handle the common negative case fast, ignoring CVR qualifiers.
1699 QualType CType = T->getCanonicalTypeInternal();
1700
Fariborz Jahanianb60352a2009-02-17 18:27:45 +00001701 // Make sure to look through type qualifiers (like ExtQuals) for the negative
Chris Lattnera1923f62008-08-04 07:31:14 +00001702 // test.
1703 if (!isa<ArrayType>(CType) &&
1704 !isa<ArrayType>(CType.getUnqualifiedType()))
1705 return 0;
1706
1707 // Apply any CVR qualifiers from the array type to the element type. This
1708 // implements C99 6.7.3p8: "If the specification of an array type includes
1709 // any type qualifiers, the element type is so qualified, not the array type."
1710
1711 // If we get here, we either have type qualifiers on the type, or we have
1712 // sugar such as a typedef in the way. If we have type qualifiers on the type
1713 // we must propagate them down into the elemeng type.
1714 unsigned CVRQuals = T.getCVRQualifiers();
1715 unsigned AddrSpace = 0;
1716 Type *Ty = T.getTypePtr();
1717
Fariborz Jahanianb60352a2009-02-17 18:27:45 +00001718 // Rip through ExtQualType's and typedefs to get to a concrete type.
Chris Lattnera1923f62008-08-04 07:31:14 +00001719 while (1) {
Fariborz Jahanianb60352a2009-02-17 18:27:45 +00001720 if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(Ty)) {
1721 AddrSpace = EXTQT->getAddressSpace();
1722 Ty = EXTQT->getBaseType();
Chris Lattnera1923f62008-08-04 07:31:14 +00001723 } else {
1724 T = Ty->getDesugaredType();
1725 if (T.getTypePtr() == Ty && T.getCVRQualifiers() == 0)
1726 break;
1727 CVRQuals |= T.getCVRQualifiers();
1728 Ty = T.getTypePtr();
1729 }
1730 }
1731
1732 // If we have a simple case, just return now.
1733 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
1734 if (ATy == 0 || (AddrSpace == 0 && CVRQuals == 0))
1735 return ATy;
1736
1737 // Otherwise, we have an array and we have qualifiers on it. Push the
1738 // qualifiers into the array element type and return a new array type.
1739 // Get the canonical version of the element with the extra qualifiers on it.
1740 // This can recursively sink qualifiers through multiple levels of arrays.
1741 QualType NewEltTy = ATy->getElementType();
1742 if (AddrSpace)
Fariborz Jahanianb60352a2009-02-17 18:27:45 +00001743 NewEltTy = getAddrSpaceQualType(NewEltTy, AddrSpace);
Chris Lattnera1923f62008-08-04 07:31:14 +00001744 NewEltTy = NewEltTy.getWithAdditionalQualifiers(CVRQuals);
1745
1746 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
1747 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
1748 CAT->getSizeModifier(),
1749 CAT->getIndexTypeQualifier()));
1750 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
1751 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
1752 IAT->getSizeModifier(),
1753 IAT->getIndexTypeQualifier()));
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001754
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001755 if (const DependentSizedArrayType *DSAT
1756 = dyn_cast<DependentSizedArrayType>(ATy))
1757 return cast<ArrayType>(
1758 getDependentSizedArrayType(NewEltTy,
1759 DSAT->getSizeExpr(),
1760 DSAT->getSizeModifier(),
1761 DSAT->getIndexTypeQualifier()));
Chris Lattnera1923f62008-08-04 07:31:14 +00001762
Chris Lattnera1923f62008-08-04 07:31:14 +00001763 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
1764 return cast<ArrayType>(getVariableArrayType(NewEltTy, VAT->getSizeExpr(),
1765 VAT->getSizeModifier(),
1766 VAT->getIndexTypeQualifier()));
Chris Lattner3dae6f42008-04-06 22:41:35 +00001767}
1768
1769
Chris Lattner19eb97e2008-04-02 05:18:44 +00001770/// getArrayDecayedType - Return the properly qualified result of decaying the
1771/// specified array type to a pointer. This operation is non-trivial when
1772/// handling typedefs etc. The canonical type of "T" must be an array type,
1773/// this returns a pointer to a properly qualified element of the array.
1774///
1775/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
1776QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001777 // Get the element type with 'getAsArrayType' so that we don't lose any
1778 // typedefs in the element type of the array. This also handles propagation
1779 // of type qualifiers from the array type into the element type if present
1780 // (C99 6.7.3p8).
1781 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
1782 assert(PrettyArrayType && "Not an array type!");
Chris Lattner19eb97e2008-04-02 05:18:44 +00001783
Chris Lattnera1923f62008-08-04 07:31:14 +00001784 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattner19eb97e2008-04-02 05:18:44 +00001785
1786 // int x[restrict 4] -> int *restrict
Chris Lattnera1923f62008-08-04 07:31:14 +00001787 return PtrTy.getQualifiedType(PrettyArrayType->getIndexTypeQualifier());
Chris Lattner19eb97e2008-04-02 05:18:44 +00001788}
1789
Daniel Dunbar4a0b75c2009-01-05 22:14:37 +00001790QualType ASTContext::getBaseElementType(const VariableArrayType *VAT) {
Anders Carlsson76d19c82008-12-21 03:44:36 +00001791 QualType ElemTy = VAT->getElementType();
1792
1793 if (const VariableArrayType *VAT = getAsVariableArrayType(ElemTy))
1794 return getBaseElementType(VAT);
1795
1796 return ElemTy;
1797}
1798
Chris Lattner4b009652007-07-25 00:24:17 +00001799/// getFloatingRank - Return a relative rank for floating point types.
1800/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerd7135b42008-04-06 23:38:49 +00001801static FloatingRank getFloatingRank(QualType T) {
Christopher Lamb2a72bb32008-02-04 02:31:56 +00001802 if (const ComplexType *CT = T->getAsComplexType())
Chris Lattner4b009652007-07-25 00:24:17 +00001803 return getFloatingRank(CT->getElementType());
Chris Lattnerd7135b42008-04-06 23:38:49 +00001804
Daniel Dunbar4a0b75c2009-01-05 22:14:37 +00001805 assert(T->getAsBuiltinType() && "getFloatingRank(): not a floating type");
Christopher Lamb2a72bb32008-02-04 02:31:56 +00001806 switch (T->getAsBuiltinType()->getKind()) {
Chris Lattnerd7135b42008-04-06 23:38:49 +00001807 default: assert(0 && "getFloatingRank(): not a floating type");
Chris Lattner4b009652007-07-25 00:24:17 +00001808 case BuiltinType::Float: return FloatRank;
1809 case BuiltinType::Double: return DoubleRank;
1810 case BuiltinType::LongDouble: return LongDoubleRank;
1811 }
1812}
1813
Steve Narofffa0c4532007-08-27 01:41:48 +00001814/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
1815/// point or a complex type (based on typeDomain/typeSize).
1816/// 'typeDomain' is a real floating point or complex type.
1817/// 'typeSize' is a real floating point or complex type.
Chris Lattner7794ae22008-04-06 23:58:54 +00001818QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
1819 QualType Domain) const {
1820 FloatingRank EltRank = getFloatingRank(Size);
1821 if (Domain->isComplexType()) {
1822 switch (EltRank) {
Steve Narofffa0c4532007-08-27 01:41:48 +00001823 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Naroff3cf497f2007-08-27 01:27:54 +00001824 case FloatRank: return FloatComplexTy;
1825 case DoubleRank: return DoubleComplexTy;
1826 case LongDoubleRank: return LongDoubleComplexTy;
1827 }
Chris Lattner4b009652007-07-25 00:24:17 +00001828 }
Chris Lattner7794ae22008-04-06 23:58:54 +00001829
1830 assert(Domain->isRealFloatingType() && "Unknown domain!");
1831 switch (EltRank) {
1832 default: assert(0 && "getFloatingRank(): illegal value for rank");
1833 case FloatRank: return FloatTy;
1834 case DoubleRank: return DoubleTy;
1835 case LongDoubleRank: return LongDoubleTy;
Steve Naroff3cf497f2007-08-27 01:27:54 +00001836 }
Chris Lattner4b009652007-07-25 00:24:17 +00001837}
1838
Chris Lattner51285d82008-04-06 23:55:33 +00001839/// getFloatingTypeOrder - Compare the rank of the two specified floating
1840/// point types, ignoring the domain of the type (i.e. 'double' ==
1841/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
1842/// LHS < RHS, return -1.
Chris Lattnerd7135b42008-04-06 23:38:49 +00001843int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
1844 FloatingRank LHSR = getFloatingRank(LHS);
1845 FloatingRank RHSR = getFloatingRank(RHS);
1846
1847 if (LHSR == RHSR)
Steve Naroff45fc9822007-08-27 15:30:22 +00001848 return 0;
Chris Lattnerd7135b42008-04-06 23:38:49 +00001849 if (LHSR > RHSR)
Steve Naroff45fc9822007-08-27 15:30:22 +00001850 return 1;
1851 return -1;
Chris Lattner4b009652007-07-25 00:24:17 +00001852}
1853
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001854/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
1855/// routine will assert if passed a built-in type that isn't an integer or enum,
1856/// or if it is not canonicalized.
Eli Friedmanff3fcdf2009-02-13 02:31:07 +00001857unsigned ASTContext::getIntegerRank(Type *T) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001858 assert(T->isCanonical() && "T should be canonicalized");
Eli Friedmanff3fcdf2009-02-13 02:31:07 +00001859 if (EnumType* ET = dyn_cast<EnumType>(T))
1860 T = ET->getDecl()->getIntegerType().getTypePtr();
1861
1862 // There are two things which impact the integer rank: the width, and
1863 // the ordering of builtins. The builtin ordering is encoded in the
1864 // bottom three bits; the width is encoded in the bits above that.
1865 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T)) {
1866 return FWIT->getWidth() << 3;
1867 }
1868
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001869 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner51285d82008-04-06 23:55:33 +00001870 default: assert(0 && "getIntegerRank(): not a built-in integer");
1871 case BuiltinType::Bool:
Eli Friedmanff3fcdf2009-02-13 02:31:07 +00001872 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner51285d82008-04-06 23:55:33 +00001873 case BuiltinType::Char_S:
1874 case BuiltinType::Char_U:
1875 case BuiltinType::SChar:
1876 case BuiltinType::UChar:
Eli Friedmanff3fcdf2009-02-13 02:31:07 +00001877 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner51285d82008-04-06 23:55:33 +00001878 case BuiltinType::Short:
1879 case BuiltinType::UShort:
Eli Friedmanff3fcdf2009-02-13 02:31:07 +00001880 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner51285d82008-04-06 23:55:33 +00001881 case BuiltinType::Int:
1882 case BuiltinType::UInt:
Eli Friedmanff3fcdf2009-02-13 02:31:07 +00001883 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner51285d82008-04-06 23:55:33 +00001884 case BuiltinType::Long:
1885 case BuiltinType::ULong:
Eli Friedmanff3fcdf2009-02-13 02:31:07 +00001886 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner51285d82008-04-06 23:55:33 +00001887 case BuiltinType::LongLong:
1888 case BuiltinType::ULongLong:
Eli Friedmanff3fcdf2009-02-13 02:31:07 +00001889 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001890 }
1891}
1892
Chris Lattner51285d82008-04-06 23:55:33 +00001893/// getIntegerTypeOrder - Returns the highest ranked integer type:
1894/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
1895/// LHS < RHS, return -1.
1896int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001897 Type *LHSC = getCanonicalType(LHS).getTypePtr();
1898 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner51285d82008-04-06 23:55:33 +00001899 if (LHSC == RHSC) return 0;
Chris Lattner4b009652007-07-25 00:24:17 +00001900
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001901 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
1902 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Chris Lattner4b009652007-07-25 00:24:17 +00001903
Chris Lattner51285d82008-04-06 23:55:33 +00001904 unsigned LHSRank = getIntegerRank(LHSC);
1905 unsigned RHSRank = getIntegerRank(RHSC);
Chris Lattner4b009652007-07-25 00:24:17 +00001906
Chris Lattner51285d82008-04-06 23:55:33 +00001907 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
1908 if (LHSRank == RHSRank) return 0;
1909 return LHSRank > RHSRank ? 1 : -1;
1910 }
Chris Lattner4b009652007-07-25 00:24:17 +00001911
Chris Lattner51285d82008-04-06 23:55:33 +00001912 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
1913 if (LHSUnsigned) {
1914 // If the unsigned [LHS] type is larger, return it.
1915 if (LHSRank >= RHSRank)
1916 return 1;
1917
1918 // If the signed type can represent all values of the unsigned type, it
1919 // wins. Because we are dealing with 2's complement and types that are
1920 // powers of two larger than each other, this is always safe.
1921 return -1;
1922 }
Chris Lattnerc1b68db2008-04-06 22:59:24 +00001923
Chris Lattner51285d82008-04-06 23:55:33 +00001924 // If the unsigned [RHS] type is larger, return it.
1925 if (RHSRank >= LHSRank)
1926 return -1;
1927
1928 // If the signed type can represent all values of the unsigned type, it
1929 // wins. Because we are dealing with 2's complement and types that are
1930 // powers of two larger than each other, this is always safe.
1931 return 1;
Chris Lattner4b009652007-07-25 00:24:17 +00001932}
Anders Carlssone7e7aa22007-08-17 05:31:46 +00001933
1934// getCFConstantStringType - Return the type used for constant CFStrings.
1935QualType ASTContext::getCFConstantStringType() {
1936 if (!CFConstantStringTypeDecl) {
Chris Lattnere4650482008-03-15 06:12:44 +00001937 CFConstantStringTypeDecl =
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001938 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
Ted Kremenek2c984042008-09-05 01:34:33 +00001939 &Idents.get("NSConstantString"));
Anders Carlssonbb2cf512007-11-19 00:25:30 +00001940 QualType FieldTypes[4];
Anders Carlssone7e7aa22007-08-17 05:31:46 +00001941
1942 // const int *isa;
1943 FieldTypes[0] = getPointerType(IntTy.getQualifiedType(QualType::Const));
Anders Carlssonbb2cf512007-11-19 00:25:30 +00001944 // int flags;
1945 FieldTypes[1] = IntTy;
Anders Carlssone7e7aa22007-08-17 05:31:46 +00001946 // const char *str;
Anders Carlssonbb2cf512007-11-19 00:25:30 +00001947 FieldTypes[2] = getPointerType(CharTy.getQualifiedType(QualType::Const));
Anders Carlssone7e7aa22007-08-17 05:31:46 +00001948 // long length;
Anders Carlssonbb2cf512007-11-19 00:25:30 +00001949 FieldTypes[3] = LongTy;
Douglas Gregor8acb7272008-12-11 16:49:14 +00001950
Anders Carlssone7e7aa22007-08-17 05:31:46 +00001951 // Create fields
Douglas Gregor8acb7272008-12-11 16:49:14 +00001952 for (unsigned i = 0; i < 4; ++i) {
1953 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
1954 SourceLocation(), 0,
1955 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001956 /*Mutable=*/false);
Douglas Gregor03b2ad22009-01-12 23:27:07 +00001957 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor8acb7272008-12-11 16:49:14 +00001958 }
1959
1960 CFConstantStringTypeDecl->completeDefinition(*this);
Anders Carlssone7e7aa22007-08-17 05:31:46 +00001961 }
1962
1963 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif61ce98c2007-09-11 15:32:40 +00001964}
Anders Carlssonfb5b1e82007-10-11 01:00:40 +00001965
Anders Carlssonf58cac72008-08-30 19:34:46 +00001966QualType ASTContext::getObjCFastEnumerationStateType()
1967{
1968 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor8acb7272008-12-11 16:49:14 +00001969 ObjCFastEnumerationStateTypeDecl =
1970 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
1971 &Idents.get("__objcFastEnumerationState"));
1972
Anders Carlssonf58cac72008-08-30 19:34:46 +00001973 QualType FieldTypes[] = {
1974 UnsignedLongTy,
1975 getPointerType(ObjCIdType),
1976 getPointerType(UnsignedLongTy),
1977 getConstantArrayType(UnsignedLongTy,
1978 llvm::APInt(32, 5), ArrayType::Normal, 0)
1979 };
1980
Douglas Gregor8acb7272008-12-11 16:49:14 +00001981 for (size_t i = 0; i < 4; ++i) {
1982 FieldDecl *Field = FieldDecl::Create(*this,
1983 ObjCFastEnumerationStateTypeDecl,
1984 SourceLocation(), 0,
1985 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001986 /*Mutable=*/false);
Douglas Gregor03b2ad22009-01-12 23:27:07 +00001987 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor8acb7272008-12-11 16:49:14 +00001988 }
Anders Carlssonf58cac72008-08-30 19:34:46 +00001989
Douglas Gregor8acb7272008-12-11 16:49:14 +00001990 ObjCFastEnumerationStateTypeDecl->completeDefinition(*this);
Anders Carlssonf58cac72008-08-30 19:34:46 +00001991 }
1992
1993 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
1994}
1995
Anders Carlssone3f02572007-10-29 06:33:42 +00001996// This returns true if a type has been typedefed to BOOL:
1997// typedef <type> BOOL;
Chris Lattnercb034cb2007-10-30 20:27:44 +00001998static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone3f02572007-10-29 06:33:42 +00001999 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner85fb3842008-11-24 03:52:59 +00002000 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
2001 return II->isStr("BOOL");
Anders Carlsson36f07d82007-10-29 05:01:08 +00002002
2003 return false;
2004}
2005
Ted Kremenek42730c52008-01-07 19:49:32 +00002006/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002007/// purpose.
Ted Kremenek42730c52008-01-07 19:49:32 +00002008int ASTContext::getObjCEncodingTypeSize(QualType type) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002009 uint64_t sz = getTypeSize(type);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002010
2011 // Make all integer and enum types at least as large as an int
2012 if (sz > 0 && type->isIntegralType())
Chris Lattner8cd0e932008-03-05 18:54:05 +00002013 sz = std::max(sz, getTypeSize(IntTy));
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002014 // Treat arrays as pointers, since that's how they're passed in.
2015 else if (type->isArrayType())
Chris Lattner8cd0e932008-03-05 18:54:05 +00002016 sz = getTypeSize(VoidPtrTy);
2017 return sz / getTypeSize(CharTy);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002018}
2019
Ted Kremenek42730c52008-01-07 19:49:32 +00002020/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002021/// declaration.
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002022void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnerae430292008-11-19 07:24:05 +00002023 std::string& S) {
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002024 // FIXME: This is not very efficient.
Fariborz Jahanian65e7eb52007-11-01 17:18:37 +00002025 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremenek42730c52008-01-07 19:49:32 +00002026 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002027 // Encode result type.
Daniel Dunbarc9197cd2008-10-17 20:21:44 +00002028 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002029 // Compute size of all parameters.
2030 // Start with computing size of a pointer in number of bytes.
2031 // FIXME: There might(should) be a better way of doing this computation!
2032 SourceLocation Loc;
Chris Lattner8cd0e932008-03-05 18:54:05 +00002033 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002034 // The first two arguments (self and _cmd) are pointers; account for
2035 // their size.
2036 int ParmOffset = 2 * PtrSize;
Chris Lattner5c6b2c62009-02-20 18:43:26 +00002037 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2038 E = Decl->param_end(); PI != E; ++PI) {
2039 QualType PType = (*PI)->getType();
2040 int sz = getObjCEncodingTypeSize(PType);
Ted Kremenek42730c52008-01-07 19:49:32 +00002041 assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002042 ParmOffset += sz;
2043 }
2044 S += llvm::utostr(ParmOffset);
2045 S += "@0:";
2046 S += llvm::utostr(PtrSize);
2047
2048 // Argument types.
2049 ParmOffset = 2 * PtrSize;
Chris Lattner5c6b2c62009-02-20 18:43:26 +00002050 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2051 E = Decl->param_end(); PI != E; ++PI) {
2052 ParmVarDecl *PVDecl = *PI;
Fariborz Jahaniane26cb432008-12-20 23:29:59 +00002053 QualType PType = PVDecl->getOriginalType();
2054 if (const ArrayType *AT =
2055 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal()))
2056 // Use array's original type only if it has known number of
2057 // elements.
2058 if (!dyn_cast<ConstantArrayType>(AT))
2059 PType = PVDecl->getType();
Fariborz Jahanian65e7eb52007-11-01 17:18:37 +00002060 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002061 // 'in', 'inout', etc.
Fariborz Jahaniane26cb432008-12-20 23:29:59 +00002062 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbarc9197cd2008-10-17 20:21:44 +00002063 getObjCEncodingForType(PType, S);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002064 S += llvm::utostr(ParmOffset);
Ted Kremenek42730c52008-01-07 19:49:32 +00002065 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002066 }
2067}
2068
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002069/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian501ef5c2009-01-20 20:04:12 +00002070/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002071/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
2072/// NULL when getting encodings for protocol properties.
Fariborz Jahanian501ef5c2009-01-20 20:04:12 +00002073/// Property attributes are stored as a comma-delimited C string. The simple
2074/// attributes readonly and bycopy are encoded as single characters. The
2075/// parametrized attributes, getter=name, setter=name, and ivar=name, are
2076/// encoded as single characters, followed by an identifier. Property types
2077/// are also encoded as a parametrized attribute. The characters used to encode
2078/// these attributes are defined by the following enumeration:
2079/// @code
2080/// enum PropertyAttributes {
2081/// kPropertyReadOnly = 'R', // property is read-only.
2082/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
2083/// kPropertyByref = '&', // property is a reference to the value last assigned
2084/// kPropertyDynamic = 'D', // property is dynamic
2085/// kPropertyGetter = 'G', // followed by getter selector name
2086/// kPropertySetter = 'S', // followed by setter selector name
2087/// kPropertyInstanceVariable = 'V' // followed by instance variable name
2088/// kPropertyType = 't' // followed by old-style type encoding.
2089/// kPropertyWeak = 'W' // 'weak' property
2090/// kPropertyStrong = 'P' // property GC'able
2091/// kPropertyNonAtomic = 'N' // property non-atomic
2092/// };
2093/// @endcode
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002094void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
2095 const Decl *Container,
Chris Lattnerae430292008-11-19 07:24:05 +00002096 std::string& S) {
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002097 // Collect information from the property implementation decl(s).
2098 bool Dynamic = false;
2099 ObjCPropertyImplDecl *SynthesizePID = 0;
2100
2101 // FIXME: Duplicated code due to poor abstraction.
2102 if (Container) {
2103 if (const ObjCCategoryImplDecl *CID =
2104 dyn_cast<ObjCCategoryImplDecl>(Container)) {
2105 for (ObjCCategoryImplDecl::propimpl_iterator
2106 i = CID->propimpl_begin(), e = CID->propimpl_end(); i != e; ++i) {
2107 ObjCPropertyImplDecl *PID = *i;
2108 if (PID->getPropertyDecl() == PD) {
2109 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2110 Dynamic = true;
2111 } else {
2112 SynthesizePID = PID;
2113 }
2114 }
2115 }
2116 } else {
Chris Lattner2fda0ed2008-10-05 17:34:18 +00002117 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002118 for (ObjCCategoryImplDecl::propimpl_iterator
2119 i = OID->propimpl_begin(), e = OID->propimpl_end(); i != e; ++i) {
2120 ObjCPropertyImplDecl *PID = *i;
2121 if (PID->getPropertyDecl() == PD) {
2122 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2123 Dynamic = true;
2124 } else {
2125 SynthesizePID = PID;
2126 }
2127 }
2128 }
2129 }
2130 }
2131
2132 // FIXME: This is not very efficient.
2133 S = "T";
2134
2135 // Encode result type.
Fariborz Jahanian892d5db2009-01-20 19:14:18 +00002136 // GCC has some special rules regarding encoding of properties which
2137 // closely resembles encoding of ivars.
2138 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, NULL,
2139 true /* outermost type */,
2140 true /* encoding for property */);
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002141
2142 if (PD->isReadOnly()) {
2143 S += ",R";
2144 } else {
2145 switch (PD->getSetterKind()) {
2146 case ObjCPropertyDecl::Assign: break;
2147 case ObjCPropertyDecl::Copy: S += ",C"; break;
2148 case ObjCPropertyDecl::Retain: S += ",&"; break;
2149 }
2150 }
2151
2152 // It really isn't clear at all what this means, since properties
2153 // are "dynamic by default".
2154 if (Dynamic)
2155 S += ",D";
2156
Fariborz Jahanian892d5db2009-01-20 19:14:18 +00002157 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
2158 S += ",N";
2159
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002160 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
2161 S += ",G";
Chris Lattner3a8f2942008-11-24 03:33:13 +00002162 S += PD->getGetterName().getAsString();
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002163 }
2164
2165 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
2166 S += ",S";
Chris Lattner3a8f2942008-11-24 03:33:13 +00002167 S += PD->getSetterName().getAsString();
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002168 }
2169
2170 if (SynthesizePID) {
2171 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
2172 S += ",V";
Chris Lattner6c5ec622008-11-24 04:00:27 +00002173 S += OID->getNameAsString();
Daniel Dunbar698d6f32008-08-28 04:38:10 +00002174 }
2175
2176 // FIXME: OBJCGC: weak & strong
2177}
2178
Fariborz Jahaniane07d9ec2008-12-23 19:56:47 +00002179/// getLegacyIntegralTypeEncoding -
2180/// Another legacy compatibility encoding: 32-bit longs are encoded as
Fariborz Jahanian89155952009-02-11 23:59:18 +00002181/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniane07d9ec2008-12-23 19:56:47 +00002182/// 'i' or 'I' instead if encoding a struct field, or a pointer!
2183///
2184void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
2185 if (dyn_cast<TypedefType>(PointeeTy.getTypePtr())) {
2186 if (const BuiltinType *BT = PointeeTy->getAsBuiltinType()) {
Fariborz Jahanian89155952009-02-11 23:59:18 +00002187 if (BT->getKind() == BuiltinType::ULong &&
2188 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniane07d9ec2008-12-23 19:56:47 +00002189 PointeeTy = UnsignedIntTy;
Fariborz Jahanian89155952009-02-11 23:59:18 +00002190 else
2191 if (BT->getKind() == BuiltinType::Long &&
2192 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniane07d9ec2008-12-23 19:56:47 +00002193 PointeeTy = IntTy;
2194 }
2195 }
2196}
2197
Fariborz Jahanian248db262008-01-22 22:44:46 +00002198void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Fariborz Jahanian0cd547f2008-12-19 23:34:38 +00002199 FieldDecl *Field) const {
Daniel Dunbarf8cfe562008-10-17 07:30:50 +00002200 // We follow the behavior of gcc, expanding structures which are
2201 // directly pointed to, and expanding embedded structures. Note that
2202 // these rules are sufficient to prevent recursive encoding of the
2203 // same type.
Fariborz Jahanian89ed86b2008-12-22 23:22:27 +00002204 getObjCEncodingForTypeImpl(T, S, true, true, Field,
2205 true /* outermost type */);
Daniel Dunbarf8cfe562008-10-17 07:30:50 +00002206}
2207
Fariborz Jahaniand1361952009-01-13 01:18:13 +00002208static void EncodeBitField(const ASTContext *Context, std::string& S,
2209 FieldDecl *FD) {
2210 const Expr *E = FD->getBitWidth();
2211 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
2212 ASTContext *Ctx = const_cast<ASTContext*>(Context);
2213 unsigned N = E->getIntegerConstantExprValue(*Ctx).getZExtValue();
2214 S += 'b';
2215 S += llvm::utostr(N);
2216}
2217
Daniel Dunbarf8cfe562008-10-17 07:30:50 +00002218void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
2219 bool ExpandPointedToStructures,
2220 bool ExpandStructures,
Fariborz Jahanian89ed86b2008-12-22 23:22:27 +00002221 FieldDecl *FD,
Fariborz Jahanian892d5db2009-01-20 19:14:18 +00002222 bool OutermostType,
2223 bool EncodingProperty) const {
Anders Carlssone3f02572007-10-29 06:33:42 +00002224 if (const BuiltinType *BT = T->getAsBuiltinType()) {
Fariborz Jahanian0cd547f2008-12-19 23:34:38 +00002225 if (FD && FD->isBitField()) {
Fariborz Jahaniand1361952009-01-13 01:18:13 +00002226 EncodeBitField(this, S, FD);
Anders Carlsson36f07d82007-10-29 05:01:08 +00002227 }
Fariborz Jahanian0cd547f2008-12-19 23:34:38 +00002228 else {
2229 char encoding;
2230 switch (BT->getKind()) {
2231 default: assert(0 && "Unhandled builtin type kind");
2232 case BuiltinType::Void: encoding = 'v'; break;
2233 case BuiltinType::Bool: encoding = 'B'; break;
2234 case BuiltinType::Char_U:
2235 case BuiltinType::UChar: encoding = 'C'; break;
2236 case BuiltinType::UShort: encoding = 'S'; break;
2237 case BuiltinType::UInt: encoding = 'I'; break;
Fariborz Jahanianebd95752009-02-11 22:31:45 +00002238 case BuiltinType::ULong:
2239 encoding =
2240 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
2241 break;
Fariborz Jahanian0cd547f2008-12-19 23:34:38 +00002242 case BuiltinType::ULongLong: encoding = 'Q'; break;
2243 case BuiltinType::Char_S:
2244 case BuiltinType::SChar: encoding = 'c'; break;
2245 case BuiltinType::Short: encoding = 's'; break;
2246 case BuiltinType::Int: encoding = 'i'; break;
Fariborz Jahanianebd95752009-02-11 22:31:45 +00002247 case BuiltinType::Long:
2248 encoding =
2249 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
2250 break;
Fariborz Jahanian0cd547f2008-12-19 23:34:38 +00002251 case BuiltinType::LongLong: encoding = 'q'; break;
2252 case BuiltinType::Float: encoding = 'f'; break;
2253 case BuiltinType::Double: encoding = 'd'; break;
2254 case BuiltinType::LongDouble: encoding = 'd'; break;
2255 }
Anders Carlsson36f07d82007-10-29 05:01:08 +00002256
Fariborz Jahanian0cd547f2008-12-19 23:34:38 +00002257 S += encoding;
2258 }
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00002259 }
Ted Kremenek42730c52008-01-07 19:49:32 +00002260 else if (T->isObjCQualifiedIdType()) {
Fariborz Jahanian892d5db2009-01-20 19:14:18 +00002261 getObjCEncodingForTypeImpl(getObjCIdType(), S,
2262 ExpandPointedToStructures,
2263 ExpandStructures, FD);
2264 if (FD || EncodingProperty) {
2265 // Note that we do extended encoding of protocol qualifer list
2266 // Only when doing ivar or property encoding.
2267 const ObjCQualifiedIdType *QIDT = T->getAsObjCQualifiedIdType();
2268 S += '"';
2269 for (unsigned i =0; i < QIDT->getNumProtocols(); i++) {
2270 ObjCProtocolDecl *Proto = QIDT->getProtocols(i);
2271 S += '<';
2272 S += Proto->getNameAsString();
2273 S += '>';
2274 }
2275 S += '"';
2276 }
2277 return;
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00002278 }
2279 else if (const PointerType *PT = T->getAsPointerType()) {
Anders Carlsson36f07d82007-10-29 05:01:08 +00002280 QualType PointeeTy = PT->getPointeeType();
Fariborz Jahaniane07d9ec2008-12-23 19:56:47 +00002281 bool isReadOnly = false;
2282 // For historical/compatibility reasons, the read-only qualifier of the
2283 // pointee gets emitted _before_ the '^'. The read-only qualifier of
2284 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
2285 // Also, do not emit the 'r' for anything but the outermost type!
2286 if (dyn_cast<TypedefType>(T.getTypePtr())) {
2287 if (OutermostType && T.isConstQualified()) {
2288 isReadOnly = true;
2289 S += 'r';
2290 }
2291 }
2292 else if (OutermostType) {
2293 QualType P = PointeeTy;
2294 while (P->getAsPointerType())
2295 P = P->getAsPointerType()->getPointeeType();
2296 if (P.isConstQualified()) {
2297 isReadOnly = true;
2298 S += 'r';
2299 }
2300 }
2301 if (isReadOnly) {
2302 // Another legacy compatibility encoding. Some ObjC qualifier and type
2303 // combinations need to be rearranged.
2304 // Rewrite "in const" from "nr" to "rn"
2305 const char * s = S.c_str();
2306 int len = S.length();
2307 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
2308 std::string replace = "rn";
2309 S.replace(S.end()-2, S.end(), replace);
2310 }
2311 }
Steve Naroff17c03822009-02-12 17:52:19 +00002312 if (isObjCIdStructType(PointeeTy)) {
Fariborz Jahanian80faffa2007-10-30 17:06:23 +00002313 S += '@';
2314 return;
Fariborz Jahanianc8679472008-12-19 00:14:49 +00002315 }
2316 else if (PointeeTy->isObjCInterfaceType()) {
Fariborz Jahanian94675042009-02-16 21:41:04 +00002317 if (!EncodingProperty &&
Fariborz Jahanian6bc0f2d2009-02-16 22:09:26 +00002318 isa<TypedefType>(PointeeTy.getTypePtr())) {
Fariborz Jahaniand3498aa2008-12-23 21:30:15 +00002319 // Another historical/compatibility reason.
2320 // We encode the underlying type which comes out as
2321 // {...};
2322 S += '^';
2323 getObjCEncodingForTypeImpl(PointeeTy, S,
2324 false, ExpandPointedToStructures,
2325 NULL);
2326 return;
2327 }
Fariborz Jahanianc8679472008-12-19 00:14:49 +00002328 S += '@';
Fariborz Jahanian892d5db2009-01-20 19:14:18 +00002329 if (FD || EncodingProperty) {
Fariborz Jahanianc69da272009-02-21 18:23:24 +00002330 const ObjCInterfaceType *OIT =
2331 PointeeTy.getUnqualifiedType()->getAsObjCInterfaceType();
Fariborz Jahanian892d5db2009-01-20 19:14:18 +00002332 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian320ac422008-12-20 19:17:01 +00002333 S += '"';
2334 S += OI->getNameAsCString();
Fariborz Jahanian892d5db2009-01-20 19:14:18 +00002335 for (unsigned i =0; i < OIT->getNumProtocols(); i++) {
2336 ObjCProtocolDecl *Proto = OIT->getProtocol(i);
2337 S += '<';
2338 S += Proto->getNameAsString();
2339 S += '>';
2340 }
Fariborz Jahanian320ac422008-12-20 19:17:01 +00002341 S += '"';
2342 }
Fariborz Jahanianc8679472008-12-19 00:14:49 +00002343 return;
Steve Naroff17c03822009-02-12 17:52:19 +00002344 } else if (isObjCClassStructType(PointeeTy)) {
Anders Carlsson7f23e3d2007-10-31 02:53:19 +00002345 S += '#';
2346 return;
Ted Kremenek42730c52008-01-07 19:49:32 +00002347 } else if (isObjCSelType(PointeeTy)) {
Anders Carlsson7f23e3d2007-10-31 02:53:19 +00002348 S += ':';
2349 return;
Fariborz Jahanian80faffa2007-10-30 17:06:23 +00002350 }
Anders Carlsson36f07d82007-10-29 05:01:08 +00002351
2352 if (PointeeTy->isCharType()) {
2353 // char pointer types should be encoded as '*' unless it is a
2354 // type that has been typedef'd to 'BOOL'.
Anders Carlssone3f02572007-10-29 06:33:42 +00002355 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson36f07d82007-10-29 05:01:08 +00002356 S += '*';
2357 return;
2358 }
2359 }
2360
2361 S += '^';
Fariborz Jahaniane07d9ec2008-12-23 19:56:47 +00002362 getLegacyIntegralTypeEncoding(PointeeTy);
2363
2364 getObjCEncodingForTypeImpl(PointeeTy, S,
Daniel Dunbaraa913102008-10-17 16:17:37 +00002365 false, ExpandPointedToStructures,
Fariborz Jahanian0cd547f2008-12-19 23:34:38 +00002366 NULL);
Chris Lattnera1923f62008-08-04 07:31:14 +00002367 } else if (const ArrayType *AT =
2368 // Ignore type qualifiers etc.
2369 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson858c64d2009-02-22 01:38:57 +00002370 if (isa<IncompleteArrayType>(AT)) {
2371 // Incomplete arrays are encoded as a pointer to the array element.
2372 S += '^';
2373
2374 getObjCEncodingForTypeImpl(AT->getElementType(), S,
2375 false, ExpandStructures, FD);
2376 } else {
2377 S += '[';
Anders Carlsson36f07d82007-10-29 05:01:08 +00002378
Anders Carlsson858c64d2009-02-22 01:38:57 +00002379 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
2380 S += llvm::utostr(CAT->getSize().getZExtValue());
2381 else {
2382 //Variable length arrays are encoded as a regular array with 0 elements.
2383 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
2384 S += '0';
2385 }
Anders Carlsson36f07d82007-10-29 05:01:08 +00002386
Anders Carlsson858c64d2009-02-22 01:38:57 +00002387 getObjCEncodingForTypeImpl(AT->getElementType(), S,
2388 false, ExpandStructures, FD);
2389 S += ']';
2390 }
Anders Carlsson5695bb72007-10-30 00:06:20 +00002391 } else if (T->getAsFunctionType()) {
2392 S += '?';
Fariborz Jahanianc8ba2bd2007-11-13 23:21:38 +00002393 } else if (const RecordType *RTy = T->getAsRecordType()) {
Daniel Dunbarf8cfe562008-10-17 07:30:50 +00002394 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbaraa913102008-10-17 16:17:37 +00002395 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar146b2d02008-10-17 06:22:57 +00002396 // Anonymous structures print as '?'
2397 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
2398 S += II->getName();
2399 } else {
2400 S += '?';
2401 }
Daniel Dunbarc9197cd2008-10-17 20:21:44 +00002402 if (ExpandStructures) {
Fariborz Jahanian248db262008-01-22 22:44:46 +00002403 S += '=';
Douglas Gregor8acb7272008-12-11 16:49:14 +00002404 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
2405 FieldEnd = RDecl->field_end();
2406 Field != FieldEnd; ++Field) {
Fariborz Jahanian0cd547f2008-12-19 23:34:38 +00002407 if (FD) {
Daniel Dunbaraa913102008-10-17 16:17:37 +00002408 S += '"';
Douglas Gregor8acb7272008-12-11 16:49:14 +00002409 S += Field->getNameAsString();
Daniel Dunbaraa913102008-10-17 16:17:37 +00002410 S += '"';
2411 }
2412
2413 // Special case bit-fields.
Fariborz Jahanian0cd547f2008-12-19 23:34:38 +00002414 if (Field->isBitField()) {
2415 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
2416 (*Field));
Daniel Dunbaraa913102008-10-17 16:17:37 +00002417 } else {
Fariborz Jahaniane07d9ec2008-12-23 19:56:47 +00002418 QualType qt = Field->getType();
2419 getLegacyIntegralTypeEncoding(qt);
2420 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian0cd547f2008-12-19 23:34:38 +00002421 FD);
Daniel Dunbaraa913102008-10-17 16:17:37 +00002422 }
Fariborz Jahanian248db262008-01-22 22:44:46 +00002423 }
Fariborz Jahanianc8ba2bd2007-11-13 23:21:38 +00002424 }
Daniel Dunbaraa913102008-10-17 16:17:37 +00002425 S += RDecl->isUnion() ? ')' : '}';
Steve Naroff49af3f32007-12-12 22:30:11 +00002426 } else if (T->isEnumeralType()) {
Fariborz Jahaniand1361952009-01-13 01:18:13 +00002427 if (FD && FD->isBitField())
2428 EncodeBitField(this, S, FD);
2429 else
2430 S += 'i';
Steve Naroff62f09f52008-09-24 15:05:44 +00002431 } else if (T->isBlockPointerType()) {
Steve Naroff725e0662009-02-02 18:24:29 +00002432 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Fariborz Jahanian0cd547f2008-12-19 23:34:38 +00002433 } else if (T->isObjCInterfaceType()) {
2434 // @encode(class_name)
2435 ObjCInterfaceDecl *OI = T->getAsObjCInterfaceType()->getDecl();
2436 S += '{';
2437 const IdentifierInfo *II = OI->getIdentifier();
2438 S += II->getName();
2439 S += '=';
Chris Lattner9329cf52009-03-31 08:48:01 +00002440 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian0cd547f2008-12-19 23:34:38 +00002441 CollectObjCIvars(OI, RecFields);
Chris Lattner9329cf52009-03-31 08:48:01 +00002442 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian0cd547f2008-12-19 23:34:38 +00002443 if (RecFields[i]->isBitField())
2444 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2445 RecFields[i]);
2446 else
2447 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2448 FD);
2449 }
2450 S += '}';
2451 }
2452 else
Steve Naroff53b6f4c2008-01-30 19:17:43 +00002453 assert(0 && "@encode for type not implemented!");
Anders Carlsson36f07d82007-10-29 05:01:08 +00002454}
2455
Ted Kremenek42730c52008-01-07 19:49:32 +00002456void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanian65e7eb52007-11-01 17:18:37 +00002457 std::string& S) const {
2458 if (QT & Decl::OBJC_TQ_In)
2459 S += 'n';
2460 if (QT & Decl::OBJC_TQ_Inout)
2461 S += 'N';
2462 if (QT & Decl::OBJC_TQ_Out)
2463 S += 'o';
2464 if (QT & Decl::OBJC_TQ_Bycopy)
2465 S += 'O';
2466 if (QT & Decl::OBJC_TQ_Byref)
2467 S += 'R';
2468 if (QT & Decl::OBJC_TQ_Oneway)
2469 S += 'V';
2470}
2471
Anders Carlssonfb5b1e82007-10-11 01:00:40 +00002472void ASTContext::setBuiltinVaListType(QualType T)
2473{
2474 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
2475
2476 BuiltinVaListType = T;
2477}
2478
Ted Kremenek42730c52008-01-07 19:49:32 +00002479void ASTContext::setObjCIdType(TypedefDecl *TD)
Steve Naroff9d12c902007-10-15 14:41:52 +00002480{
Ted Kremenek42730c52008-01-07 19:49:32 +00002481 ObjCIdType = getTypedefType(TD);
Steve Naroff9d12c902007-10-15 14:41:52 +00002482
2483 // typedef struct objc_object *id;
2484 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
Fariborz Jahaniande939672009-01-16 19:58:32 +00002485 // User error - caller will issue diagnostics.
2486 if (!ptr)
2487 return;
Steve Naroff9d12c902007-10-15 14:41:52 +00002488 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
Fariborz Jahaniande939672009-01-16 19:58:32 +00002489 // User error - caller will issue diagnostics.
2490 if (!rec)
2491 return;
Steve Naroff9d12c902007-10-15 14:41:52 +00002492 IdStructType = rec;
2493}
2494
Ted Kremenek42730c52008-01-07 19:49:32 +00002495void ASTContext::setObjCSelType(TypedefDecl *TD)
Fariborz Jahanianf807c202007-10-16 20:40:23 +00002496{
Ted Kremenek42730c52008-01-07 19:49:32 +00002497 ObjCSelType = getTypedefType(TD);
Fariborz Jahanianf807c202007-10-16 20:40:23 +00002498
2499 // typedef struct objc_selector *SEL;
2500 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
Fariborz Jahaniande939672009-01-16 19:58:32 +00002501 if (!ptr)
2502 return;
Fariborz Jahanianf807c202007-10-16 20:40:23 +00002503 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
Fariborz Jahaniande939672009-01-16 19:58:32 +00002504 if (!rec)
2505 return;
Fariborz Jahanianf807c202007-10-16 20:40:23 +00002506 SelStructType = rec;
2507}
2508
Ted Kremenek42730c52008-01-07 19:49:32 +00002509void ASTContext::setObjCProtoType(QualType QT)
Fariborz Jahanianb391e6e2007-10-17 16:58:11 +00002510{
Ted Kremenek42730c52008-01-07 19:49:32 +00002511 ObjCProtoType = QT;
Fariborz Jahanianb391e6e2007-10-17 16:58:11 +00002512}
2513
Ted Kremenek42730c52008-01-07 19:49:32 +00002514void ASTContext::setObjCClassType(TypedefDecl *TD)
Anders Carlsson7f23e3d2007-10-31 02:53:19 +00002515{
Ted Kremenek42730c52008-01-07 19:49:32 +00002516 ObjCClassType = getTypedefType(TD);
Anders Carlsson7f23e3d2007-10-31 02:53:19 +00002517
2518 // typedef struct objc_class *Class;
2519 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
2520 assert(ptr && "'Class' incorrectly typed");
2521 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
2522 assert(rec && "'Class' incorrectly typed");
2523 ClassStructType = rec;
2524}
2525
Ted Kremenek42730c52008-01-07 19:49:32 +00002526void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
2527 assert(ObjCConstantStringType.isNull() &&
Steve Narofff2e30312007-10-15 23:35:17 +00002528 "'NSConstantString' type already set!");
2529
Ted Kremenek42730c52008-01-07 19:49:32 +00002530 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff2e30312007-10-15 23:35:17 +00002531}
2532
Douglas Gregordd13e842009-03-30 22:58:21 +00002533/// \brief Retrieve the template name that represents a qualified
2534/// template name such as \c std::vector.
2535TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
2536 bool TemplateKeyword,
2537 TemplateDecl *Template) {
2538 llvm::FoldingSetNodeID ID;
2539 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
2540
2541 void *InsertPos = 0;
2542 QualifiedTemplateName *QTN =
2543 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
2544 if (!QTN) {
2545 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
2546 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
2547 }
2548
2549 return TemplateName(QTN);
2550}
2551
2552/// \brief Retrieve the template name that represents a dependent
2553/// template name such as \c MetaFun::template apply.
2554TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
2555 const IdentifierInfo *Name) {
2556 assert(NNS->isDependent() && "Nested name specifier must be dependent");
2557
2558 llvm::FoldingSetNodeID ID;
2559 DependentTemplateName::Profile(ID, NNS, Name);
2560
2561 void *InsertPos = 0;
2562 DependentTemplateName *QTN =
2563 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
2564
2565 if (QTN)
2566 return TemplateName(QTN);
2567
2568 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2569 if (CanonNNS == NNS) {
2570 QTN = new (*this,4) DependentTemplateName(NNS, Name);
2571 } else {
2572 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
2573 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
2574 }
2575
2576 DependentTemplateNames.InsertNode(QTN, InsertPos);
2577 return TemplateName(QTN);
2578}
2579
Douglas Gregorc6507e42008-11-03 14:12:49 +00002580/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorbb66b412008-11-03 15:57:00 +00002581/// TargetInfo, produce the corresponding type. The unsigned @p Type
2582/// is actually a value of type @c TargetInfo::IntType.
2583QualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorc6507e42008-11-03 14:12:49 +00002584 switch (Type) {
2585 case TargetInfo::NoInt: return QualType();
2586 case TargetInfo::SignedShort: return ShortTy;
2587 case TargetInfo::UnsignedShort: return UnsignedShortTy;
2588 case TargetInfo::SignedInt: return IntTy;
2589 case TargetInfo::UnsignedInt: return UnsignedIntTy;
2590 case TargetInfo::SignedLong: return LongTy;
2591 case TargetInfo::UnsignedLong: return UnsignedLongTy;
2592 case TargetInfo::SignedLongLong: return LongLongTy;
2593 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
2594 }
2595
2596 assert(false && "Unhandled TargetInfo::IntType value");
Daniel Dunbar7b0dcc22008-11-11 01:16:00 +00002597 return QualType();
Douglas Gregorc6507e42008-11-03 14:12:49 +00002598}
Ted Kremenek118930e2008-07-24 23:58:27 +00002599
2600//===----------------------------------------------------------------------===//
2601// Type Predicates.
2602//===----------------------------------------------------------------------===//
2603
Fariborz Jahanian82f54962009-01-13 23:34:40 +00002604/// isObjCNSObjectType - Return true if this is an NSObject object using
2605/// NSObject attribute on a c-style pointer type.
2606/// FIXME - Make it work directly on types.
2607///
2608bool ASTContext::isObjCNSObjectType(QualType Ty) const {
2609 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
2610 if (TypedefDecl *TD = TDT->getDecl())
2611 if (TD->getAttr<ObjCNSObjectAttr>())
2612 return true;
2613 }
2614 return false;
2615}
2616
Ted Kremenek118930e2008-07-24 23:58:27 +00002617/// isObjCObjectPointerType - Returns true if type is an Objective-C pointer
2618/// to an object type. This includes "id" and "Class" (two 'special' pointers
2619/// to struct), Interface* (pointer to ObjCInterfaceType) and id<P> (qualified
2620/// ID type).
2621bool ASTContext::isObjCObjectPointerType(QualType Ty) const {
Steve Naroff6805fc42009-02-23 18:36:16 +00002622 if (Ty->isObjCQualifiedIdType())
Ted Kremenek118930e2008-07-24 23:58:27 +00002623 return true;
2624
Steve Naroffd9e00802008-10-21 18:24:04 +00002625 // Blocks are objects.
2626 if (Ty->isBlockPointerType())
2627 return true;
2628
2629 // All other object types are pointers.
Ted Kremenek118930e2008-07-24 23:58:27 +00002630 if (!Ty->isPointerType())
2631 return false;
2632
2633 // Check to see if this is 'id' or 'Class', both of which are typedefs for
2634 // pointer types. This looks for the typedef specifically, not for the
2635 // underlying type.
Eli Friedman9c2b33f2009-03-22 23:00:19 +00002636 if (Ty.getUnqualifiedType() == getObjCIdType() ||
2637 Ty.getUnqualifiedType() == getObjCClassType())
Ted Kremenek118930e2008-07-24 23:58:27 +00002638 return true;
2639
2640 // If this a pointer to an interface (e.g. NSString*), it is ok.
Fariborz Jahanian82f54962009-01-13 23:34:40 +00002641 if (Ty->getAsPointerType()->getPointeeType()->isObjCInterfaceType())
2642 return true;
2643
2644 // If is has NSObject attribute, OK as well.
2645 return isObjCNSObjectType(Ty);
Ted Kremenek118930e2008-07-24 23:58:27 +00002646}
2647
Fariborz Jahanianb8ca6ff2009-02-18 21:49:28 +00002648/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
2649/// garbage collection attribute.
2650///
2651QualType::GCAttrTypes ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
Chris Lattner18b5a9a2009-02-18 22:53:11 +00002652 QualType::GCAttrTypes GCAttrs = QualType::GCNone;
Fariborz Jahanianb8ca6ff2009-02-18 21:49:28 +00002653 if (getLangOptions().ObjC1 &&
2654 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattner18b5a9a2009-02-18 22:53:11 +00002655 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanianb8ca6ff2009-02-18 21:49:28 +00002656 // Default behavious under objective-c's gc is for objective-c pointers
Fariborz Jahanianbbd4ca92009-02-19 23:36:06 +00002657 // (or pointers to them) be treated as though they were declared
2658 // as __strong.
2659 if (GCAttrs == QualType::GCNone) {
2660 if (isObjCObjectPointerType(Ty))
2661 GCAttrs = QualType::Strong;
2662 else if (Ty->isPointerType())
2663 return getObjCGCAttrKind(Ty->getAsPointerType()->getPointeeType());
2664 }
Fariborz Jahanianb8ca6ff2009-02-18 21:49:28 +00002665 }
Chris Lattner18b5a9a2009-02-18 22:53:11 +00002666 return GCAttrs;
Fariborz Jahanianb8ca6ff2009-02-18 21:49:28 +00002667}
2668
Chris Lattner6ff358b2008-04-07 06:51:04 +00002669//===----------------------------------------------------------------------===//
2670// Type Compatibility Testing
2671//===----------------------------------------------------------------------===//
Chris Lattner5003e8b2007-11-01 05:03:41 +00002672
Steve Naroff3454b6c2008-09-04 15:10:53 +00002673/// typesAreBlockCompatible - This routine is called when comparing two
Steve Naroffd6163f32008-09-05 22:11:13 +00002674/// block types. Types must be strictly compatible here. For example,
2675/// C unfortunately doesn't produce an error for the following:
2676///
2677/// int (*emptyArgFunc)();
2678/// int (*intArgList)(int) = emptyArgFunc;
2679///
2680/// For blocks, we will produce an error for the following (similar to C++):
2681///
2682/// int (^emptyArgBlock)();
2683/// int (^intArgBlock)(int) = emptyArgBlock;
2684///
2685/// FIXME: When the dust settles on this integration, fold this into mergeTypes.
2686///
Steve Naroff3454b6c2008-09-04 15:10:53 +00002687bool ASTContext::typesAreBlockCompatible(QualType lhs, QualType rhs) {
Steve Naroff09e1b9e2008-12-10 17:49:55 +00002688 const FunctionType *lbase = lhs->getAsFunctionType();
2689 const FunctionType *rbase = rhs->getAsFunctionType();
Douglas Gregor4fa58902009-02-26 23:50:07 +00002690 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
2691 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Mike Stump896ceed2009-04-01 01:17:39 +00002692 if (lproto && rproto == 0)
2693 return false;
2694 return !mergeTypes(lhs, rhs).isNull();
Steve Naroff3454b6c2008-09-04 15:10:53 +00002695}
2696
Chris Lattner6ff358b2008-04-07 06:51:04 +00002697/// areCompatVectorTypes - Return true if the two specified vector types are
2698/// compatible.
2699static bool areCompatVectorTypes(const VectorType *LHS,
2700 const VectorType *RHS) {
2701 assert(LHS->isCanonical() && RHS->isCanonical());
2702 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner2fda0ed2008-10-05 17:34:18 +00002703 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ff358b2008-04-07 06:51:04 +00002704}
2705
Eli Friedman0d9549b2008-08-22 00:56:42 +00002706/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ff358b2008-04-07 06:51:04 +00002707/// compatible for assignment from RHS to LHS. This handles validation of any
2708/// protocol qualifiers on the LHS or RHS.
2709///
Eli Friedman0d9549b2008-08-22 00:56:42 +00002710bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
2711 const ObjCInterfaceType *RHS) {
Chris Lattner6ff358b2008-04-07 06:51:04 +00002712 // Verify that the base decls are compatible: the RHS must be a subclass of
2713 // the LHS.
2714 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
2715 return false;
2716
2717 // RHS must have a superset of the protocols in the LHS. If the LHS is not
2718 // protocol qualified at all, then we are good.
2719 if (!isa<ObjCQualifiedInterfaceType>(LHS))
2720 return true;
2721
2722 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
2723 // isn't a superset.
2724 if (!isa<ObjCQualifiedInterfaceType>(RHS))
2725 return true; // FIXME: should return false!
2726
2727 // Finally, we must have two protocol-qualified interfaces.
2728 const ObjCQualifiedInterfaceType *LHSP =cast<ObjCQualifiedInterfaceType>(LHS);
2729 const ObjCQualifiedInterfaceType *RHSP =cast<ObjCQualifiedInterfaceType>(RHS);
Chris Lattner6ff358b2008-04-07 06:51:04 +00002730
Steve Naroff98e71b82009-03-01 16:12:44 +00002731 // All LHS protocols must have a presence on the RHS.
2732 assert(LHSP->qual_begin() != LHSP->qual_end() && "Empty LHS protocol list?");
Chris Lattner6ff358b2008-04-07 06:51:04 +00002733
Steve Naroff98e71b82009-03-01 16:12:44 +00002734 for (ObjCQualifiedInterfaceType::qual_iterator LHSPI = LHSP->qual_begin(),
2735 LHSPE = LHSP->qual_end();
2736 LHSPI != LHSPE; LHSPI++) {
2737 bool RHSImplementsProtocol = false;
2738
2739 // If the RHS doesn't implement the protocol on the left, the types
2740 // are incompatible.
2741 for (ObjCQualifiedInterfaceType::qual_iterator RHSPI = RHSP->qual_begin(),
2742 RHSPE = RHSP->qual_end();
2743 !RHSImplementsProtocol && (RHSPI != RHSPE); RHSPI++) {
2744 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier()))
2745 RHSImplementsProtocol = true;
2746 }
2747 // FIXME: For better diagnostics, consider passing back the protocol name.
2748 if (!RHSImplementsProtocol)
2749 return false;
Chris Lattner6ff358b2008-04-07 06:51:04 +00002750 }
Steve Naroff98e71b82009-03-01 16:12:44 +00002751 // The RHS implements all protocols listed on the LHS.
2752 return true;
Chris Lattner6ff358b2008-04-07 06:51:04 +00002753}
2754
Steve Naroff17c03822009-02-12 17:52:19 +00002755bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
2756 // get the "pointed to" types
2757 const PointerType *LHSPT = LHS->getAsPointerType();
2758 const PointerType *RHSPT = RHS->getAsPointerType();
2759
2760 if (!LHSPT || !RHSPT)
2761 return false;
2762
2763 QualType lhptee = LHSPT->getPointeeType();
2764 QualType rhptee = RHSPT->getPointeeType();
2765 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2766 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2767 // ID acts sort of like void* for ObjC interfaces
2768 if (LHSIface && isObjCIdStructType(rhptee))
2769 return true;
2770 if (RHSIface && isObjCIdStructType(lhptee))
2771 return true;
2772 if (!LHSIface || !RHSIface)
2773 return false;
2774 return canAssignObjCInterfaces(LHSIface, RHSIface) ||
2775 canAssignObjCInterfaces(RHSIface, LHSIface);
2776}
2777
Steve Naroff85f0dc52007-10-15 20:41:53 +00002778/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
2779/// both shall have the identically qualified version of a compatible type.
2780/// C99 6.2.7p1: Two types have compatible types if their types are the
2781/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman0d9549b2008-08-22 00:56:42 +00002782bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
2783 return !mergeTypes(LHS, RHS).isNull();
2784}
2785
2786QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
2787 const FunctionType *lbase = lhs->getAsFunctionType();
2788 const FunctionType *rbase = rhs->getAsFunctionType();
Douglas Gregor4fa58902009-02-26 23:50:07 +00002789 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
2790 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman0d9549b2008-08-22 00:56:42 +00002791 bool allLTypes = true;
2792 bool allRTypes = true;
2793
2794 // Check return type
2795 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
2796 if (retType.isNull()) return QualType();
Chris Lattner2fda0ed2008-10-05 17:34:18 +00002797 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
2798 allLTypes = false;
2799 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
2800 allRTypes = false;
Eli Friedman0d9549b2008-08-22 00:56:42 +00002801
2802 if (lproto && rproto) { // two C99 style function prototypes
2803 unsigned lproto_nargs = lproto->getNumArgs();
2804 unsigned rproto_nargs = rproto->getNumArgs();
2805
2806 // Compatible functions must have the same number of arguments
2807 if (lproto_nargs != rproto_nargs)
2808 return QualType();
2809
2810 // Variadic and non-variadic functions aren't compatible
2811 if (lproto->isVariadic() != rproto->isVariadic())
2812 return QualType();
2813
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002814 if (lproto->getTypeQuals() != rproto->getTypeQuals())
2815 return QualType();
2816
Eli Friedman0d9549b2008-08-22 00:56:42 +00002817 // Check argument compatibility
2818 llvm::SmallVector<QualType, 10> types;
2819 for (unsigned i = 0; i < lproto_nargs; i++) {
2820 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
2821 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
2822 QualType argtype = mergeTypes(largtype, rargtype);
2823 if (argtype.isNull()) return QualType();
2824 types.push_back(argtype);
Chris Lattner2fda0ed2008-10-05 17:34:18 +00002825 if (getCanonicalType(argtype) != getCanonicalType(largtype))
2826 allLTypes = false;
2827 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
2828 allRTypes = false;
Eli Friedman0d9549b2008-08-22 00:56:42 +00002829 }
2830 if (allLTypes) return lhs;
2831 if (allRTypes) return rhs;
2832 return getFunctionType(retType, types.begin(), types.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002833 lproto->isVariadic(), lproto->getTypeQuals());
Eli Friedman0d9549b2008-08-22 00:56:42 +00002834 }
2835
2836 if (lproto) allRTypes = false;
2837 if (rproto) allLTypes = false;
2838
Douglas Gregor4fa58902009-02-26 23:50:07 +00002839 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman0d9549b2008-08-22 00:56:42 +00002840 if (proto) {
2841 if (proto->isVariadic()) return QualType();
2842 // Check that the types are compatible with the types that
2843 // would result from default argument promotions (C99 6.7.5.3p15).
2844 // The only types actually affected are promotable integer
2845 // types and floats, which would be passed as a different
2846 // type depending on whether the prototype is visible.
2847 unsigned proto_nargs = proto->getNumArgs();
2848 for (unsigned i = 0; i < proto_nargs; ++i) {
2849 QualType argTy = proto->getArgType(i);
2850 if (argTy->isPromotableIntegerType() ||
2851 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
2852 return QualType();
2853 }
2854
2855 if (allLTypes) return lhs;
2856 if (allRTypes) return rhs;
2857 return getFunctionType(retType, proto->arg_type_begin(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002858 proto->getNumArgs(), lproto->isVariadic(),
2859 lproto->getTypeQuals());
Eli Friedman0d9549b2008-08-22 00:56:42 +00002860 }
2861
2862 if (allLTypes) return lhs;
2863 if (allRTypes) return rhs;
Douglas Gregor4fa58902009-02-26 23:50:07 +00002864 return getFunctionNoProtoType(retType);
Eli Friedman0d9549b2008-08-22 00:56:42 +00002865}
2866
2867QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
Bill Wendling6a9d8542007-12-03 07:33:35 +00002868 // C++ [expr]: If an expression initially has the type "reference to T", the
2869 // type is adjusted to "T" prior to any further analysis, the expression
2870 // designates the object or function denoted by the reference, and the
Sebastian Redlce6fff02009-03-16 23:22:08 +00002871 // expression is an lvalue unless the reference is an rvalue reference and
2872 // the expression is a function call (possibly inside parentheses).
Eli Friedman0d9549b2008-08-22 00:56:42 +00002873 // FIXME: C++ shouldn't be going through here! The rules are different
2874 // enough that they should be handled separately.
Sebastian Redlce6fff02009-03-16 23:22:08 +00002875 // FIXME: Merging of lvalue and rvalue references is incorrect. C++ *really*
2876 // shouldn't be going through here!
Eli Friedman0d9549b2008-08-22 00:56:42 +00002877 if (const ReferenceType *RT = LHS->getAsReferenceType())
Chris Lattner855fed42008-04-07 04:07:56 +00002878 LHS = RT->getPointeeType();
Eli Friedman0d9549b2008-08-22 00:56:42 +00002879 if (const ReferenceType *RT = RHS->getAsReferenceType())
Chris Lattner855fed42008-04-07 04:07:56 +00002880 RHS = RT->getPointeeType();
Chris Lattnerd47d6042008-04-07 05:37:56 +00002881
Eli Friedman0d9549b2008-08-22 00:56:42 +00002882 QualType LHSCan = getCanonicalType(LHS),
2883 RHSCan = getCanonicalType(RHS);
2884
2885 // If two types are identical, they are compatible.
2886 if (LHSCan == RHSCan)
2887 return LHS;
2888
2889 // If the qualifiers are different, the types aren't compatible
Eli Friedman94fcc9a2009-02-27 23:04:43 +00002890 // Note that we handle extended qualifiers later, in the
2891 // case for ExtQualType.
2892 if (LHSCan.getCVRQualifiers() != RHSCan.getCVRQualifiers())
Eli Friedman0d9549b2008-08-22 00:56:42 +00002893 return QualType();
2894
2895 Type::TypeClass LHSClass = LHSCan->getTypeClass();
2896 Type::TypeClass RHSClass = RHSCan->getTypeClass();
2897
Chris Lattnerc38d4522008-01-14 05:45:46 +00002898 // We want to consider the two function types to be the same for these
2899 // comparisons, just force one to the other.
2900 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
2901 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman398837e2008-02-12 08:23:06 +00002902
2903 // Same as above for arrays
Chris Lattnerb5709e22008-04-07 05:43:21 +00002904 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
2905 LHSClass = Type::ConstantArray;
2906 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
2907 RHSClass = Type::ConstantArray;
Steve Naroff85f0dc52007-10-15 20:41:53 +00002908
Nate Begemanaf6ed502008-04-18 23:10:10 +00002909 // Canonicalize ExtVector -> Vector.
2910 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
2911 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Chris Lattnerb5709e22008-04-07 05:43:21 +00002912
Chris Lattner7cdcb252008-04-07 06:38:24 +00002913 // Consider qualified interfaces and interfaces the same.
2914 if (LHSClass == Type::ObjCQualifiedInterface) LHSClass = Type::ObjCInterface;
2915 if (RHSClass == Type::ObjCQualifiedInterface) RHSClass = Type::ObjCInterface;
Eli Friedman0d9549b2008-08-22 00:56:42 +00002916
Chris Lattnerb5709e22008-04-07 05:43:21 +00002917 // If the canonical type classes don't match.
Chris Lattnerc38d4522008-01-14 05:45:46 +00002918 if (LHSClass != RHSClass) {
Steve Naroff0bbc1352009-02-21 16:18:07 +00002919 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
2920 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
2921
2922 // ID acts sort of like void* for ObjC interfaces
2923 if (LHSIface && isObjCIdStructType(RHS))
2924 return LHS;
2925 if (RHSIface && isObjCIdStructType(LHS))
2926 return RHS;
2927
Steve Naroff28ceff72008-12-10 22:14:21 +00002928 // ID is compatible with all qualified id types.
2929 if (LHS->isObjCQualifiedIdType()) {
2930 if (const PointerType *PT = RHS->getAsPointerType()) {
2931 QualType pType = PT->getPointeeType();
Steve Naroff17c03822009-02-12 17:52:19 +00002932 if (isObjCIdStructType(pType))
Steve Naroff28ceff72008-12-10 22:14:21 +00002933 return LHS;
2934 // FIXME: need to use ObjCQualifiedIdTypesAreCompatible(LHS, RHS, true).
2935 // Unfortunately, this API is part of Sema (which we don't have access
2936 // to. Need to refactor. The following check is insufficient, since we
2937 // need to make sure the class implements the protocol.
2938 if (pType->isObjCInterfaceType())
2939 return LHS;
2940 }
2941 }
2942 if (RHS->isObjCQualifiedIdType()) {
2943 if (const PointerType *PT = LHS->getAsPointerType()) {
2944 QualType pType = PT->getPointeeType();
Steve Naroff17c03822009-02-12 17:52:19 +00002945 if (isObjCIdStructType(pType))
Steve Naroff28ceff72008-12-10 22:14:21 +00002946 return RHS;
2947 // FIXME: need to use ObjCQualifiedIdTypesAreCompatible(LHS, RHS, true).
2948 // Unfortunately, this API is part of Sema (which we don't have access
2949 // to. Need to refactor. The following check is insufficient, since we
2950 // need to make sure the class implements the protocol.
2951 if (pType->isObjCInterfaceType())
2952 return RHS;
2953 }
2954 }
Chris Lattnerc38d4522008-01-14 05:45:46 +00002955 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
2956 // a signed integer type, or an unsigned integer type.
Eli Friedman0d9549b2008-08-22 00:56:42 +00002957 if (const EnumType* ETy = LHS->getAsEnumType()) {
2958 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
2959 return RHS;
Eli Friedmanad6c06c2008-02-12 08:46:17 +00002960 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00002961 if (const EnumType* ETy = RHS->getAsEnumType()) {
2962 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
2963 return LHS;
Eli Friedmanad6c06c2008-02-12 08:46:17 +00002964 }
Chris Lattnerc38d4522008-01-14 05:45:46 +00002965
Eli Friedman0d9549b2008-08-22 00:56:42 +00002966 return QualType();
Steve Naroff85f0dc52007-10-15 20:41:53 +00002967 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00002968
Steve Naroffc88babe2008-01-09 22:43:08 +00002969 // The canonical type classes match.
Chris Lattnerc38d4522008-01-14 05:45:46 +00002970 switch (LHSClass) {
Douglas Gregor4fa58902009-02-26 23:50:07 +00002971#define TYPE(Class, Base)
2972#define ABSTRACT_TYPE(Class, Base)
2973#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2974#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2975#include "clang/AST/TypeNodes.def"
2976 assert(false && "Non-canonical and dependent types shouldn't get here");
2977 return QualType();
2978
Sebastian Redlce6fff02009-03-16 23:22:08 +00002979 case Type::LValueReference:
2980 case Type::RValueReference:
Douglas Gregor4fa58902009-02-26 23:50:07 +00002981 case Type::MemberPointer:
2982 assert(false && "C++ should never be in mergeTypes");
2983 return QualType();
2984
2985 case Type::IncompleteArray:
2986 case Type::VariableArray:
2987 case Type::FunctionProto:
2988 case Type::ExtVector:
2989 case Type::ObjCQualifiedInterface:
2990 assert(false && "Types are eliminated above");
2991 return QualType();
2992
Chris Lattnerc38d4522008-01-14 05:45:46 +00002993 case Type::Pointer:
Eli Friedman0d9549b2008-08-22 00:56:42 +00002994 {
2995 // Merge two pointer types, while trying to preserve typedef info
2996 QualType LHSPointee = LHS->getAsPointerType()->getPointeeType();
2997 QualType RHSPointee = RHS->getAsPointerType()->getPointeeType();
2998 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
2999 if (ResultType.isNull()) return QualType();
Chris Lattner2fda0ed2008-10-05 17:34:18 +00003000 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
3001 return LHS;
3002 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
3003 return RHS;
Eli Friedman0d9549b2008-08-22 00:56:42 +00003004 return getPointerType(ResultType);
3005 }
Steve Naroff09e1b9e2008-12-10 17:49:55 +00003006 case Type::BlockPointer:
3007 {
3008 // Merge two block pointer types, while trying to preserve typedef info
3009 QualType LHSPointee = LHS->getAsBlockPointerType()->getPointeeType();
3010 QualType RHSPointee = RHS->getAsBlockPointerType()->getPointeeType();
3011 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
3012 if (ResultType.isNull()) return QualType();
3013 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
3014 return LHS;
3015 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
3016 return RHS;
3017 return getBlockPointerType(ResultType);
3018 }
Chris Lattnerc38d4522008-01-14 05:45:46 +00003019 case Type::ConstantArray:
Eli Friedman0d9549b2008-08-22 00:56:42 +00003020 {
3021 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
3022 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
3023 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
3024 return QualType();
3025
3026 QualType LHSElem = getAsArrayType(LHS)->getElementType();
3027 QualType RHSElem = getAsArrayType(RHS)->getElementType();
3028 QualType ResultType = mergeTypes(LHSElem, RHSElem);
3029 if (ResultType.isNull()) return QualType();
Chris Lattner2fda0ed2008-10-05 17:34:18 +00003030 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3031 return LHS;
3032 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3033 return RHS;
Eli Friedmanc91a3f32008-08-22 01:48:21 +00003034 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
3035 ArrayType::ArraySizeModifier(), 0);
3036 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
3037 ArrayType::ArraySizeModifier(), 0);
Eli Friedman0d9549b2008-08-22 00:56:42 +00003038 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
3039 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner2fda0ed2008-10-05 17:34:18 +00003040 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3041 return LHS;
3042 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3043 return RHS;
Eli Friedman0d9549b2008-08-22 00:56:42 +00003044 if (LVAT) {
3045 // FIXME: This isn't correct! But tricky to implement because
3046 // the array's size has to be the size of LHS, but the type
3047 // has to be different.
3048 return LHS;
3049 }
3050 if (RVAT) {
3051 // FIXME: This isn't correct! But tricky to implement because
3052 // the array's size has to be the size of RHS, but the type
3053 // has to be different.
3054 return RHS;
3055 }
Eli Friedmanc91a3f32008-08-22 01:48:21 +00003056 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
3057 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Chris Lattner2fda0ed2008-10-05 17:34:18 +00003058 return getIncompleteArrayType(ResultType, ArrayType::ArraySizeModifier(),0);
Eli Friedman0d9549b2008-08-22 00:56:42 +00003059 }
Chris Lattnerc38d4522008-01-14 05:45:46 +00003060 case Type::FunctionNoProto:
Eli Friedman0d9549b2008-08-22 00:56:42 +00003061 return mergeFunctionTypes(LHS, RHS);
Douglas Gregor4fa58902009-02-26 23:50:07 +00003062 case Type::Record:
Douglas Gregor4fa58902009-02-26 23:50:07 +00003063 case Type::Enum:
Eli Friedman0d9549b2008-08-22 00:56:42 +00003064 // FIXME: Why are these compatible?
Steve Naroff17c03822009-02-12 17:52:19 +00003065 if (isObjCIdStructType(LHS) && isObjCClassStructType(RHS)) return LHS;
3066 if (isObjCClassStructType(LHS) && isObjCIdStructType(RHS)) return LHS;
Eli Friedman0d9549b2008-08-22 00:56:42 +00003067 return QualType();
Chris Lattnerc38d4522008-01-14 05:45:46 +00003068 case Type::Builtin:
Chris Lattnerd1240fa2008-04-07 05:55:38 +00003069 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman0d9549b2008-08-22 00:56:42 +00003070 return QualType();
Daniel Dunbar457f33d2009-01-28 21:22:12 +00003071 case Type::Complex:
3072 // Distinct complex types are incompatible.
3073 return QualType();
Chris Lattnerd1240fa2008-04-07 05:55:38 +00003074 case Type::Vector:
Eli Friedman94fcc9a2009-02-27 23:04:43 +00003075 // FIXME: The merged type should be an ExtVector!
Eli Friedman0d9549b2008-08-22 00:56:42 +00003076 if (areCompatVectorTypes(LHS->getAsVectorType(), RHS->getAsVectorType()))
3077 return LHS;
Chris Lattner2fda0ed2008-10-05 17:34:18 +00003078 return QualType();
Cédric Venet23536132009-02-21 17:14:49 +00003079 case Type::ObjCInterface: {
Steve Naroff0bbc1352009-02-21 16:18:07 +00003080 // Check if the interfaces are assignment compatible.
Eli Friedman94fcc9a2009-02-27 23:04:43 +00003081 // FIXME: This should be type compatibility, e.g. whether
3082 // "LHS x; RHS x;" at global scope is legal.
Steve Naroff0bbc1352009-02-21 16:18:07 +00003083 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
3084 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
3085 if (LHSIface && RHSIface &&
3086 canAssignObjCInterfaces(LHSIface, RHSIface))
3087 return LHS;
3088
Eli Friedman0d9549b2008-08-22 00:56:42 +00003089 return QualType();
Cédric Venet23536132009-02-21 17:14:49 +00003090 }
Steve Naroff28ceff72008-12-10 22:14:21 +00003091 case Type::ObjCQualifiedId:
3092 // Distinct qualified id's are not compatible.
3093 return QualType();
Eli Friedman94fcc9a2009-02-27 23:04:43 +00003094 case Type::FixedWidthInt:
3095 // Distinct fixed-width integers are not compatible.
3096 return QualType();
3097 case Type::ObjCQualifiedClass:
3098 // Distinct qualified classes are not compatible.
3099 return QualType();
3100 case Type::ExtQual:
3101 // FIXME: ExtQual types can be compatible even if they're not
3102 // identical!
3103 return QualType();
3104 // First attempt at an implementation, but I'm not really sure it's
3105 // right...
3106#if 0
3107 ExtQualType* LQual = cast<ExtQualType>(LHSCan);
3108 ExtQualType* RQual = cast<ExtQualType>(RHSCan);
3109 if (LQual->getAddressSpace() != RQual->getAddressSpace() ||
3110 LQual->getObjCGCAttr() != RQual->getObjCGCAttr())
3111 return QualType();
3112 QualType LHSBase, RHSBase, ResultType, ResCanUnqual;
3113 LHSBase = QualType(LQual->getBaseType(), 0);
3114 RHSBase = QualType(RQual->getBaseType(), 0);
3115 ResultType = mergeTypes(LHSBase, RHSBase);
3116 if (ResultType.isNull()) return QualType();
3117 ResCanUnqual = getCanonicalType(ResultType).getUnqualifiedType();
3118 if (LHSCan.getUnqualifiedType() == ResCanUnqual)
3119 return LHS;
3120 if (RHSCan.getUnqualifiedType() == ResCanUnqual)
3121 return RHS;
3122 ResultType = getAddrSpaceQualType(ResultType, LQual->getAddressSpace());
3123 ResultType = getObjCGCQualType(ResultType, LQual->getObjCGCAttr());
3124 ResultType.setCVRQualifiers(LHSCan.getCVRQualifiers());
3125 return ResultType;
3126#endif
Douglas Gregordd13e842009-03-30 22:58:21 +00003127
3128 case Type::TemplateSpecialization:
3129 assert(false && "Dependent types have no size");
3130 break;
Steve Naroff85f0dc52007-10-15 20:41:53 +00003131 }
Douglas Gregor4fa58902009-02-26 23:50:07 +00003132
3133 return QualType();
Steve Naroff85f0dc52007-10-15 20:41:53 +00003134}
Ted Kremenek738e6c02007-10-31 17:10:13 +00003135
Chris Lattner1d78a862008-04-07 07:01:58 +00003136//===----------------------------------------------------------------------===//
Eli Friedman0832dbc2008-06-28 06:23:08 +00003137// Integer Predicates
3138//===----------------------------------------------------------------------===//
Chris Lattner74f67012009-01-16 07:15:35 +00003139
Eli Friedman0832dbc2008-06-28 06:23:08 +00003140unsigned ASTContext::getIntWidth(QualType T) {
3141 if (T == BoolTy)
3142 return 1;
Eli Friedmanff3fcdf2009-02-13 02:31:07 +00003143 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T)) {
3144 return FWIT->getWidth();
3145 }
3146 // For builtin types, just use the standard type sizing method
Eli Friedman0832dbc2008-06-28 06:23:08 +00003147 return (unsigned)getTypeSize(T);
3148}
3149
3150QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
3151 assert(T->isSignedIntegerType() && "Unexpected type");
3152 if (const EnumType* ETy = T->getAsEnumType())
3153 T = ETy->getDecl()->getIntegerType();
3154 const BuiltinType* BTy = T->getAsBuiltinType();
3155 assert (BTy && "Unexpected signed integer type");
3156 switch (BTy->getKind()) {
3157 case BuiltinType::Char_S:
3158 case BuiltinType::SChar:
3159 return UnsignedCharTy;
3160 case BuiltinType::Short:
3161 return UnsignedShortTy;
3162 case BuiltinType::Int:
3163 return UnsignedIntTy;
3164 case BuiltinType::Long:
3165 return UnsignedLongTy;
3166 case BuiltinType::LongLong:
3167 return UnsignedLongLongTy;
3168 default:
3169 assert(0 && "Unexpected signed integer type");
3170 return QualType();
3171 }
3172}
3173
3174
3175//===----------------------------------------------------------------------===//
Chris Lattner1d78a862008-04-07 07:01:58 +00003176// Serialization Support
3177//===----------------------------------------------------------------------===//
3178
Chris Lattnerb09b31d2009-03-28 03:45:20 +00003179enum {
3180 BasicMetadataBlock = 1,
3181 ASTContextBlock = 2,
3182 DeclsBlock = 3
3183};
3184
Chris Lattnerf4fbc442009-03-28 04:27:18 +00003185void ASTContext::EmitASTBitcodeBuffer(std::vector<unsigned char> &Buffer) const{
3186 // Create bitstream.
3187 llvm::BitstreamWriter Stream(Buffer);
3188
3189 // Emit the preamble.
3190 Stream.Emit((unsigned)'B', 8);
3191 Stream.Emit((unsigned)'C', 8);
3192 Stream.Emit(0xC, 4);
3193 Stream.Emit(0xF, 4);
3194 Stream.Emit(0xE, 4);
3195 Stream.Emit(0x0, 4);
3196
3197 // Create serializer.
3198 llvm::Serializer S(Stream);
3199
Chris Lattnerb09b31d2009-03-28 03:45:20 +00003200 // ===---------------------------------------------------===/
3201 // Serialize the "Translation Unit" metadata.
3202 // ===---------------------------------------------------===/
3203
3204 // Emit ASTContext.
3205 S.EnterBlock(ASTContextBlock);
3206 S.EmitOwnedPtr(this);
3207 S.ExitBlock(); // exit "ASTContextBlock"
3208
3209 S.EnterBlock(BasicMetadataBlock);
3210
3211 // Block for SourceManager and Target. Allows easy skipping
3212 // around to the block for the Selectors during deserialization.
3213 S.EnterBlock();
3214
3215 // Emit the SourceManager.
3216 S.Emit(getSourceManager());
3217
3218 // Emit the Target.
3219 S.EmitPtr(&Target);
3220 S.EmitCStr(Target.getTargetTriple());
3221
3222 S.ExitBlock(); // exit "SourceManager and Target Block"
3223
3224 // Emit the Selectors.
3225 S.Emit(Selectors);
3226
3227 // Emit the Identifier Table.
3228 S.Emit(Idents);
3229
3230 S.ExitBlock(); // exit "BasicMetadataBlock"
3231}
3232
3233
Ted Kremenek738e6c02007-10-31 17:10:13 +00003234/// Emit - Serialize an ASTContext object to Bitcode.
3235void ASTContext::Emit(llvm::Serializer& S) const {
Ted Kremenek842126e2008-06-04 15:55:15 +00003236 S.Emit(LangOpts);
Ted Kremenek9af4d5c2007-10-31 20:00:03 +00003237 S.EmitRef(SourceMgr);
3238 S.EmitRef(Target);
3239 S.EmitRef(Idents);
3240 S.EmitRef(Selectors);
Ted Kremenek738e6c02007-10-31 17:10:13 +00003241
Ted Kremenek68228a92007-10-31 22:44:07 +00003242 // Emit the size of the type vector so that we can reserve that size
3243 // when we reconstitute the ASTContext object.
Ted Kremenek0199d9f2007-11-06 22:26:16 +00003244 S.EmitInt(Types.size());
3245
Ted Kremenek034a78c2007-11-13 22:02:55 +00003246 for (std::vector<Type*>::const_iterator I=Types.begin(), E=Types.end();
3247 I!=E;++I)
3248 (*I)->Emit(S);
Ted Kremenek0199d9f2007-11-06 22:26:16 +00003249
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00003250 S.EmitOwnedPtr(TUDecl);
3251
Ted Kremeneke1fed7a2007-11-01 18:11:32 +00003252 // FIXME: S.EmitOwnedPtr(CFConstantStringTypeDecl);
Ted Kremenek738e6c02007-10-31 17:10:13 +00003253}
3254
Chris Lattnerf4fbc442009-03-28 04:27:18 +00003255
3256ASTContext *ASTContext::ReadASTBitcodeBuffer(llvm::MemoryBuffer &Buffer,
3257 FileManager &FMgr) {
3258 // Check if the file is of the proper length.
3259 if (Buffer.getBufferSize() & 0x3) {
3260 // FIXME: Provide diagnostic: "Length should be a multiple of 4 bytes."
3261 return 0;
3262 }
3263
3264 // Create the bitstream reader.
3265 unsigned char *BufPtr = (unsigned char *)Buffer.getBufferStart();
3266 llvm::BitstreamReader Stream(BufPtr, BufPtr+Buffer.getBufferSize());
3267
3268 if (Stream.Read(8) != 'B' ||
3269 Stream.Read(8) != 'C' ||
3270 Stream.Read(4) != 0xC ||
3271 Stream.Read(4) != 0xF ||
3272 Stream.Read(4) != 0xE ||
3273 Stream.Read(4) != 0x0) {
3274 // FIXME: Provide diagnostic.
3275 return NULL;
3276 }
3277
3278 // Create the deserializer.
3279 llvm::Deserializer Dezr(Stream);
3280
Chris Lattnerb09b31d2009-03-28 03:45:20 +00003281 // ===---------------------------------------------------===/
3282 // Deserialize the "Translation Unit" metadata.
3283 // ===---------------------------------------------------===/
3284
3285 // Skip to the BasicMetaDataBlock. First jump to ASTContextBlock
3286 // (which will appear earlier) and record its location.
3287
3288 bool FoundBlock = Dezr.SkipToBlock(ASTContextBlock);
3289 assert (FoundBlock);
3290
3291 llvm::Deserializer::Location ASTContextBlockLoc =
3292 Dezr.getCurrentBlockLocation();
3293
3294 FoundBlock = Dezr.SkipToBlock(BasicMetadataBlock);
3295 assert (FoundBlock);
3296
3297 // Read the SourceManager.
3298 SourceManager::CreateAndRegister(Dezr, FMgr);
3299
3300 { // Read the TargetInfo.
3301 llvm::SerializedPtrID PtrID = Dezr.ReadPtrID();
3302 char* triple = Dezr.ReadCStr(NULL,0,true);
3303 Dezr.RegisterPtr(PtrID, TargetInfo::CreateTargetInfo(std::string(triple)));
3304 delete [] triple;
3305 }
3306
3307 // For Selectors, we must read the identifier table first because the
3308 // SelectorTable depends on the identifiers being already deserialized.
3309 llvm::Deserializer::Location SelectorBlkLoc = Dezr.getCurrentBlockLocation();
3310 Dezr.SkipBlock();
3311
3312 // Read the identifier table.
3313 IdentifierTable::CreateAndRegister(Dezr);
3314
3315 // Now jump back and read the selectors.
3316 Dezr.JumpTo(SelectorBlkLoc);
3317 SelectorTable::CreateAndRegister(Dezr);
3318
3319 // Now jump back to ASTContextBlock and read the ASTContext.
3320 Dezr.JumpTo(ASTContextBlockLoc);
3321 return Dezr.ReadOwnedPtr<ASTContext>();
3322}
3323
Ted Kremenekacba3612007-11-13 00:25:37 +00003324ASTContext* ASTContext::Create(llvm::Deserializer& D) {
Ted Kremenek842126e2008-06-04 15:55:15 +00003325
3326 // Read the language options.
3327 LangOptions LOpts;
3328 LOpts.Read(D);
3329
Ted Kremenek68228a92007-10-31 22:44:07 +00003330 SourceManager &SM = D.ReadRef<SourceManager>();
3331 TargetInfo &t = D.ReadRef<TargetInfo>();
3332 IdentifierTable &idents = D.ReadRef<IdentifierTable>();
3333 SelectorTable &sels = D.ReadRef<SelectorTable>();
Chris Lattnereee57c02008-04-04 06:12:32 +00003334
Ted Kremenek68228a92007-10-31 22:44:07 +00003335 unsigned size_reserve = D.ReadInt();
3336
Douglas Gregor24afd4a2008-11-17 14:58:09 +00003337 ASTContext* A = new ASTContext(LOpts, SM, t, idents, sels,
3338 size_reserve);
Ted Kremenek68228a92007-10-31 22:44:07 +00003339
Ted Kremenek034a78c2007-11-13 22:02:55 +00003340 for (unsigned i = 0; i < size_reserve; ++i)
3341 Type::Create(*A,i,D);
Chris Lattnereee57c02008-04-04 06:12:32 +00003342
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00003343 A->TUDecl = cast<TranslationUnitDecl>(D.ReadOwnedPtr<Decl>(*A));
3344
Ted Kremeneke1fed7a2007-11-01 18:11:32 +00003345 // FIXME: A->CFConstantStringTypeDecl = D.ReadOwnedPtr<RecordDecl>();
Ted Kremenek68228a92007-10-31 22:44:07 +00003346
3347 return A;
3348}