blob: 25a957925838a4c201c7a4c07ef2defbddb0c8fe [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +000015#include "clang/AST/DeclCXX.h"
Steve Naroff980e5082007-10-01 19:00:59 +000016#include "clang/AST/DeclObjC.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000017#include "clang/AST/DeclTemplate.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000018#include "clang/AST/Expr.h"
19#include "clang/AST/RecordLayout.h"
Chris Lattnera9376d42009-03-28 03:45:20 +000020#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000021#include "clang/Basic/TargetInfo.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000022#include "llvm/ADT/StringExtras.h"
Ted Kremenek7192f8e2007-10-31 17:10:13 +000023#include "llvm/Bitcode/Serialize.h"
24#include "llvm/Bitcode/Deserialize.h"
Nate Begeman6fe7c8a2009-01-18 06:42:49 +000025#include "llvm/Support/MathExtras.h"
Chris Lattner557c5b12009-03-28 04:27:18 +000026#include "llvm/Support/MemoryBuffer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027using namespace clang;
28
29enum FloatingRank {
30 FloatRank, DoubleRank, LongDoubleRank
31};
32
Chris Lattner61710852008-10-05 17:34:18 +000033ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
34 TargetInfo &t,
Daniel Dunbare91593e2008-08-11 04:54:23 +000035 IdentifierTable &idents, SelectorTable &sels,
Steve Naroffc0ac4922009-01-27 23:20:32 +000036 bool FreeMem, unsigned size_reserve) :
Douglas Gregorab452ba2009-03-26 23:50:42 +000037 GlobalNestedNameSpecifier(0), CFConstantStringTypeDecl(0),
38 ObjCFastEnumerationStateTypeDecl(0), SourceMgr(SM), LangOpts(LOpts),
Chris Lattnered0e4972009-03-28 01:44:40 +000039 FreeMemory(FreeMem), Target(t), Idents(idents), Selectors(sels) {
Daniel Dunbare91593e2008-08-11 04:54:23 +000040 if (size_reserve > 0) Types.reserve(size_reserve);
41 InitBuiltinTypes();
Chris Lattner7644f072009-03-13 22:38:49 +000042 BuiltinInfo.InitializeBuiltins(idents, Target, LangOpts.NoBuiltin);
Daniel Dunbare91593e2008-08-11 04:54:23 +000043 TUDecl = TranslationUnitDecl::Create(*this);
44}
45
Reid Spencer5f016e22007-07-11 17:01:13 +000046ASTContext::~ASTContext() {
47 // Deallocate all the types.
48 while (!Types.empty()) {
Ted Kremenek4b05b1d2008-05-21 16:38:54 +000049 Types.back()->Destroy(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +000050 Types.pop_back();
51 }
Eli Friedmanb26153c2008-05-27 03:08:09 +000052
Nuno Lopesb74668e2008-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 {
72 llvm::DenseMap<const ObjCInterfaceDecl*, const RecordDecl*>::iterator
73 I = ASTRecordForInterface.begin(), E = ASTRecordForInterface.end();
74 while (I != E) {
75 RecordDecl *R = const_cast<RecordDecl*>((I++)->second);
76 R->Destroy(*this);
77 }
78 }
79
Douglas Gregorab452ba2009-03-26 23:50:42 +000080 // Destroy nested-name-specifiers.
Douglas Gregor1ae0afa2009-03-27 23:54:10 +000081 for (llvm::FoldingSet<NestedNameSpecifier>::iterator
82 NNS = NestedNameSpecifiers.begin(),
83 NNSEnd = NestedNameSpecifiers.end();
Douglas Gregore7dcd782009-03-27 23:25:45 +000084 NNS != NNSEnd;
Douglas Gregor1ae0afa2009-03-27 23:54:10 +000085 /* Increment in loop */)
86 (*NNS++).Destroy(*this);
Douglas Gregorab452ba2009-03-26 23:50:42 +000087
88 if (GlobalNestedNameSpecifier)
89 GlobalNestedNameSpecifier->Destroy(*this);
90
Eli Friedmanb26153c2008-05-27 03:08:09 +000091 TUDecl->Destroy(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +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 Dunbar248e1c02008-09-26 03:23:00 +000098 unsigned NumVector = 0, NumComplex = 0, NumBlockPointer = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +000099 unsigned NumFunctionNP = 0, NumTypeName = 0, NumTagged = 0;
100 unsigned NumLValueReference = 0, NumRValueReference = 0, NumMemberPointer = 0;
101
Reid Spencer5f016e22007-07-11 17:01:13 +0000102 unsigned NumTagStruct = 0, NumTagUnion = 0, NumTagEnum = 0, NumTagClass = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000103 unsigned NumObjCInterfaces = 0, NumObjCQualifiedInterfaces = 0;
104 unsigned NumObjCQualifiedIds = 0;
Douglas Gregor72564e72009-02-26 23:50:07 +0000105 unsigned NumTypeOfTypes = 0, NumTypeOfExprTypes = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +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 Dunbar248e1c02008-09-26 03:23:00 +0000113 else if (isa<BlockPointerType>(T))
114 ++NumBlockPointer;
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000115 else if (isa<LValueReferenceType>(T))
116 ++NumLValueReference;
117 else if (isa<RValueReferenceType>(T))
118 ++NumRValueReference;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000119 else if (isa<MemberPointerType>(T))
120 ++NumMemberPointer;
Chris Lattner6d87fc62007-07-18 05:50:59 +0000121 else if (isa<ComplexType>(T))
122 ++NumComplex;
Reid Spencer5f016e22007-07-11 17:01:13 +0000123 else if (isa<ArrayType>(T))
124 ++NumArray;
Chris Lattner6d87fc62007-07-18 05:50:59 +0000125 else if (isa<VectorType>(T))
126 ++NumVector;
Douglas Gregor72564e72009-02-26 23:50:07 +0000127 else if (isa<FunctionNoProtoType>(T))
Reid Spencer5f016e22007-07-11 17:01:13 +0000128 ++NumFunctionNP;
Douglas Gregor72564e72009-02-26 23:50:07 +0000129 else if (isa<FunctionProtoType>(T))
Reid Spencer5f016e22007-07-11 17:01:13 +0000130 ++NumFunctionP;
131 else if (isa<TypedefType>(T))
132 ++NumTypeName;
133 else if (TagType *TT = dyn_cast<TagType>(T)) {
134 ++NumTagged;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000135 switch (TT->getDecl()->getTagKind()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000136 default: assert(0 && "Unknown tagged type!");
Argyrios Kyrtzidis39ba4ae2008-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;
Reid Spencer5f016e22007-07-11 17:01:13 +0000141 }
Ted Kremeneka526c5c2008-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 Naroff6cc18962008-05-21 15:59:22 +0000148 else if (isa<TypeOfType>(T))
149 ++NumTypeOfTypes;
Douglas Gregor72564e72009-02-26 23:50:07 +0000150 else if (isa<TypeOfExprType>(T))
151 ++NumTypeOfExprTypes;
Steve Naroff3f128ad2007-09-17 14:16:13 +0000152 else {
Chris Lattnerbeb66362007-12-12 06:43:05 +0000153 QualType(T, 0).dump();
Reid Spencer5f016e22007-07-11 17:01:13 +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 Dunbar248e1c02008-09-26 03:23:00 +0000160 fprintf(stderr, " %d block pointer types\n", NumBlockPointer);
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000161 fprintf(stderr, " %d lvalue reference types\n", NumLValueReference);
162 fprintf(stderr, " %d rvalue reference types\n", NumRValueReference);
Sebastian Redlf30208a2009-01-24 21:16:55 +0000163 fprintf(stderr, " %d member pointer types\n", NumMemberPointer);
Chris Lattner6d87fc62007-07-18 05:50:59 +0000164 fprintf(stderr, " %d complex types\n", NumComplex);
Reid Spencer5f016e22007-07-11 17:01:13 +0000165 fprintf(stderr, " %d array types\n", NumArray);
Chris Lattner6d87fc62007-07-18 05:50:59 +0000166 fprintf(stderr, " %d vector types\n", NumVector);
Reid Spencer5f016e22007-07-11 17:01:13 +0000167 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 Kremeneka526c5c2008-01-07 19:49:32 +0000175 fprintf(stderr, " %d interface types\n", NumObjCInterfaces);
Chris Lattnerbeb66362007-12-12 06:43:05 +0000176 fprintf(stderr, " %d protocol qualified interface types\n",
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000177 NumObjCQualifiedInterfaces);
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000178 fprintf(stderr, " %d protocol qualified id types\n",
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000179 NumObjCQualifiedIds);
Steve Naroff6cc18962008-05-21 15:59:22 +0000180 fprintf(stderr, " %d typeof types\n", NumTypeOfTypes);
Douglas Gregor72564e72009-02-26 23:50:07 +0000181 fprintf(stderr, " %d typeof exprs\n", NumTypeOfExprTypes);
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000182
Reid Spencer5f016e22007-07-11 17:01:13 +0000183 fprintf(stderr, "Total bytes = %d\n", int(NumBuiltin*sizeof(BuiltinType)+
184 NumPointer*sizeof(PointerType)+NumArray*sizeof(ArrayType)+
Chris Lattner6d87fc62007-07-18 05:50:59 +0000185 NumComplex*sizeof(ComplexType)+NumVector*sizeof(VectorType)+
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000186 NumLValueReference*sizeof(LValueReferenceType)+
187 NumRValueReference*sizeof(RValueReferenceType)+
Sebastian Redlf30208a2009-01-24 21:16:55 +0000188 NumMemberPointer*sizeof(MemberPointerType)+
Douglas Gregor72564e72009-02-26 23:50:07 +0000189 NumFunctionP*sizeof(FunctionProtoType)+
190 NumFunctionNP*sizeof(FunctionNoProtoType)+
Steve Naroff6cc18962008-05-21 15:59:22 +0000191 NumTypeName*sizeof(TypedefType)+NumTagged*sizeof(TagType)+
Douglas Gregor72564e72009-02-26 23:50:07 +0000192 NumTypeOfTypes*sizeof(TypeOfType)+NumTypeOfExprTypes*sizeof(TypeOfExprType)));
Reid Spencer5f016e22007-07-11 17:01:13 +0000193}
194
195
196void ASTContext::InitBuiltinType(QualType &R, BuiltinType::Kind K) {
Steve Narofff83820b2009-01-27 22:08:43 +0000197 Types.push_back((R = QualType(new (*this,8) BuiltinType(K),0)).getTypePtr());
Reid Spencer5f016e22007-07-11 17:01:13 +0000198}
199
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattner98be4942008-03-05 18:54:05 +0000209 if (Target.isCharSigned())
Reid Spencer5f016e22007-07-11 17:01:13 +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);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000231
Chris Lattner3a250322009-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());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000236
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000237 // Placeholder type for functions.
Douglas Gregor898574e2008-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 Gregor8e9bebd2008-10-21 16:13:35 +0000246
Reid Spencer5f016e22007-07-11 17:01:13 +0000247 // C99 6.2.5p11.
248 FloatComplexTy = getComplexType(FloatTy);
249 DoubleComplexTy = getComplexType(DoubleTy);
250 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000251
Steve Naroff7e219e42007-10-15 14:41:52 +0000252 BuiltinVaListType = QualType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000253 ObjCIdType = QualType();
Steve Naroff7e219e42007-10-15 14:41:52 +0000254 IdStructType = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000255 ObjCClassType = QualType();
Anders Carlsson8baaca52007-10-31 02:53:19 +0000256 ClassStructType = 0;
257
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000258 ObjCConstantStringType = QualType();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000259
260 // void * type
261 VoidPtrTy = getPointerType(VoidTy);
Reid Spencer5f016e22007-07-11 17:01:13 +0000262}
263
Chris Lattner464175b2007-07-18 17:52:12 +0000264//===----------------------------------------------------------------------===//
265// Type Sizing and Analysis
266//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000267
Chris Lattnerb7cfe882008-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 Lattneraf707ab2009-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 Dunbarb7d08442009-02-17 22:16:19 +0000284unsigned ASTContext::getDeclAlignInBytes(const Decl *D) {
Eli Friedmandcdafb62009-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 Lattneraf707ab2009-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 Friedmandcdafb62009-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 Lattneraf707ab2009-01-24 21:53:27 +0000299 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000300
301 return Align / Target.getCharWidth();
Chris Lattneraf707ab2009-01-24 21:53:27 +0000302}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000303
Chris Lattnera7674d82007-07-13 22:13:22 +0000304/// getTypeSize - Return the size of the specified type, in bits. This method
305/// does not work on incomplete types.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000306std::pair<uint64_t, unsigned>
Daniel Dunbar1d751182008-11-08 05:48:37 +0000307ASTContext::getTypeInfo(const Type *T) {
Chris Lattnerf52ab252008-04-06 22:59:24 +0000308 T = getCanonicalType(T);
Mike Stump5e301002009-02-27 18:32:39 +0000309 uint64_t Width=0;
310 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000311 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-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 Lattner692233e2007-07-13 22:27:08 +0000320 case Type::FunctionNoProto:
321 case Type::FunctionProto:
Douglas Gregor72564e72009-02-26 23:50:07 +0000322 case Type::IncompleteArray:
Chris Lattnerb1c2df92007-07-20 18:13:33 +0000323 assert(0 && "Incomplete types have no size!");
Steve Narofffb22d962007-08-30 01:06:46 +0000324 case Type::VariableArray:
325 assert(0 && "VLAs not implemented yet!");
326 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000327 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Steve Narofffb22d962007-08-30 01:06:46 +0000328
Chris Lattner98be4942008-03-05 18:54:05 +0000329 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000330 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000331 Align = EltInfo.second;
332 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000333 }
Nate Begeman213541a2008-04-18 23:10:10 +0000334 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000335 case Type::Vector: {
336 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000337 getTypeInfo(cast<VectorType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000338 Width = EltInfo.first*cast<VectorType>(T)->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000339 Align = Width;
Nate Begeman6fe7c8a2009-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 Lattner030d8842007-07-19 22:06:24 +0000344 break;
345 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000346
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000347 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000348 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000349 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000350 case BuiltinType::Void:
351 assert(0 && "Incomplete types have no size!");
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000352 case BuiltinType::Bool:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000353 Width = Target.getBoolWidth();
354 Align = Target.getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000355 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000356 case BuiltinType::Char_S:
357 case BuiltinType::Char_U:
358 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000359 case BuiltinType::SChar:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000360 Width = Target.getCharWidth();
361 Align = Target.getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000362 break;
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000363 case BuiltinType::WChar:
364 Width = Target.getWCharWidth();
365 Align = Target.getWCharAlign();
366 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000367 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000368 case BuiltinType::Short:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000369 Width = Target.getShortWidth();
370 Align = Target.getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000371 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000372 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000373 case BuiltinType::Int:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000374 Width = Target.getIntWidth();
375 Align = Target.getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000376 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000377 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000378 case BuiltinType::Long:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000379 Width = Target.getLongWidth();
380 Align = Target.getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000381 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000382 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000383 case BuiltinType::LongLong:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000384 Width = Target.getLongLongWidth();
385 Align = Target.getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000386 break;
387 case BuiltinType::Float:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000388 Width = Target.getFloatWidth();
389 Align = Target.getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000390 break;
391 case BuiltinType::Double:
Chris Lattner5426bf62008-04-07 07:01:58 +0000392 Width = Target.getDoubleWidth();
393 Align = Target.getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000394 break;
395 case BuiltinType::LongDouble:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000396 Width = Target.getLongDoubleWidth();
397 Align = Target.getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000398 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000399 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000400 break;
Eli Friedmanf98aba32009-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 Lattner736166b2009-02-15 21:20:13 +0000405 Width = std::max(llvm::NextPowerOf2(Width - 1), (uint64_t)8);
Eli Friedmanf98aba32009-02-13 02:31:07 +0000406 Align = Width;
407 break;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000408 case Type::ExtQual:
Chris Lattner98be4942008-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 Jahanianf11284a2009-02-17 18:27:45 +0000411 return getTypeInfo(QualType(cast<ExtQualType>(T)->getBaseType(), 0));
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000412 case Type::ObjCQualifiedId:
Eli Friedman4bdf0872009-02-22 04:02:33 +0000413 case Type::ObjCQualifiedClass:
Douglas Gregor72564e72009-02-26 23:50:07 +0000414 case Type::ObjCQualifiedInterface:
Chris Lattner5426bf62008-04-07 07:01:58 +0000415 Width = Target.getPointerWidth(0);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000416 Align = Target.getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000417 break;
Steve Naroff485eeff2008-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 Lattnerf72a4432008-03-08 08:34:58 +0000424 case Type::Pointer: {
425 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner5426bf62008-04-07 07:01:58 +0000426 Width = Target.getPointerWidth(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000427 Align = Target.getPointerAlign(AS);
428 break;
429 }
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000430 case Type::LValueReference:
431 case Type::RValueReference:
Chris Lattner7ab2ed82007-07-13 22:16:13 +0000432 // "When applied to a reference or a reference type, the result is the size
Chris Lattner5d2a6302007-07-18 18:26:58 +0000433 // of the referenced type." C++98 5.3.3p2: expr.sizeof.
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000434 // FIXME: This is wrong for struct layout: a reference in a struct has
435 // pointer size.
Chris Lattnerbdcd6372008-04-02 17:35:06 +0000436 return getTypeInfo(cast<ReferenceType>(T)->getPointeeType());
Sebastian Redlf30208a2009-01-24 21:16:55 +0000437 case Type::MemberPointer: {
Sebastian Redl8edef7c2009-01-24 23:29:36 +0000438 // FIXME: This is not only platform- but also ABI-dependent. We follow
Sebastian Redlf30208a2009-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 Redl8edef7c2009-01-24 23:29:36 +0000441 // other compilers too, we need to delegate this completely to TargetInfo
442 // or some ABI abstraction layer.
Sebastian Redlf30208a2009-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 Lattner5d2a6302007-07-18 18:26:58 +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 Lattner98be4942008-03-05 18:54:05 +0000455 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000456 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000457 Align = EltInfo.second;
458 break;
459 }
Devang Patel44a3dde2008-06-04 21:54:36 +0000460 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000461 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000462 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
463 Width = Layout.getSize();
464 Align = Layout.getAlignment();
465 break;
466 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000467 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000468 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000469 const TagType *TT = cast<TagType>(T);
470
471 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner8389eab2008-08-09 21:35:13 +0000472 Width = 1;
473 Align = 1;
474 break;
475 }
476
Daniel Dunbar1d751182008-11-08 05:48:37 +0000477 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000478 return getTypeInfo(ET->getDecl()->getIntegerType());
479
Daniel Dunbar1d751182008-11-08 05:48:37 +0000480 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000481 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
482 Width = Layout.getSize();
483 Align = Layout.getAlignment();
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000484 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000485 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000486
487 case Type::TemplateSpecialization:
488 assert(false && "Dependent types have no size");
489 break;
Chris Lattner71763312008-04-06 22:05:18 +0000490 }
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000491
Chris Lattner464175b2007-07-18 17:52:12 +0000492 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000493 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +0000494}
495
Chris Lattner34ebde42009-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 Dunbare00d5c02009-02-18 19:59:32 +0000504 if (T->isSpecificBuiltinType(BuiltinType::Double))
505 return std::max(ABIAlign, 64U);
Chris Lattner34ebde42009-01-27 18:08:34 +0000506
507 return ABIAlign;
508}
509
510
Devang Patel8b277042008-06-04 21:22:16 +0000511/// LayoutField - Field layout.
512void ASTRecordLayout::LayoutField(const FieldDecl *FD, unsigned FieldNo,
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000513 bool IsUnion, unsigned StructPacking,
Devang Patel8b277042008-06-04 21:22:16 +0000514 ASTContext &Context) {
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000515 unsigned FieldPacking = StructPacking;
Devang Patel8b277042008-06-04 21:22:16 +0000516 uint64_t FieldOffset = IsUnion ? 0 : Size;
517 uint64_t FieldSize;
518 unsigned FieldAlign;
Daniel Dunbar3b0db902008-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 Patel8b277042008-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 Dunbar32442bb2008-08-13 23:47:13 +0000528 FieldSize =
529 BitWidthExpr->getIntegerConstantExprValue(Context).getZExtValue();
Devang Patel8b277042008-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 Dunbar3b0db902008-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 Patel8b277042008-06-04 21:22:16 +0000540 FieldAlign = FieldInfo.second;
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000541 if (FieldPacking)
542 FieldAlign = std::min(FieldAlign, FieldPacking);
Devang Patel8b277042008-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 Lattner8389eab2008-08-09 21:35:13 +0000555 if (FD->getType()->isIncompleteArrayType()) {
556 // This is a flexible array member; we can't directly
Devang Patel8b277042008-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 Lattnerc63a1f22008-08-04 07:31:14 +0000561 const ArrayType* ATy = Context.getAsArrayType(FD->getType());
Devang Patel8b277042008-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 Dunbar3b0db902008-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 Patel8b277042008-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 Jahanian88e469c2009-03-05 20:08:48 +0000600void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
Chris Lattnerf1690852009-03-31 08:48:01 +0000601 llvm::SmallVectorImpl<FieldDecl*> &Fields) const {
Fariborz Jahaniana769c002008-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 Lattnerf1690852009-03-31 08:48:01 +0000607 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000608 if (!IVDecl->isInvalidDecl())
609 Fields.push_back(cast<FieldDecl>(IVDecl));
610 }
Fariborz Jahanianaf3e7222009-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 Lattnerf1690852009-03-31 08:48:01 +0000614 if (ObjCIvarDecl *IV = (*I)->getPropertyIvarDecl())
Fariborz Jahanianaf3e7222009-03-31 00:06:29 +0000615 Fields.push_back(cast<FieldDecl>(IV));
616 }
Fariborz Jahaniana769c002008-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 Lattnerf1690852009-03-31 08:48:01 +0000622const RecordDecl *ASTContext::addRecordToClass(const ObjCInterfaceDecl *D) {
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000623 const RecordDecl *&RD = ASTRecordForInterface[D];
624 if (RD)
625 return RD;
Chris Lattnerf1690852009-03-31 08:48:01 +0000626
627 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000628 CollectObjCIvars(D, RecFields);
629 RecordDecl *NewRD = RecordDecl::Create(*this, TagDecl::TK_struct, 0,
630 D->getLocation(),
631 D->getIdentifier());
632 /// FIXME! Can do collection of ivars and adding to the record while
633 /// doing it.
634 for (unsigned int i = 0; i != RecFields.size(); i++) {
Chris Lattnerf1690852009-03-31 08:48:01 +0000635 NewRD->addDecl(FieldDecl::Create(*this, NewRD,
636 RecFields[i]->getLocation(),
637 RecFields[i]->getIdentifier(),
638 RecFields[i]->getType(),
639 RecFields[i]->getBitWidth(), false));
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000640 }
Chris Lattnerf1690852009-03-31 08:48:01 +0000641
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000642 NewRD->completeDefinition(*this);
643 RD = NewRD;
644 return RD;
645}
Devang Patel44a3dde2008-06-04 21:54:36 +0000646
Fariborz Jahanianefc4c4b2008-12-18 17:29:46 +0000647/// setFieldDecl - maps a field for the given Ivar reference node.
648//
649void ASTContext::setFieldDecl(const ObjCInterfaceDecl *OI,
650 const ObjCIvarDecl *Ivar,
651 const ObjCIvarRefExpr *MRef) {
Chris Lattnerda046392009-03-31 08:31:13 +0000652 ASTFieldForIvarRef[MRef] = OI->lookupFieldDeclForIvar(*this, Ivar);
Fariborz Jahanianefc4c4b2008-12-18 17:29:46 +0000653}
654
Chris Lattner61710852008-10-05 17:34:18 +0000655/// getASTObjcInterfaceLayout - Get or compute information about the layout of
656/// the specified Objective C, which indicates its size and ivar
Devang Patel44a3dde2008-06-04 21:54:36 +0000657/// position information.
658const ASTRecordLayout &
659ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
660 // Look up this layout, if already laid out, return what we have.
661 const ASTRecordLayout *&Entry = ASTObjCInterfaces[D];
662 if (Entry) return *Entry;
663
664 // Allocate and assign into ASTRecordLayouts here. The "Entry" reference can
665 // be invalidated (dangle) if the ASTRecordLayouts hashtable is inserted into.
Devang Patel6a5a34c2008-06-06 02:14:01 +0000666 ASTRecordLayout *NewEntry = NULL;
667 unsigned FieldCount = D->ivar_size();
668 if (ObjCInterfaceDecl *SD = D->getSuperClass()) {
669 FieldCount++;
670 const ASTRecordLayout &SL = getASTObjCInterfaceLayout(SD);
671 unsigned Alignment = SL.getAlignment();
672 uint64_t Size = SL.getSize();
673 NewEntry = new ASTRecordLayout(Size, Alignment);
674 NewEntry->InitializeLayout(FieldCount);
Chris Lattner61710852008-10-05 17:34:18 +0000675 // Super class is at the beginning of the layout.
676 NewEntry->SetFieldOffset(0, 0);
Devang Patel6a5a34c2008-06-06 02:14:01 +0000677 } else {
678 NewEntry = new ASTRecordLayout();
679 NewEntry->InitializeLayout(FieldCount);
680 }
Devang Patel44a3dde2008-06-04 21:54:36 +0000681 Entry = NewEntry;
682
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000683 unsigned StructPacking = 0;
684 if (const PackedAttr *PA = D->getAttr<PackedAttr>())
685 StructPacking = PA->getAlignment();
Devang Patel44a3dde2008-06-04 21:54:36 +0000686
687 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>())
688 NewEntry->SetAlignment(std::max(NewEntry->getAlignment(),
689 AA->getAlignment()));
690
691 // Layout each ivar sequentially.
692 unsigned i = 0;
693 for (ObjCInterfaceDecl::ivar_iterator IVI = D->ivar_begin(),
694 IVE = D->ivar_end(); IVI != IVE; ++IVI) {
695 const ObjCIvarDecl* Ivar = (*IVI);
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000696 NewEntry->LayoutField(Ivar, i++, false, StructPacking, *this);
Devang Patel44a3dde2008-06-04 21:54:36 +0000697 }
698
699 // Finally, round the size of the total struct up to the alignment of the
700 // struct itself.
701 NewEntry->FinalizeLayout();
702 return *NewEntry;
703}
704
Devang Patel88a981b2007-11-01 19:11:01 +0000705/// getASTRecordLayout - Get or compute information about the layout of the
Chris Lattner464175b2007-07-18 17:52:12 +0000706/// specified record (struct/union/class), which indicates its size and field
707/// position information.
Chris Lattner98be4942008-03-05 18:54:05 +0000708const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +0000709 D = D->getDefinition(*this);
710 assert(D && "Cannot get layout of forward declarations!");
Eli Friedman4bd998b2008-05-30 09:31:38 +0000711
Chris Lattner464175b2007-07-18 17:52:12 +0000712 // Look up this layout, if already laid out, return what we have.
Devang Patel88a981b2007-11-01 19:11:01 +0000713 const ASTRecordLayout *&Entry = ASTRecordLayouts[D];
Chris Lattner464175b2007-07-18 17:52:12 +0000714 if (Entry) return *Entry;
Eli Friedman4bd998b2008-05-30 09:31:38 +0000715
Devang Patel88a981b2007-11-01 19:11:01 +0000716 // Allocate and assign into ASTRecordLayouts here. The "Entry" reference can
717 // be invalidated (dangle) if the ASTRecordLayouts hashtable is inserted into.
718 ASTRecordLayout *NewEntry = new ASTRecordLayout();
Chris Lattner464175b2007-07-18 17:52:12 +0000719 Entry = NewEntry;
Eli Friedman4bd998b2008-05-30 09:31:38 +0000720
Douglas Gregore267ff32008-12-11 20:41:00 +0000721 // FIXME: Avoid linear walk through the fields, if possible.
Douglas Gregor44b43212008-12-11 16:49:14 +0000722 NewEntry->InitializeLayout(std::distance(D->field_begin(), D->field_end()));
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000723 bool IsUnion = D->isUnion();
Chris Lattner464175b2007-07-18 17:52:12 +0000724
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000725 unsigned StructPacking = 0;
726 if (const PackedAttr *PA = D->getAttr<PackedAttr>())
727 StructPacking = PA->getAlignment();
728
Eli Friedman4bd998b2008-05-30 09:31:38 +0000729 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>())
Devang Patel8b277042008-06-04 21:22:16 +0000730 NewEntry->SetAlignment(std::max(NewEntry->getAlignment(),
731 AA->getAlignment()));
Anders Carlsson8af226a2008-02-18 07:13:09 +0000732
Eli Friedman4bd998b2008-05-30 09:31:38 +0000733 // Layout each field, for now, just sequentially, respecting alignment. In
734 // the future, this will need to be tweakable by targets.
Douglas Gregor44b43212008-12-11 16:49:14 +0000735 unsigned FieldIdx = 0;
Douglas Gregorf8d49f62009-01-09 17:18:27 +0000736 for (RecordDecl::field_iterator Field = D->field_begin(),
737 FieldEnd = D->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +0000738 Field != FieldEnd; (void)++Field, ++FieldIdx)
739 NewEntry->LayoutField(*Field, FieldIdx, IsUnion, StructPacking, *this);
Eli Friedman4bd998b2008-05-30 09:31:38 +0000740
741 // Finally, round the size of the total struct up to the alignment of the
742 // struct itself.
Devang Patel8b277042008-06-04 21:22:16 +0000743 NewEntry->FinalizeLayout();
Chris Lattner5d2a6302007-07-18 18:26:58 +0000744 return *NewEntry;
Chris Lattner464175b2007-07-18 17:52:12 +0000745}
746
Chris Lattnera7674d82007-07-13 22:13:22 +0000747//===----------------------------------------------------------------------===//
748// Type creation/memoization methods
749//===----------------------------------------------------------------------===//
750
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000751QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerf52ab252008-04-06 22:59:24 +0000752 QualType CanT = getCanonicalType(T);
753 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +0000754 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +0000755
756 // If we are composing extended qualifiers together, merge together into one
757 // ExtQualType node.
758 unsigned CVRQuals = T.getCVRQualifiers();
759 QualType::GCAttrTypes GCAttr = QualType::GCNone;
760 Type *TypeNode = T.getTypePtr();
Chris Lattnerf46699c2008-02-20 20:55:12 +0000761
Chris Lattnerb7d25532009-02-18 22:53:11 +0000762 if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
763 // If this type already has an address space specified, it cannot get
764 // another one.
765 assert(EQT->getAddressSpace() == 0 &&
766 "Type cannot be in multiple addr spaces!");
767 GCAttr = EQT->getObjCGCAttr();
768 TypeNode = EQT->getBaseType();
769 }
Chris Lattnerf46699c2008-02-20 20:55:12 +0000770
Chris Lattnerb7d25532009-02-18 22:53:11 +0000771 // Check if we've already instantiated this type.
Christopher Lambebb97e92008-02-04 02:31:56 +0000772 llvm::FoldingSetNodeID ID;
Chris Lattnerb7d25532009-02-18 22:53:11 +0000773 ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
Christopher Lambebb97e92008-02-04 02:31:56 +0000774 void *InsertPos = 0;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000775 if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattnerb7d25532009-02-18 22:53:11 +0000776 return QualType(EXTQy, CVRQuals);
777
Christopher Lambebb97e92008-02-04 02:31:56 +0000778 // If the base type isn't canonical, this won't be a canonical type either,
779 // so fill in the canonical type field.
780 QualType Canonical;
Chris Lattnerb7d25532009-02-18 22:53:11 +0000781 if (!TypeNode->isCanonical()) {
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000782 Canonical = getAddrSpaceQualType(CanT, AddressSpace);
Christopher Lambebb97e92008-02-04 02:31:56 +0000783
Chris Lattnerb7d25532009-02-18 22:53:11 +0000784 // Update InsertPos, the previous call could have invalidated it.
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000785 ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +0000786 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Christopher Lambebb97e92008-02-04 02:31:56 +0000787 }
Chris Lattnerb7d25532009-02-18 22:53:11 +0000788 ExtQualType *New =
789 new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000790 ExtQualTypes.InsertNode(New, InsertPos);
Christopher Lambebb97e92008-02-04 02:31:56 +0000791 Types.push_back(New);
Chris Lattnerb7d25532009-02-18 22:53:11 +0000792 return QualType(New, CVRQuals);
Christopher Lambebb97e92008-02-04 02:31:56 +0000793}
794
Chris Lattnerb7d25532009-02-18 22:53:11 +0000795QualType ASTContext::getObjCGCQualType(QualType T,
796 QualType::GCAttrTypes GCAttr) {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000797 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +0000798 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000799 return T;
800
Chris Lattnerb7d25532009-02-18 22:53:11 +0000801 // If we are composing extended qualifiers together, merge together into one
802 // ExtQualType node.
803 unsigned CVRQuals = T.getCVRQualifiers();
804 Type *TypeNode = T.getTypePtr();
805 unsigned AddressSpace = 0;
806
807 if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
808 // If this type already has an address space specified, it cannot get
809 // another one.
810 assert(EQT->getObjCGCAttr() == QualType::GCNone &&
811 "Type cannot be in multiple addr spaces!");
812 AddressSpace = EQT->getAddressSpace();
813 TypeNode = EQT->getBaseType();
814 }
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000815
816 // Check if we've already instantiated an gc qual'd type of this type.
817 llvm::FoldingSetNodeID ID;
Chris Lattnerb7d25532009-02-18 22:53:11 +0000818 ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000819 void *InsertPos = 0;
820 if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattnerb7d25532009-02-18 22:53:11 +0000821 return QualType(EXTQy, CVRQuals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000822
823 // If the base type isn't canonical, this won't be a canonical type either,
824 // so fill in the canonical type field.
Eli Friedman5a61f0e2009-02-27 23:04:43 +0000825 // FIXME: Isn't this also not canonical if the base type is a array
826 // or pointer type? I can't find any documentation for objc_gc, though...
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000827 QualType Canonical;
828 if (!T->isCanonical()) {
Chris Lattnerb7d25532009-02-18 22:53:11 +0000829 Canonical = getObjCGCQualType(CanT, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000830
Chris Lattnerb7d25532009-02-18 22:53:11 +0000831 // Update InsertPos, the previous call could have invalidated it.
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000832 ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
833 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
834 }
Chris Lattnerb7d25532009-02-18 22:53:11 +0000835 ExtQualType *New =
836 new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000837 ExtQualTypes.InsertNode(New, InsertPos);
838 Types.push_back(New);
Chris Lattnerb7d25532009-02-18 22:53:11 +0000839 return QualType(New, CVRQuals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000840}
Chris Lattnera7674d82007-07-13 22:13:22 +0000841
Reid Spencer5f016e22007-07-11 17:01:13 +0000842/// getComplexType - Return the uniqued reference to the type for a complex
843/// number with the specified element type.
844QualType ASTContext::getComplexType(QualType T) {
845 // Unique pointers, to guarantee there is only one pointer of a particular
846 // structure.
847 llvm::FoldingSetNodeID ID;
848 ComplexType::Profile(ID, T);
849
850 void *InsertPos = 0;
851 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
852 return QualType(CT, 0);
853
854 // If the pointee type isn't canonical, this won't be a canonical type either,
855 // so fill in the canonical type field.
856 QualType Canonical;
857 if (!T->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +0000858 Canonical = getComplexType(getCanonicalType(T));
Reid Spencer5f016e22007-07-11 17:01:13 +0000859
860 // Get the new insert position for the node we care about.
861 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +0000862 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +0000863 }
Steve Narofff83820b2009-01-27 22:08:43 +0000864 ComplexType *New = new (*this,8) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +0000865 Types.push_back(New);
866 ComplexTypes.InsertNode(New, InsertPos);
867 return QualType(New, 0);
868}
869
Eli Friedmanf98aba32009-02-13 02:31:07 +0000870QualType ASTContext::getFixedWidthIntType(unsigned Width, bool Signed) {
871 llvm::DenseMap<unsigned, FixedWidthIntType*> &Map = Signed ?
872 SignedFixedWidthIntTypes : UnsignedFixedWidthIntTypes;
873 FixedWidthIntType *&Entry = Map[Width];
874 if (!Entry)
875 Entry = new FixedWidthIntType(Width, Signed);
876 return QualType(Entry, 0);
877}
Reid Spencer5f016e22007-07-11 17:01:13 +0000878
879/// getPointerType - Return the uniqued reference to the type for a pointer to
880/// the specified type.
881QualType ASTContext::getPointerType(QualType T) {
882 // Unique pointers, to guarantee there is only one pointer of a particular
883 // structure.
884 llvm::FoldingSetNodeID ID;
885 PointerType::Profile(ID, T);
886
887 void *InsertPos = 0;
888 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
889 return QualType(PT, 0);
890
891 // If the pointee type isn't canonical, this won't be a canonical type either,
892 // so fill in the canonical type field.
893 QualType Canonical;
894 if (!T->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +0000895 Canonical = getPointerType(getCanonicalType(T));
Reid Spencer5f016e22007-07-11 17:01:13 +0000896
897 // Get the new insert position for the node we care about.
898 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +0000899 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +0000900 }
Steve Narofff83820b2009-01-27 22:08:43 +0000901 PointerType *New = new (*this,8) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +0000902 Types.push_back(New);
903 PointerTypes.InsertNode(New, InsertPos);
904 return QualType(New, 0);
905}
906
Steve Naroff5618bd42008-08-27 16:04:49 +0000907/// getBlockPointerType - Return the uniqued reference to the type for
908/// a pointer to the specified block.
909QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff296e8d52008-08-28 19:20:44 +0000910 assert(T->isFunctionType() && "block of function types only");
911 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +0000912 // structure.
913 llvm::FoldingSetNodeID ID;
914 BlockPointerType::Profile(ID, T);
915
916 void *InsertPos = 0;
917 if (BlockPointerType *PT =
918 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
919 return QualType(PT, 0);
920
Steve Naroff296e8d52008-08-28 19:20:44 +0000921 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +0000922 // type either so fill in the canonical type field.
923 QualType Canonical;
924 if (!T->isCanonical()) {
925 Canonical = getBlockPointerType(getCanonicalType(T));
926
927 // Get the new insert position for the node we care about.
928 BlockPointerType *NewIP =
929 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +0000930 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +0000931 }
Steve Narofff83820b2009-01-27 22:08:43 +0000932 BlockPointerType *New = new (*this,8) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +0000933 Types.push_back(New);
934 BlockPointerTypes.InsertNode(New, InsertPos);
935 return QualType(New, 0);
936}
937
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000938/// getLValueReferenceType - Return the uniqued reference to the type for an
939/// lvalue reference to the specified type.
940QualType ASTContext::getLValueReferenceType(QualType T) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000941 // Unique pointers, to guarantee there is only one pointer of a particular
942 // structure.
943 llvm::FoldingSetNodeID ID;
944 ReferenceType::Profile(ID, T);
945
946 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000947 if (LValueReferenceType *RT =
948 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +0000949 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000950
Reid Spencer5f016e22007-07-11 17:01:13 +0000951 // If the referencee type isn't canonical, this won't be a canonical type
952 // either, so fill in the canonical type field.
953 QualType Canonical;
954 if (!T->isCanonical()) {
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000955 Canonical = getLValueReferenceType(getCanonicalType(T));
956
Reid Spencer5f016e22007-07-11 17:01:13 +0000957 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000958 LValueReferenceType *NewIP =
959 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +0000960 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +0000961 }
962
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000963 LValueReferenceType *New = new (*this,8) LValueReferenceType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +0000964 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000965 LValueReferenceTypes.InsertNode(New, InsertPos);
966 return QualType(New, 0);
967}
968
969/// getRValueReferenceType - Return the uniqued reference to the type for an
970/// rvalue reference to the specified type.
971QualType ASTContext::getRValueReferenceType(QualType T) {
972 // Unique pointers, to guarantee there is only one pointer of a particular
973 // structure.
974 llvm::FoldingSetNodeID ID;
975 ReferenceType::Profile(ID, T);
976
977 void *InsertPos = 0;
978 if (RValueReferenceType *RT =
979 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
980 return QualType(RT, 0);
981
982 // If the referencee type isn't canonical, this won't be a canonical type
983 // either, so fill in the canonical type field.
984 QualType Canonical;
985 if (!T->isCanonical()) {
986 Canonical = getRValueReferenceType(getCanonicalType(T));
987
988 // Get the new insert position for the node we care about.
989 RValueReferenceType *NewIP =
990 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
991 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
992 }
993
994 RValueReferenceType *New = new (*this,8) RValueReferenceType(T, Canonical);
995 Types.push_back(New);
996 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +0000997 return QualType(New, 0);
998}
999
Sebastian Redlf30208a2009-01-24 21:16:55 +00001000/// getMemberPointerType - Return the uniqued reference to the type for a
1001/// member pointer to the specified type, in the specified class.
1002QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls)
1003{
1004 // Unique pointers, to guarantee there is only one pointer of a particular
1005 // structure.
1006 llvm::FoldingSetNodeID ID;
1007 MemberPointerType::Profile(ID, T, Cls);
1008
1009 void *InsertPos = 0;
1010 if (MemberPointerType *PT =
1011 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1012 return QualType(PT, 0);
1013
1014 // If the pointee or class type isn't canonical, this won't be a canonical
1015 // type either, so fill in the canonical type field.
1016 QualType Canonical;
1017 if (!T->isCanonical()) {
1018 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1019
1020 // Get the new insert position for the node we care about.
1021 MemberPointerType *NewIP =
1022 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1023 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1024 }
Steve Narofff83820b2009-01-27 22:08:43 +00001025 MemberPointerType *New = new (*this,8) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001026 Types.push_back(New);
1027 MemberPointerTypes.InsertNode(New, InsertPos);
1028 return QualType(New, 0);
1029}
1030
Steve Narofffb22d962007-08-30 01:06:46 +00001031/// getConstantArrayType - Return the unique reference to the type for an
1032/// array of the specified element type.
1033QualType ASTContext::getConstantArrayType(QualType EltTy,
Steve Naroffc9406122007-08-30 18:10:14 +00001034 const llvm::APInt &ArySize,
1035 ArrayType::ArraySizeModifier ASM,
1036 unsigned EltTypeQuals) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001037 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001038 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001039
1040 void *InsertPos = 0;
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001041 if (ConstantArrayType *ATP =
1042 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001043 return QualType(ATP, 0);
1044
1045 // If the element type isn't canonical, this won't be a canonical type either,
1046 // so fill in the canonical type field.
1047 QualType Canonical;
1048 if (!EltTy->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001049 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroffc9406122007-08-30 18:10:14 +00001050 ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001051 // Get the new insert position for the node we care about.
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001052 ConstantArrayType *NewIP =
1053 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001054 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001055 }
1056
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001057 ConstantArrayType *New =
Steve Narofff83820b2009-01-27 22:08:43 +00001058 new(*this,8)ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001059 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001060 Types.push_back(New);
1061 return QualType(New, 0);
1062}
1063
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001064/// getVariableArrayType - Returns a non-unique reference to the type for a
1065/// variable array of the specified element type.
Steve Naroffc9406122007-08-30 18:10:14 +00001066QualType ASTContext::getVariableArrayType(QualType EltTy, Expr *NumElts,
1067 ArrayType::ArraySizeModifier ASM,
1068 unsigned EltTypeQuals) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001069 // Since we don't unique expressions, it isn't possible to unique VLA's
1070 // that have an expression provided for their size.
1071
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001072 VariableArrayType *New =
Steve Narofff83820b2009-01-27 22:08:43 +00001073 new(*this,8)VariableArrayType(EltTy,QualType(), NumElts, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001074
1075 VariableArrayTypes.push_back(New);
1076 Types.push_back(New);
1077 return QualType(New, 0);
1078}
1079
Douglas Gregor898574e2008-12-05 23:32:09 +00001080/// getDependentSizedArrayType - Returns a non-unique reference to
1081/// the type for a dependently-sized array of the specified element
1082/// type. FIXME: We will need these to be uniqued, or at least
1083/// comparable, at some point.
1084QualType ASTContext::getDependentSizedArrayType(QualType EltTy, Expr *NumElts,
1085 ArrayType::ArraySizeModifier ASM,
1086 unsigned EltTypeQuals) {
1087 assert((NumElts->isTypeDependent() || NumElts->isValueDependent()) &&
1088 "Size must be type- or value-dependent!");
1089
1090 // Since we don't unique expressions, it isn't possible to unique
1091 // dependently-sized array types.
1092
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001093 DependentSizedArrayType *New =
Steve Narofff83820b2009-01-27 22:08:43 +00001094 new (*this,8) DependentSizedArrayType(EltTy, QualType(), NumElts,
1095 ASM, EltTypeQuals);
Douglas Gregor898574e2008-12-05 23:32:09 +00001096
1097 DependentSizedArrayTypes.push_back(New);
1098 Types.push_back(New);
1099 return QualType(New, 0);
1100}
1101
Eli Friedmanc5773c42008-02-15 18:16:39 +00001102QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1103 ArrayType::ArraySizeModifier ASM,
1104 unsigned EltTypeQuals) {
1105 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001106 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001107
1108 void *InsertPos = 0;
1109 if (IncompleteArrayType *ATP =
1110 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1111 return QualType(ATP, 0);
1112
1113 // If the element type isn't canonical, this won't be a canonical type
1114 // either, so fill in the canonical type field.
1115 QualType Canonical;
1116
1117 if (!EltTy->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001118 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001119 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001120
1121 // Get the new insert position for the node we care about.
1122 IncompleteArrayType *NewIP =
1123 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001124 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001125 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001126
Steve Narofff83820b2009-01-27 22:08:43 +00001127 IncompleteArrayType *New = new (*this,8) IncompleteArrayType(EltTy, Canonical,
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001128 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001129
1130 IncompleteArrayTypes.InsertNode(New, InsertPos);
1131 Types.push_back(New);
1132 return QualType(New, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001133}
1134
Steve Naroff73322922007-07-18 18:00:27 +00001135/// getVectorType - Return the unique reference to a vector type of
1136/// the specified element type and size. VectorType must be a built-in type.
1137QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001138 BuiltinType *baseType;
1139
Chris Lattnerf52ab252008-04-06 22:59:24 +00001140 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff73322922007-07-18 18:00:27 +00001141 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Reid Spencer5f016e22007-07-11 17:01:13 +00001142
1143 // Check if we've already instantiated a vector of this type.
1144 llvm::FoldingSetNodeID ID;
Steve Naroff73322922007-07-18 18:00:27 +00001145 VectorType::Profile(ID, vecType, NumElts, Type::Vector);
Reid Spencer5f016e22007-07-11 17:01:13 +00001146 void *InsertPos = 0;
1147 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1148 return QualType(VTP, 0);
1149
1150 // If the element type isn't canonical, this won't be a canonical type either,
1151 // so fill in the canonical type field.
1152 QualType Canonical;
1153 if (!vecType->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001154 Canonical = getVectorType(getCanonicalType(vecType), NumElts);
Reid Spencer5f016e22007-07-11 17:01:13 +00001155
1156 // Get the new insert position for the node we care about.
1157 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001158 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001159 }
Steve Narofff83820b2009-01-27 22:08:43 +00001160 VectorType *New = new (*this,8) VectorType(vecType, NumElts, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001161 VectorTypes.InsertNode(New, InsertPos);
1162 Types.push_back(New);
1163 return QualType(New, 0);
1164}
1165
Nate Begeman213541a2008-04-18 23:10:10 +00001166/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001167/// the specified element type and size. VectorType must be a built-in type.
Nate Begeman213541a2008-04-18 23:10:10 +00001168QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff73322922007-07-18 18:00:27 +00001169 BuiltinType *baseType;
1170
Chris Lattnerf52ab252008-04-06 22:59:24 +00001171 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begeman213541a2008-04-18 23:10:10 +00001172 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Steve Naroff73322922007-07-18 18:00:27 +00001173
1174 // Check if we've already instantiated a vector of this type.
1175 llvm::FoldingSetNodeID ID;
Nate Begeman213541a2008-04-18 23:10:10 +00001176 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector);
Steve Naroff73322922007-07-18 18:00:27 +00001177 void *InsertPos = 0;
1178 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1179 return QualType(VTP, 0);
1180
1181 // If the element type isn't canonical, this won't be a canonical type either,
1182 // so fill in the canonical type field.
1183 QualType Canonical;
1184 if (!vecType->isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001185 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Steve Naroff73322922007-07-18 18:00:27 +00001186
1187 // Get the new insert position for the node we care about.
1188 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001189 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001190 }
Steve Narofff83820b2009-01-27 22:08:43 +00001191 ExtVectorType *New = new (*this,8) ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001192 VectorTypes.InsertNode(New, InsertPos);
1193 Types.push_back(New);
1194 return QualType(New, 0);
1195}
1196
Douglas Gregor72564e72009-02-26 23:50:07 +00001197/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001198///
Douglas Gregor72564e72009-02-26 23:50:07 +00001199QualType ASTContext::getFunctionNoProtoType(QualType ResultTy) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001200 // Unique functions, to guarantee there is only one function of a particular
1201 // structure.
1202 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001203 FunctionNoProtoType::Profile(ID, ResultTy);
Reid Spencer5f016e22007-07-11 17:01:13 +00001204
1205 void *InsertPos = 0;
Douglas Gregor72564e72009-02-26 23:50:07 +00001206 if (FunctionNoProtoType *FT =
1207 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001208 return QualType(FT, 0);
1209
1210 QualType Canonical;
1211 if (!ResultTy->isCanonical()) {
Douglas Gregor72564e72009-02-26 23:50:07 +00001212 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy));
Reid Spencer5f016e22007-07-11 17:01:13 +00001213
1214 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001215 FunctionNoProtoType *NewIP =
1216 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001217 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001218 }
1219
Douglas Gregor72564e72009-02-26 23:50:07 +00001220 FunctionNoProtoType *New =new(*this,8)FunctionNoProtoType(ResultTy,Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001221 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001222 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001223 return QualType(New, 0);
1224}
1225
1226/// getFunctionType - Return a normal function type with a typed argument
1227/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner61710852008-10-05 17:34:18 +00001228QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001229 unsigned NumArgs, bool isVariadic,
1230 unsigned TypeQuals) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001231 // Unique functions, to guarantee there is only one function of a particular
1232 // structure.
1233 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001234 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001235 TypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001236
1237 void *InsertPos = 0;
Douglas Gregor72564e72009-02-26 23:50:07 +00001238 if (FunctionProtoType *FTP =
1239 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001240 return QualType(FTP, 0);
1241
1242 // Determine whether the type being created is already canonical or not.
1243 bool isCanonical = ResultTy->isCanonical();
1244 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
1245 if (!ArgArray[i]->isCanonical())
1246 isCanonical = false;
1247
1248 // If this type isn't canonical, get the canonical version of it.
1249 QualType Canonical;
1250 if (!isCanonical) {
1251 llvm::SmallVector<QualType, 16> CanonicalArgs;
1252 CanonicalArgs.reserve(NumArgs);
1253 for (unsigned i = 0; i != NumArgs; ++i)
Chris Lattnerf52ab252008-04-06 22:59:24 +00001254 CanonicalArgs.push_back(getCanonicalType(ArgArray[i]));
Reid Spencer5f016e22007-07-11 17:01:13 +00001255
Chris Lattnerf52ab252008-04-06 22:59:24 +00001256 Canonical = getFunctionType(getCanonicalType(ResultTy),
Reid Spencer5f016e22007-07-11 17:01:13 +00001257 &CanonicalArgs[0], NumArgs,
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001258 isVariadic, TypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001259
1260 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001261 FunctionProtoType *NewIP =
1262 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001263 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001264 }
1265
Douglas Gregor72564e72009-02-26 23:50:07 +00001266 // FunctionProtoType objects are allocated with extra bytes after them
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001267 // for a variable size array (for parameter types) at the end of them.
Douglas Gregor72564e72009-02-26 23:50:07 +00001268 FunctionProtoType *FTP =
1269 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
Steve Naroffc0ac4922009-01-27 23:20:32 +00001270 NumArgs*sizeof(QualType), 8);
Douglas Gregor72564e72009-02-26 23:50:07 +00001271 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001272 TypeQuals, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001273 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001274 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001275 return QualType(FTP, 0);
1276}
1277
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001278/// getTypeDeclType - Return the unique reference to the type for the
1279/// specified type declaration.
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001280QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001281 assert(Decl && "Passed null for Decl param");
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001282 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1283
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001284 if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001285 return getTypedefType(Typedef);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001286 else if (isa<TemplateTypeParmDecl>(Decl)) {
1287 assert(false && "Template type parameter types are always available.");
1288 } else if (ObjCInterfaceDecl *ObjCInterface = dyn_cast<ObjCInterfaceDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001289 return getObjCInterfaceType(ObjCInterface);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001290
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001291 if (RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001292 if (PrevDecl)
1293 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001294 else
1295 Decl->TypeForDecl = new (*this,8) RecordType(Record);
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001296 }
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001297 else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
1298 if (PrevDecl)
1299 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001300 else
1301 Decl->TypeForDecl = new (*this,8) EnumType(Enum);
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001302 }
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001303 else
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001304 assert(false && "TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001305
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001306 if (!PrevDecl) Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001307 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001308}
1309
Reid Spencer5f016e22007-07-11 17:01:13 +00001310/// getTypedefType - Return the unique reference to the type for the
1311/// specified typename decl.
1312QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
1313 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1314
Chris Lattnerf52ab252008-04-06 22:59:24 +00001315 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
Douglas Gregor72564e72009-02-26 23:50:07 +00001316 Decl->TypeForDecl = new(*this,8) TypedefType(Type::Typedef, Decl, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001317 Types.push_back(Decl->TypeForDecl);
1318 return QualType(Decl->TypeForDecl, 0);
1319}
1320
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001321/// getObjCInterfaceType - Return the unique reference to the type for the
Steve Naroff3536b442007-09-06 21:24:23 +00001322/// specified ObjC interface decl.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001323QualType ASTContext::getObjCInterfaceType(ObjCInterfaceDecl *Decl) {
Steve Naroff3536b442007-09-06 21:24:23 +00001324 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1325
Steve Narofff83820b2009-01-27 22:08:43 +00001326 Decl->TypeForDecl = new(*this,8) ObjCInterfaceType(Type::ObjCInterface, Decl);
Steve Naroff3536b442007-09-06 21:24:23 +00001327 Types.push_back(Decl->TypeForDecl);
1328 return QualType(Decl->TypeForDecl, 0);
1329}
1330
Fariborz Jahanianf3710ba2009-02-14 20:13:28 +00001331/// buildObjCInterfaceType - Returns a new type for the interface
1332/// declaration, regardless. It also removes any previously built
1333/// record declaration so caller can rebuild it.
1334QualType ASTContext::buildObjCInterfaceType(ObjCInterfaceDecl *Decl) {
1335 const RecordDecl *&RD = ASTRecordForInterface[Decl];
1336 if (RD)
1337 RD = 0;
1338 Decl->TypeForDecl = new(*this,8) ObjCInterfaceType(Type::ObjCInterface, Decl);
1339 Types.push_back(Decl->TypeForDecl);
1340 return QualType(Decl->TypeForDecl, 0);
1341}
1342
Douglas Gregorfab9d672009-02-05 23:33:38 +00001343/// \brief Retrieve the template type parameter type for a template
1344/// parameter with the given depth, index, and (optionally) name.
1345QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
1346 IdentifierInfo *Name) {
1347 llvm::FoldingSetNodeID ID;
1348 TemplateTypeParmType::Profile(ID, Depth, Index, Name);
1349 void *InsertPos = 0;
1350 TemplateTypeParmType *TypeParm
1351 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1352
1353 if (TypeParm)
1354 return QualType(TypeParm, 0);
1355
1356 if (Name)
1357 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, Name,
1358 getTemplateTypeParmType(Depth, Index));
1359 else
1360 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index);
1361
1362 Types.push_back(TypeParm);
1363 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1364
1365 return QualType(TypeParm, 0);
1366}
1367
Douglas Gregor55f6b142009-02-09 18:46:07 +00001368QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00001369ASTContext::getTemplateSpecializationType(TemplateName Template,
1370 const TemplateArgument *Args,
1371 unsigned NumArgs,
1372 QualType Canon) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001373 if (!Canon.isNull())
1374 Canon = getCanonicalType(Canon);
Douglas Gregorfc705b82009-02-26 22:19:44 +00001375
Douglas Gregor55f6b142009-02-09 18:46:07 +00001376 llvm::FoldingSetNodeID ID;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001377 TemplateSpecializationType::Profile(ID, Template, Args, NumArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001378
Douglas Gregor55f6b142009-02-09 18:46:07 +00001379 void *InsertPos = 0;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001380 TemplateSpecializationType *Spec
1381 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001382
1383 if (Spec)
1384 return QualType(Spec, 0);
1385
Douglas Gregor7532dc62009-03-30 22:58:21 +00001386 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00001387 sizeof(TemplateArgument) * NumArgs),
1388 8);
Douglas Gregor7532dc62009-03-30 22:58:21 +00001389 Spec = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, Canon);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001390 Types.push_back(Spec);
Douglas Gregor7532dc62009-03-30 22:58:21 +00001391 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001392
1393 return QualType(Spec, 0);
1394}
1395
Douglas Gregore4e5b052009-03-19 00:18:19 +00001396QualType
Douglas Gregorab452ba2009-03-26 23:50:42 +00001397ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
Douglas Gregore4e5b052009-03-19 00:18:19 +00001398 QualType NamedType) {
1399 llvm::FoldingSetNodeID ID;
Douglas Gregorab452ba2009-03-26 23:50:42 +00001400 QualifiedNameType::Profile(ID, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001401
1402 void *InsertPos = 0;
1403 QualifiedNameType *T
1404 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
1405 if (T)
1406 return QualType(T, 0);
1407
Douglas Gregorab452ba2009-03-26 23:50:42 +00001408 T = new (*this) QualifiedNameType(NNS, NamedType,
1409 getCanonicalType(NamedType));
Douglas Gregore4e5b052009-03-19 00:18:19 +00001410 Types.push_back(T);
1411 QualifiedNameTypes.InsertNode(T, InsertPos);
1412 return QualType(T, 0);
1413}
1414
Douglas Gregord57959a2009-03-27 23:10:48 +00001415QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1416 const IdentifierInfo *Name,
1417 QualType Canon) {
1418 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1419
1420 if (Canon.isNull()) {
1421 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1422 if (CanonNNS != NNS)
1423 Canon = getTypenameType(CanonNNS, Name);
1424 }
1425
1426 llvm::FoldingSetNodeID ID;
1427 TypenameType::Profile(ID, NNS, Name);
1428
1429 void *InsertPos = 0;
1430 TypenameType *T
1431 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1432 if (T)
1433 return QualType(T, 0);
1434
1435 T = new (*this) TypenameType(NNS, Name, Canon);
1436 Types.push_back(T);
1437 TypenameTypes.InsertNode(T, InsertPos);
1438 return QualType(T, 0);
1439}
1440
Chris Lattner88cb27a2008-04-07 04:56:42 +00001441/// CmpProtocolNames - Comparison predicate for sorting protocols
1442/// alphabetically.
1443static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
1444 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001445 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00001446}
1447
1448static void SortAndUniqueProtocols(ObjCProtocolDecl **&Protocols,
1449 unsigned &NumProtocols) {
1450 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
1451
1452 // Sort protocols, keyed by name.
1453 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
1454
1455 // Remove duplicates.
1456 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
1457 NumProtocols = ProtocolsEnd-Protocols;
1458}
1459
1460
Chris Lattner065f0d72008-04-07 04:44:08 +00001461/// getObjCQualifiedInterfaceType - Return a ObjCQualifiedInterfaceType type for
1462/// the given interface decl and the conforming protocol list.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001463QualType ASTContext::getObjCQualifiedInterfaceType(ObjCInterfaceDecl *Decl,
1464 ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
Chris Lattner88cb27a2008-04-07 04:56:42 +00001465 // Sort the protocol list alphabetically to canonicalize it.
1466 SortAndUniqueProtocols(Protocols, NumProtocols);
1467
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001468 llvm::FoldingSetNodeID ID;
Chris Lattnerb0489812008-04-07 06:38:24 +00001469 ObjCQualifiedInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001470
1471 void *InsertPos = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001472 if (ObjCQualifiedInterfaceType *QT =
1473 ObjCQualifiedInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001474 return QualType(QT, 0);
1475
1476 // No Match;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001477 ObjCQualifiedInterfaceType *QType =
Steve Narofff83820b2009-01-27 22:08:43 +00001478 new (*this,8) ObjCQualifiedInterfaceType(Decl, Protocols, NumProtocols);
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001479
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001480 Types.push_back(QType);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001481 ObjCQualifiedInterfaceTypes.InsertNode(QType, InsertPos);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001482 return QualType(QType, 0);
1483}
1484
Chris Lattner88cb27a2008-04-07 04:56:42 +00001485/// getObjCQualifiedIdType - Return an ObjCQualifiedIdType for the 'id' decl
1486/// and the conforming protocol list.
Chris Lattner62f5f7f2008-07-26 00:46:50 +00001487QualType ASTContext::getObjCQualifiedIdType(ObjCProtocolDecl **Protocols,
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001488 unsigned NumProtocols) {
Chris Lattner88cb27a2008-04-07 04:56:42 +00001489 // Sort the protocol list alphabetically to canonicalize it.
1490 SortAndUniqueProtocols(Protocols, NumProtocols);
1491
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001492 llvm::FoldingSetNodeID ID;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001493 ObjCQualifiedIdType::Profile(ID, Protocols, NumProtocols);
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001494
1495 void *InsertPos = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001496 if (ObjCQualifiedIdType *QT =
Chris Lattner62f5f7f2008-07-26 00:46:50 +00001497 ObjCQualifiedIdTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001498 return QualType(QT, 0);
1499
1500 // No Match;
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001501 ObjCQualifiedIdType *QType =
Steve Narofff83820b2009-01-27 22:08:43 +00001502 new (*this,8) ObjCQualifiedIdType(Protocols, NumProtocols);
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001503 Types.push_back(QType);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001504 ObjCQualifiedIdTypes.InsertNode(QType, InsertPos);
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001505 return QualType(QType, 0);
1506}
1507
Douglas Gregor72564e72009-02-26 23:50:07 +00001508/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
1509/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00001510/// multiple declarations that refer to "typeof(x)" all contain different
1511/// DeclRefExpr's. This doesn't effect the type checker, since it operates
1512/// on canonical type's (which are always unique).
Douglas Gregor72564e72009-02-26 23:50:07 +00001513QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001514 QualType Canonical = getCanonicalType(tofExpr->getType());
Douglas Gregor72564e72009-02-26 23:50:07 +00001515 TypeOfExprType *toe = new (*this,8) TypeOfExprType(tofExpr, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00001516 Types.push_back(toe);
1517 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00001518}
1519
Steve Naroff9752f252007-08-01 18:02:17 +00001520/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
1521/// TypeOfType AST's. The only motivation to unique these nodes would be
1522/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
1523/// an issue. This doesn't effect the type checker, since it operates
1524/// on canonical type's (which are always unique).
Steve Naroffd1861fd2007-07-31 12:34:36 +00001525QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001526 QualType Canonical = getCanonicalType(tofType);
Steve Narofff83820b2009-01-27 22:08:43 +00001527 TypeOfType *tot = new (*this,8) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00001528 Types.push_back(tot);
1529 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00001530}
1531
Reid Spencer5f016e22007-07-11 17:01:13 +00001532/// getTagDeclType - Return the unique reference to the type for the
1533/// specified TagDecl (struct/union/class/enum) decl.
1534QualType ASTContext::getTagDeclType(TagDecl *Decl) {
Ted Kremenekd778f882007-11-26 21:16:01 +00001535 assert (Decl);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001536 return getTypeDeclType(Decl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001537}
1538
1539/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
1540/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
1541/// needs to agree with the definition in <stddef.h>.
1542QualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00001543 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00001544}
1545
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00001546/// getSignedWCharType - Return the type of "signed wchar_t".
1547/// Used when in C++, as a GCC extension.
1548QualType ASTContext::getSignedWCharType() const {
1549 // FIXME: derive from "Target" ?
1550 return WCharTy;
1551}
1552
1553/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
1554/// Used when in C++, as a GCC extension.
1555QualType ASTContext::getUnsignedWCharType() const {
1556 // FIXME: derive from "Target" ?
1557 return UnsignedIntTy;
1558}
1559
Chris Lattner8b9023b2007-07-13 03:05:23 +00001560/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
1561/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
1562QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00001563 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00001564}
1565
Chris Lattnere6327742008-04-02 05:18:44 +00001566//===----------------------------------------------------------------------===//
1567// Type Operators
1568//===----------------------------------------------------------------------===//
1569
Chris Lattner77c96472008-04-06 22:41:35 +00001570/// getCanonicalType - Return the canonical (structural) type corresponding to
1571/// the specified potentially non-canonical type. The non-canonical version
1572/// of a type may have many "decorated" versions of types. Decorators can
1573/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
1574/// to be free of any of these, allowing two canonical types to be compared
1575/// for exact equality with a simple pointer comparison.
1576QualType ASTContext::getCanonicalType(QualType T) {
1577 QualType CanType = T.getTypePtr()->getCanonicalTypeInternal();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001578
1579 // If the result has type qualifiers, make sure to canonicalize them as well.
1580 unsigned TypeQuals = T.getCVRQualifiers() | CanType.getCVRQualifiers();
1581 if (TypeQuals == 0) return CanType;
1582
1583 // If the type qualifiers are on an array type, get the canonical type of the
1584 // array with the qualifiers applied to the element type.
1585 ArrayType *AT = dyn_cast<ArrayType>(CanType);
1586 if (!AT)
1587 return CanType.getQualifiedType(TypeQuals);
1588
1589 // Get the canonical version of the element with the extra qualifiers on it.
1590 // This can recursively sink qualifiers through multiple levels of arrays.
1591 QualType NewEltTy=AT->getElementType().getWithAdditionalQualifiers(TypeQuals);
1592 NewEltTy = getCanonicalType(NewEltTy);
1593
1594 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
1595 return getConstantArrayType(NewEltTy, CAT->getSize(),CAT->getSizeModifier(),
1596 CAT->getIndexTypeQualifier());
1597 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
1598 return getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
1599 IAT->getIndexTypeQualifier());
1600
Douglas Gregor898574e2008-12-05 23:32:09 +00001601 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
1602 return getDependentSizedArrayType(NewEltTy, DSAT->getSizeExpr(),
1603 DSAT->getSizeModifier(),
1604 DSAT->getIndexTypeQualifier());
1605
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001606 VariableArrayType *VAT = cast<VariableArrayType>(AT);
1607 return getVariableArrayType(NewEltTy, VAT->getSizeExpr(),
1608 VAT->getSizeModifier(),
1609 VAT->getIndexTypeQualifier());
1610}
1611
Douglas Gregord57959a2009-03-27 23:10:48 +00001612NestedNameSpecifier *
1613ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
1614 if (!NNS)
1615 return 0;
1616
1617 switch (NNS->getKind()) {
1618 case NestedNameSpecifier::Identifier:
1619 // Canonicalize the prefix but keep the identifier the same.
1620 return NestedNameSpecifier::Create(*this,
1621 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
1622 NNS->getAsIdentifier());
1623
1624 case NestedNameSpecifier::Namespace:
1625 // A namespace is canonical; build a nested-name-specifier with
1626 // this namespace and no prefix.
1627 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
1628
1629 case NestedNameSpecifier::TypeSpec:
1630 case NestedNameSpecifier::TypeSpecWithTemplate: {
1631 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
1632 NestedNameSpecifier *Prefix = 0;
1633
1634 // FIXME: This isn't the right check!
1635 if (T->isDependentType())
1636 Prefix = getCanonicalNestedNameSpecifier(NNS->getPrefix());
1637
1638 return NestedNameSpecifier::Create(*this, Prefix,
1639 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
1640 T.getTypePtr());
1641 }
1642
1643 case NestedNameSpecifier::Global:
1644 // The global specifier is canonical and unique.
1645 return NNS;
1646 }
1647
1648 // Required to silence a GCC warning
1649 return 0;
1650}
1651
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001652
1653const ArrayType *ASTContext::getAsArrayType(QualType T) {
1654 // Handle the non-qualified case efficiently.
1655 if (T.getCVRQualifiers() == 0) {
1656 // Handle the common positive case fast.
1657 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
1658 return AT;
1659 }
1660
1661 // Handle the common negative case fast, ignoring CVR qualifiers.
1662 QualType CType = T->getCanonicalTypeInternal();
1663
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001664 // Make sure to look through type qualifiers (like ExtQuals) for the negative
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001665 // test.
1666 if (!isa<ArrayType>(CType) &&
1667 !isa<ArrayType>(CType.getUnqualifiedType()))
1668 return 0;
1669
1670 // Apply any CVR qualifiers from the array type to the element type. This
1671 // implements C99 6.7.3p8: "If the specification of an array type includes
1672 // any type qualifiers, the element type is so qualified, not the array type."
1673
1674 // If we get here, we either have type qualifiers on the type, or we have
1675 // sugar such as a typedef in the way. If we have type qualifiers on the type
1676 // we must propagate them down into the elemeng type.
1677 unsigned CVRQuals = T.getCVRQualifiers();
1678 unsigned AddrSpace = 0;
1679 Type *Ty = T.getTypePtr();
1680
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001681 // Rip through ExtQualType's and typedefs to get to a concrete type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001682 while (1) {
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001683 if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(Ty)) {
1684 AddrSpace = EXTQT->getAddressSpace();
1685 Ty = EXTQT->getBaseType();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001686 } else {
1687 T = Ty->getDesugaredType();
1688 if (T.getTypePtr() == Ty && T.getCVRQualifiers() == 0)
1689 break;
1690 CVRQuals |= T.getCVRQualifiers();
1691 Ty = T.getTypePtr();
1692 }
1693 }
1694
1695 // If we have a simple case, just return now.
1696 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
1697 if (ATy == 0 || (AddrSpace == 0 && CVRQuals == 0))
1698 return ATy;
1699
1700 // Otherwise, we have an array and we have qualifiers on it. Push the
1701 // qualifiers into the array element type and return a new array type.
1702 // Get the canonical version of the element with the extra qualifiers on it.
1703 // This can recursively sink qualifiers through multiple levels of arrays.
1704 QualType NewEltTy = ATy->getElementType();
1705 if (AddrSpace)
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001706 NewEltTy = getAddrSpaceQualType(NewEltTy, AddrSpace);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001707 NewEltTy = NewEltTy.getWithAdditionalQualifiers(CVRQuals);
1708
1709 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
1710 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
1711 CAT->getSizeModifier(),
1712 CAT->getIndexTypeQualifier()));
1713 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
1714 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
1715 IAT->getSizeModifier(),
1716 IAT->getIndexTypeQualifier()));
Douglas Gregor898574e2008-12-05 23:32:09 +00001717
Douglas Gregor898574e2008-12-05 23:32:09 +00001718 if (const DependentSizedArrayType *DSAT
1719 = dyn_cast<DependentSizedArrayType>(ATy))
1720 return cast<ArrayType>(
1721 getDependentSizedArrayType(NewEltTy,
1722 DSAT->getSizeExpr(),
1723 DSAT->getSizeModifier(),
1724 DSAT->getIndexTypeQualifier()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001725
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001726 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
1727 return cast<ArrayType>(getVariableArrayType(NewEltTy, VAT->getSizeExpr(),
1728 VAT->getSizeModifier(),
1729 VAT->getIndexTypeQualifier()));
Chris Lattner77c96472008-04-06 22:41:35 +00001730}
1731
1732
Chris Lattnere6327742008-04-02 05:18:44 +00001733/// getArrayDecayedType - Return the properly qualified result of decaying the
1734/// specified array type to a pointer. This operation is non-trivial when
1735/// handling typedefs etc. The canonical type of "T" must be an array type,
1736/// this returns a pointer to a properly qualified element of the array.
1737///
1738/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
1739QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001740 // Get the element type with 'getAsArrayType' so that we don't lose any
1741 // typedefs in the element type of the array. This also handles propagation
1742 // of type qualifiers from the array type into the element type if present
1743 // (C99 6.7.3p8).
1744 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
1745 assert(PrettyArrayType && "Not an array type!");
Chris Lattnere6327742008-04-02 05:18:44 +00001746
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001747 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00001748
1749 // int x[restrict 4] -> int *restrict
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001750 return PtrTy.getQualifiedType(PrettyArrayType->getIndexTypeQualifier());
Chris Lattnere6327742008-04-02 05:18:44 +00001751}
1752
Daniel Dunbard786f6a2009-01-05 22:14:37 +00001753QualType ASTContext::getBaseElementType(const VariableArrayType *VAT) {
Anders Carlsson6183a992008-12-21 03:44:36 +00001754 QualType ElemTy = VAT->getElementType();
1755
1756 if (const VariableArrayType *VAT = getAsVariableArrayType(ElemTy))
1757 return getBaseElementType(VAT);
1758
1759 return ElemTy;
1760}
1761
Reid Spencer5f016e22007-07-11 17:01:13 +00001762/// getFloatingRank - Return a relative rank for floating point types.
1763/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00001764static FloatingRank getFloatingRank(QualType T) {
Christopher Lambebb97e92008-02-04 02:31:56 +00001765 if (const ComplexType *CT = T->getAsComplexType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001766 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00001767
Daniel Dunbard786f6a2009-01-05 22:14:37 +00001768 assert(T->getAsBuiltinType() && "getFloatingRank(): not a floating type");
Christopher Lambebb97e92008-02-04 02:31:56 +00001769 switch (T->getAsBuiltinType()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00001770 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00001771 case BuiltinType::Float: return FloatRank;
1772 case BuiltinType::Double: return DoubleRank;
1773 case BuiltinType::LongDouble: return LongDoubleRank;
1774 }
1775}
1776
Steve Naroff716c7302007-08-27 01:41:48 +00001777/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
1778/// point or a complex type (based on typeDomain/typeSize).
1779/// 'typeDomain' is a real floating point or complex type.
1780/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00001781QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
1782 QualType Domain) const {
1783 FloatingRank EltRank = getFloatingRank(Size);
1784 if (Domain->isComplexType()) {
1785 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00001786 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00001787 case FloatRank: return FloatComplexTy;
1788 case DoubleRank: return DoubleComplexTy;
1789 case LongDoubleRank: return LongDoubleComplexTy;
1790 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001791 }
Chris Lattner1361b112008-04-06 23:58:54 +00001792
1793 assert(Domain->isRealFloatingType() && "Unknown domain!");
1794 switch (EltRank) {
1795 default: assert(0 && "getFloatingRank(): illegal value for rank");
1796 case FloatRank: return FloatTy;
1797 case DoubleRank: return DoubleTy;
1798 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00001799 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001800}
1801
Chris Lattner7cfeb082008-04-06 23:55:33 +00001802/// getFloatingTypeOrder - Compare the rank of the two specified floating
1803/// point types, ignoring the domain of the type (i.e. 'double' ==
1804/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
1805/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00001806int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
1807 FloatingRank LHSR = getFloatingRank(LHS);
1808 FloatingRank RHSR = getFloatingRank(RHS);
1809
1810 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00001811 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00001812 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00001813 return 1;
1814 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00001815}
1816
Chris Lattnerf52ab252008-04-06 22:59:24 +00001817/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
1818/// routine will assert if passed a built-in type that isn't an integer or enum,
1819/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00001820unsigned ASTContext::getIntegerRank(Type *T) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001821 assert(T->isCanonical() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00001822 if (EnumType* ET = dyn_cast<EnumType>(T))
1823 T = ET->getDecl()->getIntegerType().getTypePtr();
1824
1825 // There are two things which impact the integer rank: the width, and
1826 // the ordering of builtins. The builtin ordering is encoded in the
1827 // bottom three bits; the width is encoded in the bits above that.
1828 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T)) {
1829 return FWIT->getWidth() << 3;
1830 }
1831
Chris Lattnerf52ab252008-04-06 22:59:24 +00001832 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00001833 default: assert(0 && "getIntegerRank(): not a built-in integer");
1834 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00001835 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00001836 case BuiltinType::Char_S:
1837 case BuiltinType::Char_U:
1838 case BuiltinType::SChar:
1839 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00001840 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00001841 case BuiltinType::Short:
1842 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00001843 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00001844 case BuiltinType::Int:
1845 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00001846 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00001847 case BuiltinType::Long:
1848 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00001849 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00001850 case BuiltinType::LongLong:
1851 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00001852 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00001853 }
1854}
1855
Chris Lattner7cfeb082008-04-06 23:55:33 +00001856/// getIntegerTypeOrder - Returns the highest ranked integer type:
1857/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
1858/// LHS < RHS, return -1.
1859int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001860 Type *LHSC = getCanonicalType(LHS).getTypePtr();
1861 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00001862 if (LHSC == RHSC) return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001863
Chris Lattnerf52ab252008-04-06 22:59:24 +00001864 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
1865 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001866
Chris Lattner7cfeb082008-04-06 23:55:33 +00001867 unsigned LHSRank = getIntegerRank(LHSC);
1868 unsigned RHSRank = getIntegerRank(RHSC);
Reid Spencer5f016e22007-07-11 17:01:13 +00001869
Chris Lattner7cfeb082008-04-06 23:55:33 +00001870 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
1871 if (LHSRank == RHSRank) return 0;
1872 return LHSRank > RHSRank ? 1 : -1;
1873 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001874
Chris Lattner7cfeb082008-04-06 23:55:33 +00001875 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
1876 if (LHSUnsigned) {
1877 // If the unsigned [LHS] type is larger, return it.
1878 if (LHSRank >= RHSRank)
1879 return 1;
1880
1881 // If the signed type can represent all values of the unsigned type, it
1882 // wins. Because we are dealing with 2's complement and types that are
1883 // powers of two larger than each other, this is always safe.
1884 return -1;
1885 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00001886
Chris Lattner7cfeb082008-04-06 23:55:33 +00001887 // If the unsigned [RHS] type is larger, return it.
1888 if (RHSRank >= LHSRank)
1889 return -1;
1890
1891 // If the signed type can represent all values of the unsigned type, it
1892 // wins. Because we are dealing with 2's complement and types that are
1893 // powers of two larger than each other, this is always safe.
1894 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00001895}
Anders Carlsson71993dd2007-08-17 05:31:46 +00001896
1897// getCFConstantStringType - Return the type used for constant CFStrings.
1898QualType ASTContext::getCFConstantStringType() {
1899 if (!CFConstantStringTypeDecl) {
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001900 CFConstantStringTypeDecl =
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001901 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00001902 &Idents.get("NSConstantString"));
Anders Carlssonf06273f2007-11-19 00:25:30 +00001903 QualType FieldTypes[4];
Anders Carlsson71993dd2007-08-17 05:31:46 +00001904
1905 // const int *isa;
1906 FieldTypes[0] = getPointerType(IntTy.getQualifiedType(QualType::Const));
Anders Carlssonf06273f2007-11-19 00:25:30 +00001907 // int flags;
1908 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00001909 // const char *str;
Anders Carlssonf06273f2007-11-19 00:25:30 +00001910 FieldTypes[2] = getPointerType(CharTy.getQualifiedType(QualType::Const));
Anders Carlsson71993dd2007-08-17 05:31:46 +00001911 // long length;
Anders Carlssonf06273f2007-11-19 00:25:30 +00001912 FieldTypes[3] = LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00001913
Anders Carlsson71993dd2007-08-17 05:31:46 +00001914 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00001915 for (unsigned i = 0; i < 4; ++i) {
1916 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
1917 SourceLocation(), 0,
1918 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001919 /*Mutable=*/false);
Douglas Gregor482b77d2009-01-12 23:27:07 +00001920 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00001921 }
1922
1923 CFConstantStringTypeDecl->completeDefinition(*this);
Anders Carlsson71993dd2007-08-17 05:31:46 +00001924 }
1925
1926 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00001927}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00001928
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00001929QualType ASTContext::getObjCFastEnumerationStateType()
1930{
1931 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00001932 ObjCFastEnumerationStateTypeDecl =
1933 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
1934 &Idents.get("__objcFastEnumerationState"));
1935
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00001936 QualType FieldTypes[] = {
1937 UnsignedLongTy,
1938 getPointerType(ObjCIdType),
1939 getPointerType(UnsignedLongTy),
1940 getConstantArrayType(UnsignedLongTy,
1941 llvm::APInt(32, 5), ArrayType::Normal, 0)
1942 };
1943
Douglas Gregor44b43212008-12-11 16:49:14 +00001944 for (size_t i = 0; i < 4; ++i) {
1945 FieldDecl *Field = FieldDecl::Create(*this,
1946 ObjCFastEnumerationStateTypeDecl,
1947 SourceLocation(), 0,
1948 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001949 /*Mutable=*/false);
Douglas Gregor482b77d2009-01-12 23:27:07 +00001950 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00001951 }
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00001952
Douglas Gregor44b43212008-12-11 16:49:14 +00001953 ObjCFastEnumerationStateTypeDecl->completeDefinition(*this);
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00001954 }
1955
1956 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
1957}
1958
Anders Carlssone8c49532007-10-29 06:33:42 +00001959// This returns true if a type has been typedefed to BOOL:
1960// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00001961static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00001962 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00001963 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
1964 return II->isStr("BOOL");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001965
1966 return false;
1967}
1968
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001969/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001970/// purpose.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001971int ASTContext::getObjCEncodingTypeSize(QualType type) {
Chris Lattner98be4942008-03-05 18:54:05 +00001972 uint64_t sz = getTypeSize(type);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001973
1974 // Make all integer and enum types at least as large as an int
1975 if (sz > 0 && type->isIntegralType())
Chris Lattner98be4942008-03-05 18:54:05 +00001976 sz = std::max(sz, getTypeSize(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001977 // Treat arrays as pointers, since that's how they're passed in.
1978 else if (type->isArrayType())
Chris Lattner98be4942008-03-05 18:54:05 +00001979 sz = getTypeSize(VoidPtrTy);
1980 return sz / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001981}
1982
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001983/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001984/// declaration.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001985void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00001986 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00001987 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00001988 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001989 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001990 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001991 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001992 // Compute size of all parameters.
1993 // Start with computing size of a pointer in number of bytes.
1994 // FIXME: There might(should) be a better way of doing this computation!
1995 SourceLocation Loc;
Chris Lattner98be4942008-03-05 18:54:05 +00001996 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001997 // The first two arguments (self and _cmd) are pointers; account for
1998 // their size.
1999 int ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00002000 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2001 E = Decl->param_end(); PI != E; ++PI) {
2002 QualType PType = (*PI)->getType();
2003 int sz = getObjCEncodingTypeSize(PType);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002004 assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002005 ParmOffset += sz;
2006 }
2007 S += llvm::utostr(ParmOffset);
2008 S += "@0:";
2009 S += llvm::utostr(PtrSize);
2010
2011 // Argument types.
2012 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00002013 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2014 E = Decl->param_end(); PI != E; ++PI) {
2015 ParmVarDecl *PVDecl = *PI;
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00002016 QualType PType = PVDecl->getOriginalType();
2017 if (const ArrayType *AT =
2018 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal()))
2019 // Use array's original type only if it has known number of
2020 // elements.
2021 if (!dyn_cast<ConstantArrayType>(AT))
2022 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002023 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002024 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00002025 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002026 getObjCEncodingForType(PType, S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002027 S += llvm::utostr(ParmOffset);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002028 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002029 }
2030}
2031
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002032/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00002033/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002034/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
2035/// NULL when getting encodings for protocol properties.
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00002036/// Property attributes are stored as a comma-delimited C string. The simple
2037/// attributes readonly and bycopy are encoded as single characters. The
2038/// parametrized attributes, getter=name, setter=name, and ivar=name, are
2039/// encoded as single characters, followed by an identifier. Property types
2040/// are also encoded as a parametrized attribute. The characters used to encode
2041/// these attributes are defined by the following enumeration:
2042/// @code
2043/// enum PropertyAttributes {
2044/// kPropertyReadOnly = 'R', // property is read-only.
2045/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
2046/// kPropertyByref = '&', // property is a reference to the value last assigned
2047/// kPropertyDynamic = 'D', // property is dynamic
2048/// kPropertyGetter = 'G', // followed by getter selector name
2049/// kPropertySetter = 'S', // followed by setter selector name
2050/// kPropertyInstanceVariable = 'V' // followed by instance variable name
2051/// kPropertyType = 't' // followed by old-style type encoding.
2052/// kPropertyWeak = 'W' // 'weak' property
2053/// kPropertyStrong = 'P' // property GC'able
2054/// kPropertyNonAtomic = 'N' // property non-atomic
2055/// };
2056/// @endcode
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002057void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
2058 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00002059 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002060 // Collect information from the property implementation decl(s).
2061 bool Dynamic = false;
2062 ObjCPropertyImplDecl *SynthesizePID = 0;
2063
2064 // FIXME: Duplicated code due to poor abstraction.
2065 if (Container) {
2066 if (const ObjCCategoryImplDecl *CID =
2067 dyn_cast<ObjCCategoryImplDecl>(Container)) {
2068 for (ObjCCategoryImplDecl::propimpl_iterator
2069 i = CID->propimpl_begin(), e = CID->propimpl_end(); i != e; ++i) {
2070 ObjCPropertyImplDecl *PID = *i;
2071 if (PID->getPropertyDecl() == PD) {
2072 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2073 Dynamic = true;
2074 } else {
2075 SynthesizePID = PID;
2076 }
2077 }
2078 }
2079 } else {
Chris Lattner61710852008-10-05 17:34:18 +00002080 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002081 for (ObjCCategoryImplDecl::propimpl_iterator
2082 i = OID->propimpl_begin(), e = OID->propimpl_end(); i != e; ++i) {
2083 ObjCPropertyImplDecl *PID = *i;
2084 if (PID->getPropertyDecl() == PD) {
2085 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2086 Dynamic = true;
2087 } else {
2088 SynthesizePID = PID;
2089 }
2090 }
2091 }
2092 }
2093 }
2094
2095 // FIXME: This is not very efficient.
2096 S = "T";
2097
2098 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002099 // GCC has some special rules regarding encoding of properties which
2100 // closely resembles encoding of ivars.
2101 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, NULL,
2102 true /* outermost type */,
2103 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002104
2105 if (PD->isReadOnly()) {
2106 S += ",R";
2107 } else {
2108 switch (PD->getSetterKind()) {
2109 case ObjCPropertyDecl::Assign: break;
2110 case ObjCPropertyDecl::Copy: S += ",C"; break;
2111 case ObjCPropertyDecl::Retain: S += ",&"; break;
2112 }
2113 }
2114
2115 // It really isn't clear at all what this means, since properties
2116 // are "dynamic by default".
2117 if (Dynamic)
2118 S += ",D";
2119
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002120 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
2121 S += ",N";
2122
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002123 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
2124 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002125 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002126 }
2127
2128 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
2129 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002130 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002131 }
2132
2133 if (SynthesizePID) {
2134 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
2135 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00002136 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002137 }
2138
2139 // FIXME: OBJCGC: weak & strong
2140}
2141
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002142/// getLegacyIntegralTypeEncoding -
2143/// Another legacy compatibility encoding: 32-bit longs are encoded as
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002144/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002145/// 'i' or 'I' instead if encoding a struct field, or a pointer!
2146///
2147void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
2148 if (dyn_cast<TypedefType>(PointeeTy.getTypePtr())) {
2149 if (const BuiltinType *BT = PointeeTy->getAsBuiltinType()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002150 if (BT->getKind() == BuiltinType::ULong &&
2151 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002152 PointeeTy = UnsignedIntTy;
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002153 else
2154 if (BT->getKind() == BuiltinType::Long &&
2155 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002156 PointeeTy = IntTy;
2157 }
2158 }
2159}
2160
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002161void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002162 FieldDecl *Field) const {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002163 // We follow the behavior of gcc, expanding structures which are
2164 // directly pointed to, and expanding embedded structures. Note that
2165 // these rules are sufficient to prevent recursive encoding of the
2166 // same type.
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00002167 getObjCEncodingForTypeImpl(T, S, true, true, Field,
2168 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002169}
2170
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002171static void EncodeBitField(const ASTContext *Context, std::string& S,
2172 FieldDecl *FD) {
2173 const Expr *E = FD->getBitWidth();
2174 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
2175 ASTContext *Ctx = const_cast<ASTContext*>(Context);
2176 unsigned N = E->getIntegerConstantExprValue(*Ctx).getZExtValue();
2177 S += 'b';
2178 S += llvm::utostr(N);
2179}
2180
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002181void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
2182 bool ExpandPointedToStructures,
2183 bool ExpandStructures,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00002184 FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002185 bool OutermostType,
2186 bool EncodingProperty) const {
Anders Carlssone8c49532007-10-29 06:33:42 +00002187 if (const BuiltinType *BT = T->getAsBuiltinType()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002188 if (FD && FD->isBitField()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002189 EncodeBitField(this, S, FD);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002190 }
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002191 else {
2192 char encoding;
2193 switch (BT->getKind()) {
2194 default: assert(0 && "Unhandled builtin type kind");
2195 case BuiltinType::Void: encoding = 'v'; break;
2196 case BuiltinType::Bool: encoding = 'B'; break;
2197 case BuiltinType::Char_U:
2198 case BuiltinType::UChar: encoding = 'C'; break;
2199 case BuiltinType::UShort: encoding = 'S'; break;
2200 case BuiltinType::UInt: encoding = 'I'; break;
Fariborz Jahanian72696e12009-02-11 22:31:45 +00002201 case BuiltinType::ULong:
2202 encoding =
2203 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
2204 break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002205 case BuiltinType::ULongLong: encoding = 'Q'; break;
2206 case BuiltinType::Char_S:
2207 case BuiltinType::SChar: encoding = 'c'; break;
2208 case BuiltinType::Short: encoding = 's'; break;
2209 case BuiltinType::Int: encoding = 'i'; break;
Fariborz Jahanian72696e12009-02-11 22:31:45 +00002210 case BuiltinType::Long:
2211 encoding =
2212 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
2213 break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002214 case BuiltinType::LongLong: encoding = 'q'; break;
2215 case BuiltinType::Float: encoding = 'f'; break;
2216 case BuiltinType::Double: encoding = 'd'; break;
2217 case BuiltinType::LongDouble: encoding = 'd'; break;
2218 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002219
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002220 S += encoding;
2221 }
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002222 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002223 else if (T->isObjCQualifiedIdType()) {
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002224 getObjCEncodingForTypeImpl(getObjCIdType(), S,
2225 ExpandPointedToStructures,
2226 ExpandStructures, FD);
2227 if (FD || EncodingProperty) {
2228 // Note that we do extended encoding of protocol qualifer list
2229 // Only when doing ivar or property encoding.
2230 const ObjCQualifiedIdType *QIDT = T->getAsObjCQualifiedIdType();
2231 S += '"';
2232 for (unsigned i =0; i < QIDT->getNumProtocols(); i++) {
2233 ObjCProtocolDecl *Proto = QIDT->getProtocols(i);
2234 S += '<';
2235 S += Proto->getNameAsString();
2236 S += '>';
2237 }
2238 S += '"';
2239 }
2240 return;
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002241 }
2242 else if (const PointerType *PT = T->getAsPointerType()) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002243 QualType PointeeTy = PT->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002244 bool isReadOnly = false;
2245 // For historical/compatibility reasons, the read-only qualifier of the
2246 // pointee gets emitted _before_ the '^'. The read-only qualifier of
2247 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
2248 // Also, do not emit the 'r' for anything but the outermost type!
2249 if (dyn_cast<TypedefType>(T.getTypePtr())) {
2250 if (OutermostType && T.isConstQualified()) {
2251 isReadOnly = true;
2252 S += 'r';
2253 }
2254 }
2255 else if (OutermostType) {
2256 QualType P = PointeeTy;
2257 while (P->getAsPointerType())
2258 P = P->getAsPointerType()->getPointeeType();
2259 if (P.isConstQualified()) {
2260 isReadOnly = true;
2261 S += 'r';
2262 }
2263 }
2264 if (isReadOnly) {
2265 // Another legacy compatibility encoding. Some ObjC qualifier and type
2266 // combinations need to be rearranged.
2267 // Rewrite "in const" from "nr" to "rn"
2268 const char * s = S.c_str();
2269 int len = S.length();
2270 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
2271 std::string replace = "rn";
2272 S.replace(S.end()-2, S.end(), replace);
2273 }
2274 }
Steve Naroff389bf462009-02-12 17:52:19 +00002275 if (isObjCIdStructType(PointeeTy)) {
Fariborz Jahanianc2939bc2007-10-30 17:06:23 +00002276 S += '@';
2277 return;
Fariborz Jahanianc166d732008-12-19 00:14:49 +00002278 }
2279 else if (PointeeTy->isObjCInterfaceType()) {
Fariborz Jahanianbb99bde2009-02-16 21:41:04 +00002280 if (!EncodingProperty &&
Fariborz Jahanian225dfd72009-02-16 22:09:26 +00002281 isa<TypedefType>(PointeeTy.getTypePtr())) {
Fariborz Jahanian3e1b16c2008-12-23 21:30:15 +00002282 // Another historical/compatibility reason.
2283 // We encode the underlying type which comes out as
2284 // {...};
2285 S += '^';
2286 getObjCEncodingForTypeImpl(PointeeTy, S,
2287 false, ExpandPointedToStructures,
2288 NULL);
2289 return;
2290 }
Fariborz Jahanianc166d732008-12-19 00:14:49 +00002291 S += '@';
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002292 if (FD || EncodingProperty) {
Fariborz Jahanian86f938b2009-02-21 18:23:24 +00002293 const ObjCInterfaceType *OIT =
2294 PointeeTy.getUnqualifiedType()->getAsObjCInterfaceType();
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002295 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanianadcaf542008-12-20 19:17:01 +00002296 S += '"';
2297 S += OI->getNameAsCString();
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002298 for (unsigned i =0; i < OIT->getNumProtocols(); i++) {
2299 ObjCProtocolDecl *Proto = OIT->getProtocol(i);
2300 S += '<';
2301 S += Proto->getNameAsString();
2302 S += '>';
2303 }
Fariborz Jahanianadcaf542008-12-20 19:17:01 +00002304 S += '"';
2305 }
Fariborz Jahanianc166d732008-12-19 00:14:49 +00002306 return;
Steve Naroff389bf462009-02-12 17:52:19 +00002307 } else if (isObjCClassStructType(PointeeTy)) {
Anders Carlsson8baaca52007-10-31 02:53:19 +00002308 S += '#';
2309 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002310 } else if (isObjCSelType(PointeeTy)) {
Anders Carlsson8baaca52007-10-31 02:53:19 +00002311 S += ':';
2312 return;
Fariborz Jahanianc2939bc2007-10-30 17:06:23 +00002313 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002314
2315 if (PointeeTy->isCharType()) {
2316 // char pointer types should be encoded as '*' unless it is a
2317 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00002318 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002319 S += '*';
2320 return;
2321 }
2322 }
2323
2324 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002325 getLegacyIntegralTypeEncoding(PointeeTy);
2326
2327 getObjCEncodingForTypeImpl(PointeeTy, S,
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002328 false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002329 NULL);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002330 } else if (const ArrayType *AT =
2331 // Ignore type qualifiers etc.
2332 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00002333 if (isa<IncompleteArrayType>(AT)) {
2334 // Incomplete arrays are encoded as a pointer to the array element.
2335 S += '^';
2336
2337 getObjCEncodingForTypeImpl(AT->getElementType(), S,
2338 false, ExpandStructures, FD);
2339 } else {
2340 S += '[';
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002341
Anders Carlsson559a8332009-02-22 01:38:57 +00002342 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
2343 S += llvm::utostr(CAT->getSize().getZExtValue());
2344 else {
2345 //Variable length arrays are encoded as a regular array with 0 elements.
2346 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
2347 S += '0';
2348 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002349
Anders Carlsson559a8332009-02-22 01:38:57 +00002350 getObjCEncodingForTypeImpl(AT->getElementType(), S,
2351 false, ExpandStructures, FD);
2352 S += ']';
2353 }
Anders Carlssonc0a87b72007-10-30 00:06:20 +00002354 } else if (T->getAsFunctionType()) {
2355 S += '?';
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00002356 } else if (const RecordType *RTy = T->getAsRecordType()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002357 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002358 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00002359 // Anonymous structures print as '?'
2360 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
2361 S += II->getName();
2362 } else {
2363 S += '?';
2364 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002365 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002366 S += '=';
Douglas Gregor44b43212008-12-11 16:49:14 +00002367 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
2368 FieldEnd = RDecl->field_end();
2369 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002370 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002371 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00002372 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002373 S += '"';
2374 }
2375
2376 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002377 if (Field->isBitField()) {
2378 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
2379 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002380 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002381 QualType qt = Field->getType();
2382 getLegacyIntegralTypeEncoding(qt);
2383 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002384 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002385 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002386 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00002387 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002388 S += RDecl->isUnion() ? ')' : '}';
Steve Naroff5e711242007-12-12 22:30:11 +00002389 } else if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002390 if (FD && FD->isBitField())
2391 EncodeBitField(this, S, FD);
2392 else
2393 S += 'i';
Steve Naroff485eeff2008-09-24 15:05:44 +00002394 } else if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00002395 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002396 } else if (T->isObjCInterfaceType()) {
2397 // @encode(class_name)
2398 ObjCInterfaceDecl *OI = T->getAsObjCInterfaceType()->getDecl();
2399 S += '{';
2400 const IdentifierInfo *II = OI->getIdentifier();
2401 S += II->getName();
2402 S += '=';
Chris Lattnerf1690852009-03-31 08:48:01 +00002403 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002404 CollectObjCIvars(OI, RecFields);
Chris Lattnerf1690852009-03-31 08:48:01 +00002405 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002406 if (RecFields[i]->isBitField())
2407 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2408 RecFields[i]);
2409 else
2410 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2411 FD);
2412 }
2413 S += '}';
2414 }
2415 else
Steve Narofff69cc5d2008-01-30 19:17:43 +00002416 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002417}
2418
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002419void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002420 std::string& S) const {
2421 if (QT & Decl::OBJC_TQ_In)
2422 S += 'n';
2423 if (QT & Decl::OBJC_TQ_Inout)
2424 S += 'N';
2425 if (QT & Decl::OBJC_TQ_Out)
2426 S += 'o';
2427 if (QT & Decl::OBJC_TQ_Bycopy)
2428 S += 'O';
2429 if (QT & Decl::OBJC_TQ_Byref)
2430 S += 'R';
2431 if (QT & Decl::OBJC_TQ_Oneway)
2432 S += 'V';
2433}
2434
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002435void ASTContext::setBuiltinVaListType(QualType T)
2436{
2437 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
2438
2439 BuiltinVaListType = T;
2440}
2441
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002442void ASTContext::setObjCIdType(TypedefDecl *TD)
Steve Naroff7e219e42007-10-15 14:41:52 +00002443{
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002444 ObjCIdType = getTypedefType(TD);
Steve Naroff7e219e42007-10-15 14:41:52 +00002445
2446 // typedef struct objc_object *id;
2447 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00002448 // User error - caller will issue diagnostics.
2449 if (!ptr)
2450 return;
Steve Naroff7e219e42007-10-15 14:41:52 +00002451 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00002452 // User error - caller will issue diagnostics.
2453 if (!rec)
2454 return;
Steve Naroff7e219e42007-10-15 14:41:52 +00002455 IdStructType = rec;
2456}
2457
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002458void ASTContext::setObjCSelType(TypedefDecl *TD)
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002459{
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002460 ObjCSelType = getTypedefType(TD);
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002461
2462 // typedef struct objc_selector *SEL;
2463 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00002464 if (!ptr)
2465 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002466 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00002467 if (!rec)
2468 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002469 SelStructType = rec;
2470}
2471
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002472void ASTContext::setObjCProtoType(QualType QT)
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00002473{
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002474 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00002475}
2476
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002477void ASTContext::setObjCClassType(TypedefDecl *TD)
Anders Carlsson8baaca52007-10-31 02:53:19 +00002478{
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002479 ObjCClassType = getTypedefType(TD);
Anders Carlsson8baaca52007-10-31 02:53:19 +00002480
2481 // typedef struct objc_class *Class;
2482 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
2483 assert(ptr && "'Class' incorrectly typed");
2484 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
2485 assert(rec && "'Class' incorrectly typed");
2486 ClassStructType = rec;
2487}
2488
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002489void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
2490 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00002491 "'NSConstantString' type already set!");
2492
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002493 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00002494}
2495
Douglas Gregor7532dc62009-03-30 22:58:21 +00002496/// \brief Retrieve the template name that represents a qualified
2497/// template name such as \c std::vector.
2498TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
2499 bool TemplateKeyword,
2500 TemplateDecl *Template) {
2501 llvm::FoldingSetNodeID ID;
2502 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
2503
2504 void *InsertPos = 0;
2505 QualifiedTemplateName *QTN =
2506 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
2507 if (!QTN) {
2508 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
2509 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
2510 }
2511
2512 return TemplateName(QTN);
2513}
2514
2515/// \brief Retrieve the template name that represents a dependent
2516/// template name such as \c MetaFun::template apply.
2517TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
2518 const IdentifierInfo *Name) {
2519 assert(NNS->isDependent() && "Nested name specifier must be dependent");
2520
2521 llvm::FoldingSetNodeID ID;
2522 DependentTemplateName::Profile(ID, NNS, Name);
2523
2524 void *InsertPos = 0;
2525 DependentTemplateName *QTN =
2526 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
2527
2528 if (QTN)
2529 return TemplateName(QTN);
2530
2531 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2532 if (CanonNNS == NNS) {
2533 QTN = new (*this,4) DependentTemplateName(NNS, Name);
2534 } else {
2535 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
2536 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
2537 }
2538
2539 DependentTemplateNames.InsertNode(QTN, InsertPos);
2540 return TemplateName(QTN);
2541}
2542
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002543/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00002544/// TargetInfo, produce the corresponding type. The unsigned @p Type
2545/// is actually a value of type @c TargetInfo::IntType.
2546QualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002547 switch (Type) {
2548 case TargetInfo::NoInt: return QualType();
2549 case TargetInfo::SignedShort: return ShortTy;
2550 case TargetInfo::UnsignedShort: return UnsignedShortTy;
2551 case TargetInfo::SignedInt: return IntTy;
2552 case TargetInfo::UnsignedInt: return UnsignedIntTy;
2553 case TargetInfo::SignedLong: return LongTy;
2554 case TargetInfo::UnsignedLong: return UnsignedLongTy;
2555 case TargetInfo::SignedLongLong: return LongLongTy;
2556 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
2557 }
2558
2559 assert(false && "Unhandled TargetInfo::IntType value");
Daniel Dunbarb3ac5432008-11-11 01:16:00 +00002560 return QualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002561}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00002562
2563//===----------------------------------------------------------------------===//
2564// Type Predicates.
2565//===----------------------------------------------------------------------===//
2566
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00002567/// isObjCNSObjectType - Return true if this is an NSObject object using
2568/// NSObject attribute on a c-style pointer type.
2569/// FIXME - Make it work directly on types.
2570///
2571bool ASTContext::isObjCNSObjectType(QualType Ty) const {
2572 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
2573 if (TypedefDecl *TD = TDT->getDecl())
2574 if (TD->getAttr<ObjCNSObjectAttr>())
2575 return true;
2576 }
2577 return false;
2578}
2579
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00002580/// isObjCObjectPointerType - Returns true if type is an Objective-C pointer
2581/// to an object type. This includes "id" and "Class" (two 'special' pointers
2582/// to struct), Interface* (pointer to ObjCInterfaceType) and id<P> (qualified
2583/// ID type).
2584bool ASTContext::isObjCObjectPointerType(QualType Ty) const {
Steve Naroffd4617772009-02-23 18:36:16 +00002585 if (Ty->isObjCQualifiedIdType())
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00002586 return true;
2587
Steve Naroff6ae98502008-10-21 18:24:04 +00002588 // Blocks are objects.
2589 if (Ty->isBlockPointerType())
2590 return true;
2591
2592 // All other object types are pointers.
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00002593 if (!Ty->isPointerType())
2594 return false;
2595
2596 // Check to see if this is 'id' or 'Class', both of which are typedefs for
2597 // pointer types. This looks for the typedef specifically, not for the
2598 // underlying type.
Eli Friedman5fdeae12009-03-22 23:00:19 +00002599 if (Ty.getUnqualifiedType() == getObjCIdType() ||
2600 Ty.getUnqualifiedType() == getObjCClassType())
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00002601 return true;
2602
2603 // If this a pointer to an interface (e.g. NSString*), it is ok.
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00002604 if (Ty->getAsPointerType()->getPointeeType()->isObjCInterfaceType())
2605 return true;
2606
2607 // If is has NSObject attribute, OK as well.
2608 return isObjCNSObjectType(Ty);
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00002609}
2610
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00002611/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
2612/// garbage collection attribute.
2613///
2614QualType::GCAttrTypes ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
Chris Lattnerb7d25532009-02-18 22:53:11 +00002615 QualType::GCAttrTypes GCAttrs = QualType::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00002616 if (getLangOptions().ObjC1 &&
2617 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00002618 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00002619 // Default behavious under objective-c's gc is for objective-c pointers
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00002620 // (or pointers to them) be treated as though they were declared
2621 // as __strong.
2622 if (GCAttrs == QualType::GCNone) {
2623 if (isObjCObjectPointerType(Ty))
2624 GCAttrs = QualType::Strong;
2625 else if (Ty->isPointerType())
2626 return getObjCGCAttrKind(Ty->getAsPointerType()->getPointeeType());
2627 }
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00002628 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00002629 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00002630}
2631
Chris Lattner6ac46a42008-04-07 06:51:04 +00002632//===----------------------------------------------------------------------===//
2633// Type Compatibility Testing
2634//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00002635
Steve Naroff1c7d0672008-09-04 15:10:53 +00002636/// typesAreBlockCompatible - This routine is called when comparing two
Steve Naroffdd972f22008-09-05 22:11:13 +00002637/// block types. Types must be strictly compatible here. For example,
2638/// C unfortunately doesn't produce an error for the following:
2639///
2640/// int (*emptyArgFunc)();
2641/// int (*intArgList)(int) = emptyArgFunc;
2642///
2643/// For blocks, we will produce an error for the following (similar to C++):
2644///
2645/// int (^emptyArgBlock)();
2646/// int (^intArgBlock)(int) = emptyArgBlock;
2647///
2648/// FIXME: When the dust settles on this integration, fold this into mergeTypes.
2649///
Steve Naroff1c7d0672008-09-04 15:10:53 +00002650bool ASTContext::typesAreBlockCompatible(QualType lhs, QualType rhs) {
Steve Naroffc0febd52008-12-10 17:49:55 +00002651 const FunctionType *lbase = lhs->getAsFunctionType();
2652 const FunctionType *rbase = rhs->getAsFunctionType();
Douglas Gregor72564e72009-02-26 23:50:07 +00002653 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
2654 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Steve Naroffc0febd52008-12-10 17:49:55 +00002655 if (lproto && rproto)
2656 return !mergeTypes(lhs, rhs).isNull();
2657 return false;
Steve Naroff1c7d0672008-09-04 15:10:53 +00002658}
2659
Chris Lattner6ac46a42008-04-07 06:51:04 +00002660/// areCompatVectorTypes - Return true if the two specified vector types are
2661/// compatible.
2662static bool areCompatVectorTypes(const VectorType *LHS,
2663 const VectorType *RHS) {
2664 assert(LHS->isCanonical() && RHS->isCanonical());
2665 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00002666 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00002667}
2668
Eli Friedman3d815e72008-08-22 00:56:42 +00002669/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00002670/// compatible for assignment from RHS to LHS. This handles validation of any
2671/// protocol qualifiers on the LHS or RHS.
2672///
Eli Friedman3d815e72008-08-22 00:56:42 +00002673bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
2674 const ObjCInterfaceType *RHS) {
Chris Lattner6ac46a42008-04-07 06:51:04 +00002675 // Verify that the base decls are compatible: the RHS must be a subclass of
2676 // the LHS.
2677 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
2678 return false;
2679
2680 // RHS must have a superset of the protocols in the LHS. If the LHS is not
2681 // protocol qualified at all, then we are good.
2682 if (!isa<ObjCQualifiedInterfaceType>(LHS))
2683 return true;
2684
2685 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
2686 // isn't a superset.
2687 if (!isa<ObjCQualifiedInterfaceType>(RHS))
2688 return true; // FIXME: should return false!
2689
2690 // Finally, we must have two protocol-qualified interfaces.
2691 const ObjCQualifiedInterfaceType *LHSP =cast<ObjCQualifiedInterfaceType>(LHS);
2692 const ObjCQualifiedInterfaceType *RHSP =cast<ObjCQualifiedInterfaceType>(RHS);
Chris Lattner6ac46a42008-04-07 06:51:04 +00002693
Steve Naroff91b0b0c2009-03-01 16:12:44 +00002694 // All LHS protocols must have a presence on the RHS.
2695 assert(LHSP->qual_begin() != LHSP->qual_end() && "Empty LHS protocol list?");
Chris Lattner6ac46a42008-04-07 06:51:04 +00002696
Steve Naroff91b0b0c2009-03-01 16:12:44 +00002697 for (ObjCQualifiedInterfaceType::qual_iterator LHSPI = LHSP->qual_begin(),
2698 LHSPE = LHSP->qual_end();
2699 LHSPI != LHSPE; LHSPI++) {
2700 bool RHSImplementsProtocol = false;
2701
2702 // If the RHS doesn't implement the protocol on the left, the types
2703 // are incompatible.
2704 for (ObjCQualifiedInterfaceType::qual_iterator RHSPI = RHSP->qual_begin(),
2705 RHSPE = RHSP->qual_end();
2706 !RHSImplementsProtocol && (RHSPI != RHSPE); RHSPI++) {
2707 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier()))
2708 RHSImplementsProtocol = true;
2709 }
2710 // FIXME: For better diagnostics, consider passing back the protocol name.
2711 if (!RHSImplementsProtocol)
2712 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00002713 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00002714 // The RHS implements all protocols listed on the LHS.
2715 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00002716}
2717
Steve Naroff389bf462009-02-12 17:52:19 +00002718bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
2719 // get the "pointed to" types
2720 const PointerType *LHSPT = LHS->getAsPointerType();
2721 const PointerType *RHSPT = RHS->getAsPointerType();
2722
2723 if (!LHSPT || !RHSPT)
2724 return false;
2725
2726 QualType lhptee = LHSPT->getPointeeType();
2727 QualType rhptee = RHSPT->getPointeeType();
2728 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2729 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2730 // ID acts sort of like void* for ObjC interfaces
2731 if (LHSIface && isObjCIdStructType(rhptee))
2732 return true;
2733 if (RHSIface && isObjCIdStructType(lhptee))
2734 return true;
2735 if (!LHSIface || !RHSIface)
2736 return false;
2737 return canAssignObjCInterfaces(LHSIface, RHSIface) ||
2738 canAssignObjCInterfaces(RHSIface, LHSIface);
2739}
2740
Steve Naroffec0550f2007-10-15 20:41:53 +00002741/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
2742/// both shall have the identically qualified version of a compatible type.
2743/// C99 6.2.7p1: Two types have compatible types if their types are the
2744/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman3d815e72008-08-22 00:56:42 +00002745bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
2746 return !mergeTypes(LHS, RHS).isNull();
2747}
2748
2749QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
2750 const FunctionType *lbase = lhs->getAsFunctionType();
2751 const FunctionType *rbase = rhs->getAsFunctionType();
Douglas Gregor72564e72009-02-26 23:50:07 +00002752 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
2753 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00002754 bool allLTypes = true;
2755 bool allRTypes = true;
2756
2757 // Check return type
2758 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
2759 if (retType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00002760 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
2761 allLTypes = false;
2762 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
2763 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00002764
2765 if (lproto && rproto) { // two C99 style function prototypes
2766 unsigned lproto_nargs = lproto->getNumArgs();
2767 unsigned rproto_nargs = rproto->getNumArgs();
2768
2769 // Compatible functions must have the same number of arguments
2770 if (lproto_nargs != rproto_nargs)
2771 return QualType();
2772
2773 // Variadic and non-variadic functions aren't compatible
2774 if (lproto->isVariadic() != rproto->isVariadic())
2775 return QualType();
2776
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002777 if (lproto->getTypeQuals() != rproto->getTypeQuals())
2778 return QualType();
2779
Eli Friedman3d815e72008-08-22 00:56:42 +00002780 // Check argument compatibility
2781 llvm::SmallVector<QualType, 10> types;
2782 for (unsigned i = 0; i < lproto_nargs; i++) {
2783 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
2784 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
2785 QualType argtype = mergeTypes(largtype, rargtype);
2786 if (argtype.isNull()) return QualType();
2787 types.push_back(argtype);
Chris Lattner61710852008-10-05 17:34:18 +00002788 if (getCanonicalType(argtype) != getCanonicalType(largtype))
2789 allLTypes = false;
2790 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
2791 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00002792 }
2793 if (allLTypes) return lhs;
2794 if (allRTypes) return rhs;
2795 return getFunctionType(retType, types.begin(), types.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002796 lproto->isVariadic(), lproto->getTypeQuals());
Eli Friedman3d815e72008-08-22 00:56:42 +00002797 }
2798
2799 if (lproto) allRTypes = false;
2800 if (rproto) allLTypes = false;
2801
Douglas Gregor72564e72009-02-26 23:50:07 +00002802 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00002803 if (proto) {
2804 if (proto->isVariadic()) return QualType();
2805 // Check that the types are compatible with the types that
2806 // would result from default argument promotions (C99 6.7.5.3p15).
2807 // The only types actually affected are promotable integer
2808 // types and floats, which would be passed as a different
2809 // type depending on whether the prototype is visible.
2810 unsigned proto_nargs = proto->getNumArgs();
2811 for (unsigned i = 0; i < proto_nargs; ++i) {
2812 QualType argTy = proto->getArgType(i);
2813 if (argTy->isPromotableIntegerType() ||
2814 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
2815 return QualType();
2816 }
2817
2818 if (allLTypes) return lhs;
2819 if (allRTypes) return rhs;
2820 return getFunctionType(retType, proto->arg_type_begin(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002821 proto->getNumArgs(), lproto->isVariadic(),
2822 lproto->getTypeQuals());
Eli Friedman3d815e72008-08-22 00:56:42 +00002823 }
2824
2825 if (allLTypes) return lhs;
2826 if (allRTypes) return rhs;
Douglas Gregor72564e72009-02-26 23:50:07 +00002827 return getFunctionNoProtoType(retType);
Eli Friedman3d815e72008-08-22 00:56:42 +00002828}
2829
2830QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
Bill Wendling43d69752007-12-03 07:33:35 +00002831 // C++ [expr]: If an expression initially has the type "reference to T", the
2832 // type is adjusted to "T" prior to any further analysis, the expression
2833 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002834 // expression is an lvalue unless the reference is an rvalue reference and
2835 // the expression is a function call (possibly inside parentheses).
Eli Friedman3d815e72008-08-22 00:56:42 +00002836 // FIXME: C++ shouldn't be going through here! The rules are different
2837 // enough that they should be handled separately.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002838 // FIXME: Merging of lvalue and rvalue references is incorrect. C++ *really*
2839 // shouldn't be going through here!
Eli Friedman3d815e72008-08-22 00:56:42 +00002840 if (const ReferenceType *RT = LHS->getAsReferenceType())
Chris Lattnerc4e40592008-04-07 04:07:56 +00002841 LHS = RT->getPointeeType();
Eli Friedman3d815e72008-08-22 00:56:42 +00002842 if (const ReferenceType *RT = RHS->getAsReferenceType())
Chris Lattnerc4e40592008-04-07 04:07:56 +00002843 RHS = RT->getPointeeType();
Chris Lattnerf3692dc2008-04-07 05:37:56 +00002844
Eli Friedman3d815e72008-08-22 00:56:42 +00002845 QualType LHSCan = getCanonicalType(LHS),
2846 RHSCan = getCanonicalType(RHS);
2847
2848 // If two types are identical, they are compatible.
2849 if (LHSCan == RHSCan)
2850 return LHS;
2851
2852 // If the qualifiers are different, the types aren't compatible
Eli Friedman5a61f0e2009-02-27 23:04:43 +00002853 // Note that we handle extended qualifiers later, in the
2854 // case for ExtQualType.
2855 if (LHSCan.getCVRQualifiers() != RHSCan.getCVRQualifiers())
Eli Friedman3d815e72008-08-22 00:56:42 +00002856 return QualType();
2857
2858 Type::TypeClass LHSClass = LHSCan->getTypeClass();
2859 Type::TypeClass RHSClass = RHSCan->getTypeClass();
2860
Chris Lattner1adb8832008-01-14 05:45:46 +00002861 // We want to consider the two function types to be the same for these
2862 // comparisons, just force one to the other.
2863 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
2864 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00002865
2866 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00002867 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
2868 LHSClass = Type::ConstantArray;
2869 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
2870 RHSClass = Type::ConstantArray;
Steve Naroffec0550f2007-10-15 20:41:53 +00002871
Nate Begeman213541a2008-04-18 23:10:10 +00002872 // Canonicalize ExtVector -> Vector.
2873 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
2874 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Chris Lattnera36a61f2008-04-07 05:43:21 +00002875
Chris Lattnerb0489812008-04-07 06:38:24 +00002876 // Consider qualified interfaces and interfaces the same.
2877 if (LHSClass == Type::ObjCQualifiedInterface) LHSClass = Type::ObjCInterface;
2878 if (RHSClass == Type::ObjCQualifiedInterface) RHSClass = Type::ObjCInterface;
Eli Friedman3d815e72008-08-22 00:56:42 +00002879
Chris Lattnera36a61f2008-04-07 05:43:21 +00002880 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00002881 if (LHSClass != RHSClass) {
Steve Naroff5fd659d2009-02-21 16:18:07 +00002882 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
2883 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
2884
2885 // ID acts sort of like void* for ObjC interfaces
2886 if (LHSIface && isObjCIdStructType(RHS))
2887 return LHS;
2888 if (RHSIface && isObjCIdStructType(LHS))
2889 return RHS;
2890
Steve Naroffbc76dd02008-12-10 22:14:21 +00002891 // ID is compatible with all qualified id types.
2892 if (LHS->isObjCQualifiedIdType()) {
2893 if (const PointerType *PT = RHS->getAsPointerType()) {
2894 QualType pType = PT->getPointeeType();
Steve Naroff389bf462009-02-12 17:52:19 +00002895 if (isObjCIdStructType(pType))
Steve Naroffbc76dd02008-12-10 22:14:21 +00002896 return LHS;
2897 // FIXME: need to use ObjCQualifiedIdTypesAreCompatible(LHS, RHS, true).
2898 // Unfortunately, this API is part of Sema (which we don't have access
2899 // to. Need to refactor. The following check is insufficient, since we
2900 // need to make sure the class implements the protocol.
2901 if (pType->isObjCInterfaceType())
2902 return LHS;
2903 }
2904 }
2905 if (RHS->isObjCQualifiedIdType()) {
2906 if (const PointerType *PT = LHS->getAsPointerType()) {
2907 QualType pType = PT->getPointeeType();
Steve Naroff389bf462009-02-12 17:52:19 +00002908 if (isObjCIdStructType(pType))
Steve Naroffbc76dd02008-12-10 22:14:21 +00002909 return RHS;
2910 // FIXME: need to use ObjCQualifiedIdTypesAreCompatible(LHS, RHS, true).
2911 // Unfortunately, this API is part of Sema (which we don't have access
2912 // to. Need to refactor. The following check is insufficient, since we
2913 // need to make sure the class implements the protocol.
2914 if (pType->isObjCInterfaceType())
2915 return RHS;
2916 }
2917 }
Chris Lattner1adb8832008-01-14 05:45:46 +00002918 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
2919 // a signed integer type, or an unsigned integer type.
Eli Friedman3d815e72008-08-22 00:56:42 +00002920 if (const EnumType* ETy = LHS->getAsEnumType()) {
2921 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
2922 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00002923 }
Eli Friedman3d815e72008-08-22 00:56:42 +00002924 if (const EnumType* ETy = RHS->getAsEnumType()) {
2925 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
2926 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00002927 }
Chris Lattner1adb8832008-01-14 05:45:46 +00002928
Eli Friedman3d815e72008-08-22 00:56:42 +00002929 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00002930 }
Eli Friedman3d815e72008-08-22 00:56:42 +00002931
Steve Naroff4a746782008-01-09 22:43:08 +00002932 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00002933 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00002934#define TYPE(Class, Base)
2935#define ABSTRACT_TYPE(Class, Base)
2936#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2937#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2938#include "clang/AST/TypeNodes.def"
2939 assert(false && "Non-canonical and dependent types shouldn't get here");
2940 return QualType();
2941
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002942 case Type::LValueReference:
2943 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00002944 case Type::MemberPointer:
2945 assert(false && "C++ should never be in mergeTypes");
2946 return QualType();
2947
2948 case Type::IncompleteArray:
2949 case Type::VariableArray:
2950 case Type::FunctionProto:
2951 case Type::ExtVector:
2952 case Type::ObjCQualifiedInterface:
2953 assert(false && "Types are eliminated above");
2954 return QualType();
2955
Chris Lattner1adb8832008-01-14 05:45:46 +00002956 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00002957 {
2958 // Merge two pointer types, while trying to preserve typedef info
2959 QualType LHSPointee = LHS->getAsPointerType()->getPointeeType();
2960 QualType RHSPointee = RHS->getAsPointerType()->getPointeeType();
2961 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
2962 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00002963 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
2964 return LHS;
2965 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
2966 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00002967 return getPointerType(ResultType);
2968 }
Steve Naroffc0febd52008-12-10 17:49:55 +00002969 case Type::BlockPointer:
2970 {
2971 // Merge two block pointer types, while trying to preserve typedef info
2972 QualType LHSPointee = LHS->getAsBlockPointerType()->getPointeeType();
2973 QualType RHSPointee = RHS->getAsBlockPointerType()->getPointeeType();
2974 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
2975 if (ResultType.isNull()) return QualType();
2976 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
2977 return LHS;
2978 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
2979 return RHS;
2980 return getBlockPointerType(ResultType);
2981 }
Chris Lattner1adb8832008-01-14 05:45:46 +00002982 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00002983 {
2984 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
2985 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
2986 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
2987 return QualType();
2988
2989 QualType LHSElem = getAsArrayType(LHS)->getElementType();
2990 QualType RHSElem = getAsArrayType(RHS)->getElementType();
2991 QualType ResultType = mergeTypes(LHSElem, RHSElem);
2992 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00002993 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
2994 return LHS;
2995 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
2996 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00002997 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
2998 ArrayType::ArraySizeModifier(), 0);
2999 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
3000 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00003001 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
3002 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00003003 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3004 return LHS;
3005 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3006 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00003007 if (LVAT) {
3008 // FIXME: This isn't correct! But tricky to implement because
3009 // the array's size has to be the size of LHS, but the type
3010 // has to be different.
3011 return LHS;
3012 }
3013 if (RVAT) {
3014 // FIXME: This isn't correct! But tricky to implement because
3015 // the array's size has to be the size of RHS, but the type
3016 // has to be different.
3017 return RHS;
3018 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00003019 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
3020 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Chris Lattner61710852008-10-05 17:34:18 +00003021 return getIncompleteArrayType(ResultType, ArrayType::ArraySizeModifier(),0);
Eli Friedman3d815e72008-08-22 00:56:42 +00003022 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003023 case Type::FunctionNoProto:
Eli Friedman3d815e72008-08-22 00:56:42 +00003024 return mergeFunctionTypes(LHS, RHS);
Douglas Gregor72564e72009-02-26 23:50:07 +00003025 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00003026 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00003027 // FIXME: Why are these compatible?
Steve Naroff389bf462009-02-12 17:52:19 +00003028 if (isObjCIdStructType(LHS) && isObjCClassStructType(RHS)) return LHS;
3029 if (isObjCClassStructType(LHS) && isObjCIdStructType(RHS)) return LHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00003030 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00003031 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00003032 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00003033 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00003034 case Type::Complex:
3035 // Distinct complex types are incompatible.
3036 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00003037 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003038 // FIXME: The merged type should be an ExtVector!
Eli Friedman3d815e72008-08-22 00:56:42 +00003039 if (areCompatVectorTypes(LHS->getAsVectorType(), RHS->getAsVectorType()))
3040 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00003041 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00003042 case Type::ObjCInterface: {
Steve Naroff5fd659d2009-02-21 16:18:07 +00003043 // Check if the interfaces are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003044 // FIXME: This should be type compatibility, e.g. whether
3045 // "LHS x; RHS x;" at global scope is legal.
Steve Naroff5fd659d2009-02-21 16:18:07 +00003046 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
3047 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
3048 if (LHSIface && RHSIface &&
3049 canAssignObjCInterfaces(LHSIface, RHSIface))
3050 return LHS;
3051
Eli Friedman3d815e72008-08-22 00:56:42 +00003052 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00003053 }
Steve Naroffbc76dd02008-12-10 22:14:21 +00003054 case Type::ObjCQualifiedId:
3055 // Distinct qualified id's are not compatible.
3056 return QualType();
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003057 case Type::FixedWidthInt:
3058 // Distinct fixed-width integers are not compatible.
3059 return QualType();
3060 case Type::ObjCQualifiedClass:
3061 // Distinct qualified classes are not compatible.
3062 return QualType();
3063 case Type::ExtQual:
3064 // FIXME: ExtQual types can be compatible even if they're not
3065 // identical!
3066 return QualType();
3067 // First attempt at an implementation, but I'm not really sure it's
3068 // right...
3069#if 0
3070 ExtQualType* LQual = cast<ExtQualType>(LHSCan);
3071 ExtQualType* RQual = cast<ExtQualType>(RHSCan);
3072 if (LQual->getAddressSpace() != RQual->getAddressSpace() ||
3073 LQual->getObjCGCAttr() != RQual->getObjCGCAttr())
3074 return QualType();
3075 QualType LHSBase, RHSBase, ResultType, ResCanUnqual;
3076 LHSBase = QualType(LQual->getBaseType(), 0);
3077 RHSBase = QualType(RQual->getBaseType(), 0);
3078 ResultType = mergeTypes(LHSBase, RHSBase);
3079 if (ResultType.isNull()) return QualType();
3080 ResCanUnqual = getCanonicalType(ResultType).getUnqualifiedType();
3081 if (LHSCan.getUnqualifiedType() == ResCanUnqual)
3082 return LHS;
3083 if (RHSCan.getUnqualifiedType() == ResCanUnqual)
3084 return RHS;
3085 ResultType = getAddrSpaceQualType(ResultType, LQual->getAddressSpace());
3086 ResultType = getObjCGCQualType(ResultType, LQual->getObjCGCAttr());
3087 ResultType.setCVRQualifiers(LHSCan.getCVRQualifiers());
3088 return ResultType;
3089#endif
Douglas Gregor7532dc62009-03-30 22:58:21 +00003090
3091 case Type::TemplateSpecialization:
3092 assert(false && "Dependent types have no size");
3093 break;
Steve Naroffec0550f2007-10-15 20:41:53 +00003094 }
Douglas Gregor72564e72009-02-26 23:50:07 +00003095
3096 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00003097}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00003098
Chris Lattner5426bf62008-04-07 07:01:58 +00003099//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00003100// Integer Predicates
3101//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00003102
Eli Friedmanad74a752008-06-28 06:23:08 +00003103unsigned ASTContext::getIntWidth(QualType T) {
3104 if (T == BoolTy)
3105 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00003106 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T)) {
3107 return FWIT->getWidth();
3108 }
3109 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00003110 return (unsigned)getTypeSize(T);
3111}
3112
3113QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
3114 assert(T->isSignedIntegerType() && "Unexpected type");
3115 if (const EnumType* ETy = T->getAsEnumType())
3116 T = ETy->getDecl()->getIntegerType();
3117 const BuiltinType* BTy = T->getAsBuiltinType();
3118 assert (BTy && "Unexpected signed integer type");
3119 switch (BTy->getKind()) {
3120 case BuiltinType::Char_S:
3121 case BuiltinType::SChar:
3122 return UnsignedCharTy;
3123 case BuiltinType::Short:
3124 return UnsignedShortTy;
3125 case BuiltinType::Int:
3126 return UnsignedIntTy;
3127 case BuiltinType::Long:
3128 return UnsignedLongTy;
3129 case BuiltinType::LongLong:
3130 return UnsignedLongLongTy;
3131 default:
3132 assert(0 && "Unexpected signed integer type");
3133 return QualType();
3134 }
3135}
3136
3137
3138//===----------------------------------------------------------------------===//
Chris Lattner5426bf62008-04-07 07:01:58 +00003139// Serialization Support
3140//===----------------------------------------------------------------------===//
3141
Chris Lattnera9376d42009-03-28 03:45:20 +00003142enum {
3143 BasicMetadataBlock = 1,
3144 ASTContextBlock = 2,
3145 DeclsBlock = 3
3146};
3147
Chris Lattner557c5b12009-03-28 04:27:18 +00003148void ASTContext::EmitASTBitcodeBuffer(std::vector<unsigned char> &Buffer) const{
3149 // Create bitstream.
3150 llvm::BitstreamWriter Stream(Buffer);
3151
3152 // Emit the preamble.
3153 Stream.Emit((unsigned)'B', 8);
3154 Stream.Emit((unsigned)'C', 8);
3155 Stream.Emit(0xC, 4);
3156 Stream.Emit(0xF, 4);
3157 Stream.Emit(0xE, 4);
3158 Stream.Emit(0x0, 4);
3159
3160 // Create serializer.
3161 llvm::Serializer S(Stream);
3162
Chris Lattnera9376d42009-03-28 03:45:20 +00003163 // ===---------------------------------------------------===/
3164 // Serialize the "Translation Unit" metadata.
3165 // ===---------------------------------------------------===/
3166
3167 // Emit ASTContext.
3168 S.EnterBlock(ASTContextBlock);
3169 S.EmitOwnedPtr(this);
3170 S.ExitBlock(); // exit "ASTContextBlock"
3171
3172 S.EnterBlock(BasicMetadataBlock);
3173
3174 // Block for SourceManager and Target. Allows easy skipping
3175 // around to the block for the Selectors during deserialization.
3176 S.EnterBlock();
3177
3178 // Emit the SourceManager.
3179 S.Emit(getSourceManager());
3180
3181 // Emit the Target.
3182 S.EmitPtr(&Target);
3183 S.EmitCStr(Target.getTargetTriple());
3184
3185 S.ExitBlock(); // exit "SourceManager and Target Block"
3186
3187 // Emit the Selectors.
3188 S.Emit(Selectors);
3189
3190 // Emit the Identifier Table.
3191 S.Emit(Idents);
3192
3193 S.ExitBlock(); // exit "BasicMetadataBlock"
3194}
3195
3196
Ted Kremenek7192f8e2007-10-31 17:10:13 +00003197/// Emit - Serialize an ASTContext object to Bitcode.
3198void ASTContext::Emit(llvm::Serializer& S) const {
Ted Kremeneke7d07d12008-06-04 15:55:15 +00003199 S.Emit(LangOpts);
Ted Kremenek54513502007-10-31 20:00:03 +00003200 S.EmitRef(SourceMgr);
3201 S.EmitRef(Target);
3202 S.EmitRef(Idents);
3203 S.EmitRef(Selectors);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00003204
Ted Kremenekfee04522007-10-31 22:44:07 +00003205 // Emit the size of the type vector so that we can reserve that size
3206 // when we reconstitute the ASTContext object.
Ted Kremeneka4559c32007-11-06 22:26:16 +00003207 S.EmitInt(Types.size());
3208
Ted Kremenek03ed4402007-11-13 22:02:55 +00003209 for (std::vector<Type*>::const_iterator I=Types.begin(), E=Types.end();
3210 I!=E;++I)
3211 (*I)->Emit(S);
Ted Kremeneka4559c32007-11-06 22:26:16 +00003212
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003213 S.EmitOwnedPtr(TUDecl);
3214
Ted Kremeneka9a4a242007-11-01 18:11:32 +00003215 // FIXME: S.EmitOwnedPtr(CFConstantStringTypeDecl);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00003216}
3217
Chris Lattner557c5b12009-03-28 04:27:18 +00003218
3219ASTContext *ASTContext::ReadASTBitcodeBuffer(llvm::MemoryBuffer &Buffer,
3220 FileManager &FMgr) {
3221 // Check if the file is of the proper length.
3222 if (Buffer.getBufferSize() & 0x3) {
3223 // FIXME: Provide diagnostic: "Length should be a multiple of 4 bytes."
3224 return 0;
3225 }
3226
3227 // Create the bitstream reader.
3228 unsigned char *BufPtr = (unsigned char *)Buffer.getBufferStart();
3229 llvm::BitstreamReader Stream(BufPtr, BufPtr+Buffer.getBufferSize());
3230
3231 if (Stream.Read(8) != 'B' ||
3232 Stream.Read(8) != 'C' ||
3233 Stream.Read(4) != 0xC ||
3234 Stream.Read(4) != 0xF ||
3235 Stream.Read(4) != 0xE ||
3236 Stream.Read(4) != 0x0) {
3237 // FIXME: Provide diagnostic.
3238 return NULL;
3239 }
3240
3241 // Create the deserializer.
3242 llvm::Deserializer Dezr(Stream);
3243
Chris Lattnera9376d42009-03-28 03:45:20 +00003244 // ===---------------------------------------------------===/
3245 // Deserialize the "Translation Unit" metadata.
3246 // ===---------------------------------------------------===/
3247
3248 // Skip to the BasicMetaDataBlock. First jump to ASTContextBlock
3249 // (which will appear earlier) and record its location.
3250
3251 bool FoundBlock = Dezr.SkipToBlock(ASTContextBlock);
3252 assert (FoundBlock);
3253
3254 llvm::Deserializer::Location ASTContextBlockLoc =
3255 Dezr.getCurrentBlockLocation();
3256
3257 FoundBlock = Dezr.SkipToBlock(BasicMetadataBlock);
3258 assert (FoundBlock);
3259
3260 // Read the SourceManager.
3261 SourceManager::CreateAndRegister(Dezr, FMgr);
3262
3263 { // Read the TargetInfo.
3264 llvm::SerializedPtrID PtrID = Dezr.ReadPtrID();
3265 char* triple = Dezr.ReadCStr(NULL,0,true);
3266 Dezr.RegisterPtr(PtrID, TargetInfo::CreateTargetInfo(std::string(triple)));
3267 delete [] triple;
3268 }
3269
3270 // For Selectors, we must read the identifier table first because the
3271 // SelectorTable depends on the identifiers being already deserialized.
3272 llvm::Deserializer::Location SelectorBlkLoc = Dezr.getCurrentBlockLocation();
3273 Dezr.SkipBlock();
3274
3275 // Read the identifier table.
3276 IdentifierTable::CreateAndRegister(Dezr);
3277
3278 // Now jump back and read the selectors.
3279 Dezr.JumpTo(SelectorBlkLoc);
3280 SelectorTable::CreateAndRegister(Dezr);
3281
3282 // Now jump back to ASTContextBlock and read the ASTContext.
3283 Dezr.JumpTo(ASTContextBlockLoc);
3284 return Dezr.ReadOwnedPtr<ASTContext>();
3285}
3286
Ted Kremenek0f84c002007-11-13 00:25:37 +00003287ASTContext* ASTContext::Create(llvm::Deserializer& D) {
Ted Kremeneke7d07d12008-06-04 15:55:15 +00003288
3289 // Read the language options.
3290 LangOptions LOpts;
3291 LOpts.Read(D);
3292
Ted Kremenekfee04522007-10-31 22:44:07 +00003293 SourceManager &SM = D.ReadRef<SourceManager>();
3294 TargetInfo &t = D.ReadRef<TargetInfo>();
3295 IdentifierTable &idents = D.ReadRef<IdentifierTable>();
3296 SelectorTable &sels = D.ReadRef<SelectorTable>();
Chris Lattner0ed844b2008-04-04 06:12:32 +00003297
Ted Kremenekfee04522007-10-31 22:44:07 +00003298 unsigned size_reserve = D.ReadInt();
3299
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003300 ASTContext* A = new ASTContext(LOpts, SM, t, idents, sels,
3301 size_reserve);
Ted Kremenekfee04522007-10-31 22:44:07 +00003302
Ted Kremenek03ed4402007-11-13 22:02:55 +00003303 for (unsigned i = 0; i < size_reserve; ++i)
3304 Type::Create(*A,i,D);
Chris Lattner0ed844b2008-04-04 06:12:32 +00003305
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003306 A->TUDecl = cast<TranslationUnitDecl>(D.ReadOwnedPtr<Decl>(*A));
3307
Ted Kremeneka9a4a242007-11-01 18:11:32 +00003308 // FIXME: A->CFConstantStringTypeDecl = D.ReadOwnedPtr<RecordDecl>();
Ted Kremenekfee04522007-10-31 22:44:07 +00003309
3310 return A;
3311}