blob: 4f78ad9800a2a9320c41e4e0c2e1e32fe28a0bbb [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"
Douglas Gregor2cf26342009-04-09 22:27:44 +000019#include "clang/AST/ExternalASTSource.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000020#include "clang/AST/RecordLayout.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000021#include "clang/Basic/Builtins.h"
Chris Lattnera9376d42009-03-28 03:45:20 +000022#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000023#include "clang/Basic/TargetInfo.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000024#include "llvm/ADT/StringExtras.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,
Chris Lattner1b63e4f2009-06-14 01:54:56 +000036 Builtin::Context &builtins,
37 bool FreeMem, unsigned size_reserve) :
Douglas Gregorab452ba2009-03-26 23:50:42 +000038 GlobalNestedNameSpecifier(0), CFConstantStringTypeDecl(0),
39 ObjCFastEnumerationStateTypeDecl(0), SourceMgr(SM), LangOpts(LOpts),
Douglas Gregor2cf26342009-04-09 22:27:44 +000040 FreeMemory(FreeMem), Target(t), Idents(idents), Selectors(sels),
Chris Lattnere4f21422009-06-30 01:26:17 +000041 BuiltinInfo(builtins), ExternalSource(0), PrintingPolicy(LOpts) {
Daniel Dunbare91593e2008-08-11 04:54:23 +000042 if (size_reserve > 0) Types.reserve(size_reserve);
43 InitBuiltinTypes();
Daniel Dunbare91593e2008-08-11 04:54:23 +000044 TUDecl = TranslationUnitDecl::Create(*this);
45}
46
Reid Spencer5f016e22007-07-11 17:01:13 +000047ASTContext::~ASTContext() {
48 // Deallocate all the types.
49 while (!Types.empty()) {
Ted Kremenek4b05b1d2008-05-21 16:38:54 +000050 Types.back()->Destroy(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +000051 Types.pop_back();
52 }
Eli Friedmanb26153c2008-05-27 03:08:09 +000053
Nuno Lopesb74668e2008-12-17 22:30:25 +000054 {
55 llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
56 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end();
57 while (I != E) {
58 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
59 delete R;
60 }
61 }
62
63 {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +000064 llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>::iterator
65 I = ObjCLayouts.begin(), E = ObjCLayouts.end();
Nuno Lopesb74668e2008-12-17 22:30:25 +000066 while (I != E) {
67 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
68 delete R;
69 }
70 }
71
Douglas Gregorab452ba2009-03-26 23:50:42 +000072 // Destroy nested-name-specifiers.
Douglas Gregor1ae0afa2009-03-27 23:54:10 +000073 for (llvm::FoldingSet<NestedNameSpecifier>::iterator
74 NNS = NestedNameSpecifiers.begin(),
75 NNSEnd = NestedNameSpecifiers.end();
Douglas Gregore7dcd782009-03-27 23:25:45 +000076 NNS != NNSEnd;
Douglas Gregor1ae0afa2009-03-27 23:54:10 +000077 /* Increment in loop */)
78 (*NNS++).Destroy(*this);
Douglas Gregorab452ba2009-03-26 23:50:42 +000079
80 if (GlobalNestedNameSpecifier)
81 GlobalNestedNameSpecifier->Destroy(*this);
82
Eli Friedmanb26153c2008-05-27 03:08:09 +000083 TUDecl->Destroy(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +000084}
85
Douglas Gregor2cf26342009-04-09 22:27:44 +000086void
87ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
88 ExternalSource.reset(Source.take());
89}
90
Reid Spencer5f016e22007-07-11 17:01:13 +000091void ASTContext::PrintStats() const {
92 fprintf(stderr, "*** AST Context Stats:\n");
93 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl7c80bd62009-03-16 23:22:08 +000094
Douglas Gregordbe833d2009-05-26 14:40:08 +000095 unsigned counts[] = {
96#define TYPE(Name, Parent) 0,
97#define ABSTRACT_TYPE(Name, Parent)
98#include "clang/AST/TypeNodes.def"
99 0 // Extra
100 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000101
Reid Spencer5f016e22007-07-11 17:01:13 +0000102 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
103 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000104 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000105 }
106
Douglas Gregordbe833d2009-05-26 14:40:08 +0000107 unsigned Idx = 0;
108 unsigned TotalBytes = 0;
109#define TYPE(Name, Parent) \
110 if (counts[Idx]) \
111 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
112 TotalBytes += counts[Idx] * sizeof(Name##Type); \
113 ++Idx;
114#define ABSTRACT_TYPE(Name, Parent)
115#include "clang/AST/TypeNodes.def"
116
117 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregor2cf26342009-04-09 22:27:44 +0000118
119 if (ExternalSource.get()) {
120 fprintf(stderr, "\n");
121 ExternalSource->PrintStats();
122 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000123}
124
125
126void ASTContext::InitBuiltinType(QualType &R, BuiltinType::Kind K) {
Steve Narofff83820b2009-01-27 22:08:43 +0000127 Types.push_back((R = QualType(new (*this,8) BuiltinType(K),0)).getTypePtr());
Reid Spencer5f016e22007-07-11 17:01:13 +0000128}
129
Reid Spencer5f016e22007-07-11 17:01:13 +0000130void ASTContext::InitBuiltinTypes() {
131 assert(VoidTy.isNull() && "Context reinitialized?");
132
133 // C99 6.2.5p19.
134 InitBuiltinType(VoidTy, BuiltinType::Void);
135
136 // C99 6.2.5p2.
137 InitBuiltinType(BoolTy, BuiltinType::Bool);
138 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000139 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000140 InitBuiltinType(CharTy, BuiltinType::Char_S);
141 else
142 InitBuiltinType(CharTy, BuiltinType::Char_U);
143 // C99 6.2.5p4.
144 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
145 InitBuiltinType(ShortTy, BuiltinType::Short);
146 InitBuiltinType(IntTy, BuiltinType::Int);
147 InitBuiltinType(LongTy, BuiltinType::Long);
148 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
149
150 // C99 6.2.5p6.
151 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
152 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
153 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
154 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
155 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
156
157 // C99 6.2.5p10.
158 InitBuiltinType(FloatTy, BuiltinType::Float);
159 InitBuiltinType(DoubleTy, BuiltinType::Double);
160 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000161
Chris Lattner2df9ced2009-04-30 02:43:43 +0000162 // GNU extension, 128-bit integers.
163 InitBuiltinType(Int128Ty, BuiltinType::Int128);
164 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
165
Chris Lattner3a250322009-02-26 23:43:47 +0000166 if (LangOpts.CPlusPlus) // C++ 3.9.1p5
167 InitBuiltinType(WCharTy, BuiltinType::WChar);
168 else // C99
169 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000170
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000171 // Placeholder type for functions.
Douglas Gregor898574e2008-12-05 23:32:09 +0000172 InitBuiltinType(OverloadTy, BuiltinType::Overload);
173
174 // Placeholder type for type-dependent expressions whose type is
175 // completely unknown. No code should ever check a type against
176 // DependentTy and users should never see it; however, it is here to
177 // help diagnose failures to properly check for type-dependent
178 // expressions.
179 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000180
Anders Carlssone89d1592009-06-26 18:41:36 +0000181 // Placeholder type for C++0x auto declarations whose real type has
182 // not yet been deduced.
183 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
184
Reid Spencer5f016e22007-07-11 17:01:13 +0000185 // C99 6.2.5p11.
186 FloatComplexTy = getComplexType(FloatTy);
187 DoubleComplexTy = getComplexType(DoubleTy);
188 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000189
Steve Naroff7e219e42007-10-15 14:41:52 +0000190 BuiltinVaListType = QualType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000191 ObjCIdType = QualType();
Steve Naroff7e219e42007-10-15 14:41:52 +0000192 IdStructType = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000193 ObjCClassType = QualType();
Anders Carlsson8baaca52007-10-31 02:53:19 +0000194 ClassStructType = 0;
195
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000196 ObjCConstantStringType = QualType();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000197
198 // void * type
199 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000200
201 // nullptr type (C++0x 2.14.7)
202 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000203}
204
Chris Lattner464175b2007-07-18 17:52:12 +0000205//===----------------------------------------------------------------------===//
206// Type Sizing and Analysis
207//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000208
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000209/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
210/// scalar floating point type.
211const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
212 const BuiltinType *BT = T->getAsBuiltinType();
213 assert(BT && "Not a floating point type!");
214 switch (BT->getKind()) {
215 default: assert(0 && "Not a floating point type!");
216 case BuiltinType::Float: return Target.getFloatFormat();
217 case BuiltinType::Double: return Target.getDoubleFormat();
218 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
219 }
220}
221
Chris Lattneraf707ab2009-01-24 21:53:27 +0000222/// getDeclAlign - Return a conservative estimate of the alignment of the
223/// specified decl. Note that bitfields do not have a valid alignment, so
224/// this method will assert on them.
Daniel Dunbarb7d08442009-02-17 22:16:19 +0000225unsigned ASTContext::getDeclAlignInBytes(const Decl *D) {
Eli Friedmandcdafb62009-02-22 02:56:25 +0000226 unsigned Align = Target.getCharWidth();
227
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000228 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
Eli Friedmandcdafb62009-02-22 02:56:25 +0000229 Align = std::max(Align, AA->getAlignment());
230
Chris Lattneraf707ab2009-01-24 21:53:27 +0000231 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
232 QualType T = VD->getType();
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000233 if (const ReferenceType* RT = T->getAsReferenceType()) {
234 unsigned AS = RT->getPointeeType().getAddressSpace();
Anders Carlssonf0930232009-04-10 04:52:36 +0000235 Align = Target.getPointerAlign(AS);
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000236 } else if (!T->isIncompleteType() && !T->isFunctionType()) {
237 // Incomplete or function types default to 1.
Eli Friedmandcdafb62009-02-22 02:56:25 +0000238 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
239 T = cast<ArrayType>(T)->getElementType();
240
241 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
242 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000243 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000244
245 return Align / Target.getCharWidth();
Chris Lattneraf707ab2009-01-24 21:53:27 +0000246}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000247
Chris Lattnera7674d82007-07-13 22:13:22 +0000248/// getTypeSize - Return the size of the specified type, in bits. This method
249/// does not work on incomplete types.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000250std::pair<uint64_t, unsigned>
Daniel Dunbar1d751182008-11-08 05:48:37 +0000251ASTContext::getTypeInfo(const Type *T) {
Mike Stump5e301002009-02-27 18:32:39 +0000252 uint64_t Width=0;
253 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000254 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000255#define TYPE(Class, Base)
256#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000257#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000258#define DEPENDENT_TYPE(Class, Base) case Type::Class:
259#include "clang/AST/TypeNodes.def"
Douglas Gregor18857642009-04-30 17:32:17 +0000260 assert(false && "Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000261 break;
262
Chris Lattner692233e2007-07-13 22:27:08 +0000263 case Type::FunctionNoProto:
264 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000265 // GCC extension: alignof(function) = 32 bits
266 Width = 0;
267 Align = 32;
268 break;
269
Douglas Gregor72564e72009-02-26 23:50:07 +0000270 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000271 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000272 Width = 0;
273 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
274 break;
275
Steve Narofffb22d962007-08-30 01:06:46 +0000276 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000277 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Steve Narofffb22d962007-08-30 01:06:46 +0000278
Chris Lattner98be4942008-03-05 18:54:05 +0000279 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000280 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000281 Align = EltInfo.second;
282 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000283 }
Nate Begeman213541a2008-04-18 23:10:10 +0000284 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000285 case Type::Vector: {
286 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000287 getTypeInfo(cast<VectorType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000288 Width = EltInfo.first*cast<VectorType>(T)->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000289 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000290 // If the alignment is not a power of 2, round up to the next power of 2.
291 // This happens for non-power-of-2 length vectors.
292 // FIXME: this should probably be a target property.
293 Align = 1 << llvm::Log2_32_Ceil(Align);
Chris Lattner030d8842007-07-19 22:06:24 +0000294 break;
295 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000296
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000297 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000298 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000299 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000300 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000301 // GCC extension: alignof(void) = 8 bits.
302 Width = 0;
303 Align = 8;
304 break;
305
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000306 case BuiltinType::Bool:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000307 Width = Target.getBoolWidth();
308 Align = Target.getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000309 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000310 case BuiltinType::Char_S:
311 case BuiltinType::Char_U:
312 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000313 case BuiltinType::SChar:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000314 Width = Target.getCharWidth();
315 Align = Target.getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000316 break;
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000317 case BuiltinType::WChar:
318 Width = Target.getWCharWidth();
319 Align = Target.getWCharAlign();
320 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000321 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000322 case BuiltinType::Short:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000323 Width = Target.getShortWidth();
324 Align = Target.getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000325 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000326 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000327 case BuiltinType::Int:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000328 Width = Target.getIntWidth();
329 Align = Target.getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000330 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000331 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000332 case BuiltinType::Long:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000333 Width = Target.getLongWidth();
334 Align = Target.getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000335 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000336 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000337 case BuiltinType::LongLong:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000338 Width = Target.getLongLongWidth();
339 Align = Target.getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000340 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000341 case BuiltinType::Int128:
342 case BuiltinType::UInt128:
343 Width = 128;
344 Align = 128; // int128_t is 128-bit aligned on all targets.
345 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000346 case BuiltinType::Float:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000347 Width = Target.getFloatWidth();
348 Align = Target.getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000349 break;
350 case BuiltinType::Double:
Chris Lattner5426bf62008-04-07 07:01:58 +0000351 Width = Target.getDoubleWidth();
352 Align = Target.getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000353 break;
354 case BuiltinType::LongDouble:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000355 Width = Target.getLongDoubleWidth();
356 Align = Target.getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000357 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000358 case BuiltinType::NullPtr:
359 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
360 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000361 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000362 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000363 break;
Eli Friedmanf98aba32009-02-13 02:31:07 +0000364 case Type::FixedWidthInt:
365 // FIXME: This isn't precisely correct; the width/alignment should depend
366 // on the available types for the target
367 Width = cast<FixedWidthIntType>(T)->getWidth();
Chris Lattner736166b2009-02-15 21:20:13 +0000368 Width = std::max(llvm::NextPowerOf2(Width - 1), (uint64_t)8);
Eli Friedmanf98aba32009-02-13 02:31:07 +0000369 Align = Width;
370 break;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000371 case Type::ExtQual:
Chris Lattner98be4942008-03-05 18:54:05 +0000372 // FIXME: Pointers into different addr spaces could have different sizes and
373 // alignment requirements: getPointerInfo should take an AddrSpace.
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000374 return getTypeInfo(QualType(cast<ExtQualType>(T)->getBaseType(), 0));
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000375 case Type::ObjCObjectPointer:
Douglas Gregor72564e72009-02-26 23:50:07 +0000376 case Type::ObjCQualifiedInterface:
Chris Lattner5426bf62008-04-07 07:01:58 +0000377 Width = Target.getPointerWidth(0);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000378 Align = Target.getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000379 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000380 case Type::BlockPointer: {
381 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
382 Width = Target.getPointerWidth(AS);
383 Align = Target.getPointerAlign(AS);
384 break;
385 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000386 case Type::Pointer: {
387 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner5426bf62008-04-07 07:01:58 +0000388 Width = Target.getPointerWidth(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000389 Align = Target.getPointerAlign(AS);
390 break;
391 }
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000392 case Type::LValueReference:
393 case Type::RValueReference:
Chris Lattner7ab2ed82007-07-13 22:16:13 +0000394 // "When applied to a reference or a reference type, the result is the size
Chris Lattner5d2a6302007-07-18 18:26:58 +0000395 // of the referenced type." C++98 5.3.3p2: expr.sizeof.
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000396 // FIXME: This is wrong for struct layout: a reference in a struct has
397 // pointer size.
Chris Lattnerbdcd6372008-04-02 17:35:06 +0000398 return getTypeInfo(cast<ReferenceType>(T)->getPointeeType());
Sebastian Redlf30208a2009-01-24 21:16:55 +0000399 case Type::MemberPointer: {
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000400 // FIXME: This is ABI dependent. We use the Itanium C++ ABI.
401 // http://www.codesourcery.com/public/cxx-abi/abi.html#member-pointers
402 // If we ever want to support other ABIs this needs to be abstracted.
403
Sebastian Redlf30208a2009-01-24 21:16:55 +0000404 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000405 std::pair<uint64_t, unsigned> PtrDiffInfo =
406 getTypeInfo(getPointerDiffType());
407 Width = PtrDiffInfo.first;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000408 if (Pointee->isFunctionType())
409 Width *= 2;
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000410 Align = PtrDiffInfo.second;
411 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000412 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000413 case Type::Complex: {
414 // Complex types have the same alignment as their elements, but twice the
415 // size.
416 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000417 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000418 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000419 Align = EltInfo.second;
420 break;
421 }
Devang Patel44a3dde2008-06-04 21:54:36 +0000422 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000423 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000424 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
425 Width = Layout.getSize();
426 Align = Layout.getAlignment();
427 break;
428 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000429 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000430 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000431 const TagType *TT = cast<TagType>(T);
432
433 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner8389eab2008-08-09 21:35:13 +0000434 Width = 1;
435 Align = 1;
436 break;
437 }
438
Daniel Dunbar1d751182008-11-08 05:48:37 +0000439 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000440 return getTypeInfo(ET->getDecl()->getIntegerType());
441
Daniel Dunbar1d751182008-11-08 05:48:37 +0000442 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000443 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
444 Width = Layout.getSize();
445 Align = Layout.getAlignment();
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000446 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000447 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000448
Douglas Gregor18857642009-04-30 17:32:17 +0000449 case Type::Typedef: {
450 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000451 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
Douglas Gregor18857642009-04-30 17:32:17 +0000452 Align = Aligned->getAlignment();
453 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
454 } else
455 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregor7532dc62009-03-30 22:58:21 +0000456 break;
Chris Lattner71763312008-04-06 22:05:18 +0000457 }
Douglas Gregor18857642009-04-30 17:32:17 +0000458
459 case Type::TypeOfExpr:
460 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
461 .getTypePtr());
462
463 case Type::TypeOf:
464 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
465
Anders Carlsson395b4752009-06-24 19:06:50 +0000466 case Type::Decltype:
467 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
468 .getTypePtr());
469
Douglas Gregor18857642009-04-30 17:32:17 +0000470 case Type::QualifiedName:
471 return getTypeInfo(cast<QualifiedNameType>(T)->getNamedType().getTypePtr());
472
473 case Type::TemplateSpecialization:
474 assert(getCanonicalType(T) != T &&
475 "Cannot request the size of a dependent type");
476 // FIXME: this is likely to be wrong once we support template
477 // aliases, since a template alias could refer to a typedef that
478 // has an __aligned__ attribute on it.
479 return getTypeInfo(getCanonicalType(T));
480 }
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000481
Chris Lattner464175b2007-07-18 17:52:12 +0000482 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000483 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +0000484}
485
Chris Lattner34ebde42009-01-27 18:08:34 +0000486/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
487/// type for the current target in bits. This can be different than the ABI
488/// alignment in cases where it is beneficial for performance to overalign
489/// a data type.
490unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
491 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +0000492
493 // Double and long long should be naturally aligned if possible.
494 if (const ComplexType* CT = T->getAsComplexType())
495 T = CT->getElementType().getTypePtr();
496 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
497 T->isSpecificBuiltinType(BuiltinType::LongLong))
498 return std::max(ABIAlign, (unsigned)getTypeSize(T));
499
Chris Lattner34ebde42009-01-27 18:08:34 +0000500 return ABIAlign;
501}
502
503
Devang Patel8b277042008-06-04 21:22:16 +0000504/// LayoutField - Field layout.
505void ASTRecordLayout::LayoutField(const FieldDecl *FD, unsigned FieldNo,
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000506 bool IsUnion, unsigned StructPacking,
Devang Patel8b277042008-06-04 21:22:16 +0000507 ASTContext &Context) {
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000508 unsigned FieldPacking = StructPacking;
Devang Patel8b277042008-06-04 21:22:16 +0000509 uint64_t FieldOffset = IsUnion ? 0 : Size;
510 uint64_t FieldSize;
511 unsigned FieldAlign;
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000512
513 // FIXME: Should this override struct packing? Probably we want to
514 // take the minimum?
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000515 if (const PackedAttr *PA = FD->getAttr<PackedAttr>())
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000516 FieldPacking = PA->getAlignment();
Devang Patel8b277042008-06-04 21:22:16 +0000517
518 if (const Expr *BitWidthExpr = FD->getBitWidth()) {
519 // TODO: Need to check this algorithm on other targets!
520 // (tested on Linux-X86)
Eli Friedman9a901bb2009-04-26 19:19:15 +0000521 FieldSize = BitWidthExpr->EvaluateAsInt(Context).getZExtValue();
Devang Patel8b277042008-06-04 21:22:16 +0000522
523 std::pair<uint64_t, unsigned> FieldInfo =
524 Context.getTypeInfo(FD->getType());
525 uint64_t TypeSize = FieldInfo.first;
526
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000527 // Determine the alignment of this bitfield. The packing
528 // attributes define a maximum and the alignment attribute defines
529 // a minimum.
530 // FIXME: What is the right behavior when the specified alignment
531 // is smaller than the specified packing?
Devang Patel8b277042008-06-04 21:22:16 +0000532 FieldAlign = FieldInfo.second;
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000533 if (FieldPacking)
534 FieldAlign = std::min(FieldAlign, FieldPacking);
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000535 if (const AlignedAttr *AA = FD->getAttr<AlignedAttr>())
Devang Patel8b277042008-06-04 21:22:16 +0000536 FieldAlign = std::max(FieldAlign, AA->getAlignment());
537
538 // Check if we need to add padding to give the field the correct
539 // alignment.
540 if (FieldSize == 0 || (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize)
541 FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1);
542
543 // Padding members don't affect overall alignment
544 if (!FD->getIdentifier())
545 FieldAlign = 1;
546 } else {
Chris Lattner8389eab2008-08-09 21:35:13 +0000547 if (FD->getType()->isIncompleteArrayType()) {
548 // This is a flexible array member; we can't directly
Devang Patel8b277042008-06-04 21:22:16 +0000549 // query getTypeInfo about these, so we figure it out here.
550 // Flexible array members don't have any size, but they
551 // have to be aligned appropriately for their element type.
552 FieldSize = 0;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000553 const ArrayType* ATy = Context.getAsArrayType(FD->getType());
Devang Patel8b277042008-06-04 21:22:16 +0000554 FieldAlign = Context.getTypeAlign(ATy->getElementType());
Anders Carlsson2f1169f2009-04-10 05:31:15 +0000555 } else if (const ReferenceType *RT = FD->getType()->getAsReferenceType()) {
556 unsigned AS = RT->getPointeeType().getAddressSpace();
557 FieldSize = Context.Target.getPointerWidth(AS);
558 FieldAlign = Context.Target.getPointerAlign(AS);
Devang Patel8b277042008-06-04 21:22:16 +0000559 } else {
560 std::pair<uint64_t, unsigned> FieldInfo =
561 Context.getTypeInfo(FD->getType());
562 FieldSize = FieldInfo.first;
563 FieldAlign = FieldInfo.second;
564 }
565
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000566 // Determine the alignment of this bitfield. The packing
567 // attributes define a maximum and the alignment attribute defines
568 // a minimum. Additionally, the packing alignment must be at least
569 // a byte for non-bitfields.
570 //
571 // FIXME: What is the right behavior when the specified alignment
572 // is smaller than the specified packing?
573 if (FieldPacking)
574 FieldAlign = std::min(FieldAlign, std::max(8U, FieldPacking));
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000575 if (const AlignedAttr *AA = FD->getAttr<AlignedAttr>())
Devang Patel8b277042008-06-04 21:22:16 +0000576 FieldAlign = std::max(FieldAlign, AA->getAlignment());
577
578 // Round up the current record size to the field's alignment boundary.
579 FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1);
580 }
581
582 // Place this field at the current location.
583 FieldOffsets[FieldNo] = FieldOffset;
584
585 // Reserve space for this field.
586 if (IsUnion) {
587 Size = std::max(Size, FieldSize);
588 } else {
589 Size = FieldOffset + FieldSize;
590 }
591
Daniel Dunbard6884a02009-05-04 05:16:21 +0000592 // Remember the next available offset.
593 NextOffset = Size;
594
Devang Patel8b277042008-06-04 21:22:16 +0000595 // Remember max struct/class alignment.
596 Alignment = std::max(Alignment, FieldAlign);
597}
598
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000599static void CollectLocalObjCIvars(ASTContext *Ctx,
600 const ObjCInterfaceDecl *OI,
601 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000602 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
603 E = OI->ivar_end(); I != E; ++I) {
Chris Lattnerf1690852009-03-31 08:48:01 +0000604 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000605 if (!IVDecl->isInvalidDecl())
606 Fields.push_back(cast<FieldDecl>(IVDecl));
607 }
608}
609
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000610void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
611 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
612 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
613 CollectObjCIvars(SuperClass, Fields);
614 CollectLocalObjCIvars(this, OI, Fields);
615}
616
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000617/// ShallowCollectObjCIvars -
618/// Collect all ivars, including those synthesized, in the current class.
619///
620void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
621 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars,
622 bool CollectSynthesized) {
623 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
624 E = OI->ivar_end(); I != E; ++I) {
625 Ivars.push_back(*I);
626 }
627 if (CollectSynthesized)
628 CollectSynthesizedIvars(OI, Ivars);
629}
630
Fariborz Jahanian98200742009-05-12 18:14:29 +0000631void ASTContext::CollectProtocolSynthesizedIvars(const ObjCProtocolDecl *PD,
632 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
633 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(*this),
634 E = PD->prop_end(*this); I != E; ++I)
635 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
636 Ivars.push_back(Ivar);
637
638 // Also look into nested protocols.
639 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
640 E = PD->protocol_end(); P != E; ++P)
641 CollectProtocolSynthesizedIvars(*P, Ivars);
642}
643
644/// CollectSynthesizedIvars -
645/// This routine collect synthesized ivars for the designated class.
646///
647void ASTContext::CollectSynthesizedIvars(const ObjCInterfaceDecl *OI,
648 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
649 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(*this),
650 E = OI->prop_end(*this); I != E; ++I) {
651 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
652 Ivars.push_back(Ivar);
653 }
654 // Also look into interface's protocol list for properties declared
655 // in the protocol and whose ivars are synthesized.
656 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
657 PE = OI->protocol_end(); P != PE; ++P) {
658 ObjCProtocolDecl *PD = (*P);
659 CollectProtocolSynthesizedIvars(PD, Ivars);
660 }
661}
662
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000663unsigned ASTContext::CountProtocolSynthesizedIvars(const ObjCProtocolDecl *PD) {
664 unsigned count = 0;
665 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(*this),
666 E = PD->prop_end(*this); I != E; ++I)
667 if ((*I)->getPropertyIvarDecl())
668 ++count;
669
670 // Also look into nested protocols.
671 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
672 E = PD->protocol_end(); P != E; ++P)
673 count += CountProtocolSynthesizedIvars(*P);
674 return count;
675}
676
677unsigned ASTContext::CountSynthesizedIvars(const ObjCInterfaceDecl *OI)
678{
679 unsigned count = 0;
680 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(*this),
681 E = OI->prop_end(*this); I != E; ++I) {
682 if ((*I)->getPropertyIvarDecl())
683 ++count;
684 }
685 // Also look into interface's protocol list for properties declared
686 // in the protocol and whose ivars are synthesized.
687 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
688 PE = OI->protocol_end(); P != PE; ++P) {
689 ObjCProtocolDecl *PD = (*P);
690 count += CountProtocolSynthesizedIvars(PD);
691 }
692 return count;
693}
694
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000695/// getInterfaceLayoutImpl - Get or compute information about the
696/// layout of the given interface.
697///
698/// \param Impl - If given, also include the layout of the interface's
699/// implementation. This may differ by including synthesized ivars.
Devang Patel44a3dde2008-06-04 21:54:36 +0000700const ASTRecordLayout &
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000701ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
702 const ObjCImplementationDecl *Impl) {
Daniel Dunbar532d4da2009-05-03 13:15:50 +0000703 assert(!D->isForwardDecl() && "Invalid interface decl!");
704
Devang Patel44a3dde2008-06-04 21:54:36 +0000705 // Look up this layout, if already laid out, return what we have.
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000706 ObjCContainerDecl *Key =
707 Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
708 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
709 return *Entry;
Devang Patel44a3dde2008-06-04 21:54:36 +0000710
Daniel Dunbar453addb2009-05-03 11:16:44 +0000711 unsigned FieldCount = D->ivar_size();
712 // Add in synthesized ivar count if laying out an implementation.
713 if (Impl) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000714 unsigned SynthCount = CountSynthesizedIvars(D);
715 FieldCount += SynthCount;
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000716 // If there aren't any sythesized ivars then reuse the interface
Daniel Dunbar453addb2009-05-03 11:16:44 +0000717 // entry. Note we can't cache this because we simply free all
718 // entries later; however we shouldn't look up implementations
719 // frequently.
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000720 if (SynthCount == 0)
Daniel Dunbar453addb2009-05-03 11:16:44 +0000721 return getObjCLayout(D, 0);
722 }
723
Devang Patel6a5a34c2008-06-06 02:14:01 +0000724 ASTRecordLayout *NewEntry = NULL;
Devang Patel6a5a34c2008-06-06 02:14:01 +0000725 if (ObjCInterfaceDecl *SD = D->getSuperClass()) {
Devang Patel6a5a34c2008-06-06 02:14:01 +0000726 const ASTRecordLayout &SL = getASTObjCInterfaceLayout(SD);
727 unsigned Alignment = SL.getAlignment();
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000728
Daniel Dunbar913af352009-05-07 21:58:26 +0000729 // We start laying out ivars not at the end of the superclass
730 // structure, but at the next byte following the last field.
731 uint64_t Size = llvm::RoundUpToAlignment(SL.NextOffset, 8);
Daniel Dunbard6884a02009-05-04 05:16:21 +0000732
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000733 ObjCLayouts[Key] = NewEntry = new ASTRecordLayout(Size, Alignment);
Devang Patel6a5a34c2008-06-06 02:14:01 +0000734 NewEntry->InitializeLayout(FieldCount);
Devang Patel6a5a34c2008-06-06 02:14:01 +0000735 } else {
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000736 ObjCLayouts[Key] = NewEntry = new ASTRecordLayout();
Devang Patel6a5a34c2008-06-06 02:14:01 +0000737 NewEntry->InitializeLayout(FieldCount);
738 }
Devang Patel44a3dde2008-06-04 21:54:36 +0000739
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000740 unsigned StructPacking = 0;
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000741 if (const PackedAttr *PA = D->getAttr<PackedAttr>())
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000742 StructPacking = PA->getAlignment();
Devang Patel44a3dde2008-06-04 21:54:36 +0000743
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000744 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>())
Devang Patel44a3dde2008-06-04 21:54:36 +0000745 NewEntry->SetAlignment(std::max(NewEntry->getAlignment(),
746 AA->getAlignment()));
747
748 // Layout each ivar sequentially.
749 unsigned i = 0;
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000750 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
751 ShallowCollectObjCIvars(D, Ivars, Impl);
752 for (unsigned k = 0, e = Ivars.size(); k != e; ++k)
753 NewEntry->LayoutField(Ivars[k], i++, false, StructPacking, *this);
754
Devang Patel44a3dde2008-06-04 21:54:36 +0000755 // Finally, round the size of the total struct up to the alignment of the
756 // struct itself.
757 NewEntry->FinalizeLayout();
758 return *NewEntry;
759}
760
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000761const ASTRecordLayout &
762ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
763 return getObjCLayout(D, 0);
764}
765
766const ASTRecordLayout &
767ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
768 return getObjCLayout(D->getClassInterface(), D);
769}
770
Devang Patel88a981b2007-11-01 19:11:01 +0000771/// getASTRecordLayout - Get or compute information about the layout of the
Chris Lattner464175b2007-07-18 17:52:12 +0000772/// specified record (struct/union/class), which indicates its size and field
773/// position information.
Chris Lattner98be4942008-03-05 18:54:05 +0000774const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +0000775 D = D->getDefinition(*this);
776 assert(D && "Cannot get layout of forward declarations!");
Eli Friedman4bd998b2008-05-30 09:31:38 +0000777
Chris Lattner464175b2007-07-18 17:52:12 +0000778 // Look up this layout, if already laid out, return what we have.
Devang Patel88a981b2007-11-01 19:11:01 +0000779 const ASTRecordLayout *&Entry = ASTRecordLayouts[D];
Chris Lattner464175b2007-07-18 17:52:12 +0000780 if (Entry) return *Entry;
Eli Friedman4bd998b2008-05-30 09:31:38 +0000781
Devang Patel88a981b2007-11-01 19:11:01 +0000782 // Allocate and assign into ASTRecordLayouts here. The "Entry" reference can
783 // be invalidated (dangle) if the ASTRecordLayouts hashtable is inserted into.
784 ASTRecordLayout *NewEntry = new ASTRecordLayout();
Chris Lattner464175b2007-07-18 17:52:12 +0000785 Entry = NewEntry;
Eli Friedman4bd998b2008-05-30 09:31:38 +0000786
Douglas Gregore267ff32008-12-11 20:41:00 +0000787 // FIXME: Avoid linear walk through the fields, if possible.
Douglas Gregor6ab35242009-04-09 21:40:53 +0000788 NewEntry->InitializeLayout(std::distance(D->field_begin(*this),
789 D->field_end(*this)));
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000790 bool IsUnion = D->isUnion();
Chris Lattner464175b2007-07-18 17:52:12 +0000791
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000792 unsigned StructPacking = 0;
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000793 if (const PackedAttr *PA = D->getAttr<PackedAttr>())
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000794 StructPacking = PA->getAlignment();
795
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000796 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>())
Devang Patel8b277042008-06-04 21:22:16 +0000797 NewEntry->SetAlignment(std::max(NewEntry->getAlignment(),
798 AA->getAlignment()));
Anders Carlsson8af226a2008-02-18 07:13:09 +0000799
Eli Friedman4bd998b2008-05-30 09:31:38 +0000800 // Layout each field, for now, just sequentially, respecting alignment. In
801 // the future, this will need to be tweakable by targets.
Douglas Gregor44b43212008-12-11 16:49:14 +0000802 unsigned FieldIdx = 0;
Douglas Gregor6ab35242009-04-09 21:40:53 +0000803 for (RecordDecl::field_iterator Field = D->field_begin(*this),
804 FieldEnd = D->field_end(*this);
Douglas Gregor44b43212008-12-11 16:49:14 +0000805 Field != FieldEnd; (void)++Field, ++FieldIdx)
806 NewEntry->LayoutField(*Field, FieldIdx, IsUnion, StructPacking, *this);
Eli Friedman4bd998b2008-05-30 09:31:38 +0000807
808 // Finally, round the size of the total struct up to the alignment of the
809 // struct itself.
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000810 NewEntry->FinalizeLayout(getLangOptions().CPlusPlus);
Chris Lattner5d2a6302007-07-18 18:26:58 +0000811 return *NewEntry;
Chris Lattner464175b2007-07-18 17:52:12 +0000812}
813
Chris Lattnera7674d82007-07-13 22:13:22 +0000814//===----------------------------------------------------------------------===//
815// Type creation/memoization methods
816//===----------------------------------------------------------------------===//
817
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000818QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerf52ab252008-04-06 22:59:24 +0000819 QualType CanT = getCanonicalType(T);
820 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +0000821 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +0000822
823 // If we are composing extended qualifiers together, merge together into one
824 // ExtQualType node.
825 unsigned CVRQuals = T.getCVRQualifiers();
826 QualType::GCAttrTypes GCAttr = QualType::GCNone;
827 Type *TypeNode = T.getTypePtr();
Chris Lattnerf46699c2008-02-20 20:55:12 +0000828
Chris Lattnerb7d25532009-02-18 22:53:11 +0000829 if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
830 // If this type already has an address space specified, it cannot get
831 // another one.
832 assert(EQT->getAddressSpace() == 0 &&
833 "Type cannot be in multiple addr spaces!");
834 GCAttr = EQT->getObjCGCAttr();
835 TypeNode = EQT->getBaseType();
836 }
Chris Lattnerf46699c2008-02-20 20:55:12 +0000837
Chris Lattnerb7d25532009-02-18 22:53:11 +0000838 // Check if we've already instantiated this type.
Christopher Lambebb97e92008-02-04 02:31:56 +0000839 llvm::FoldingSetNodeID ID;
Chris Lattnerb7d25532009-02-18 22:53:11 +0000840 ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
Christopher Lambebb97e92008-02-04 02:31:56 +0000841 void *InsertPos = 0;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000842 if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattnerb7d25532009-02-18 22:53:11 +0000843 return QualType(EXTQy, CVRQuals);
844
Christopher Lambebb97e92008-02-04 02:31:56 +0000845 // If the base type isn't canonical, this won't be a canonical type either,
846 // so fill in the canonical type field.
847 QualType Canonical;
Chris Lattnerb7d25532009-02-18 22:53:11 +0000848 if (!TypeNode->isCanonical()) {
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000849 Canonical = getAddrSpaceQualType(CanT, AddressSpace);
Christopher Lambebb97e92008-02-04 02:31:56 +0000850
Chris Lattnerb7d25532009-02-18 22:53:11 +0000851 // Update InsertPos, the previous call could have invalidated it.
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000852 ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +0000853 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Christopher Lambebb97e92008-02-04 02:31:56 +0000854 }
Chris Lattnerb7d25532009-02-18 22:53:11 +0000855 ExtQualType *New =
856 new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000857 ExtQualTypes.InsertNode(New, InsertPos);
Christopher Lambebb97e92008-02-04 02:31:56 +0000858 Types.push_back(New);
Chris Lattnerb7d25532009-02-18 22:53:11 +0000859 return QualType(New, CVRQuals);
Christopher Lambebb97e92008-02-04 02:31:56 +0000860}
861
Chris Lattnerb7d25532009-02-18 22:53:11 +0000862QualType ASTContext::getObjCGCQualType(QualType T,
863 QualType::GCAttrTypes GCAttr) {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000864 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +0000865 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000866 return T;
867
Fariborz Jahanian4027cd12009-06-03 17:15:17 +0000868 if (T->isPointerType()) {
869 QualType Pointee = T->getAsPointerType()->getPointeeType();
870 if (Pointee->isPointerType()) {
871 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
872 return getPointerType(ResultType);
873 }
874 }
Chris Lattnerb7d25532009-02-18 22:53:11 +0000875 // If we are composing extended qualifiers together, merge together into one
876 // ExtQualType node.
877 unsigned CVRQuals = T.getCVRQualifiers();
878 Type *TypeNode = T.getTypePtr();
879 unsigned AddressSpace = 0;
880
881 if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
882 // If this type already has an address space specified, it cannot get
883 // another one.
884 assert(EQT->getObjCGCAttr() == QualType::GCNone &&
885 "Type cannot be in multiple addr spaces!");
886 AddressSpace = EQT->getAddressSpace();
887 TypeNode = EQT->getBaseType();
888 }
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000889
890 // Check if we've already instantiated an gc qual'd type of this type.
891 llvm::FoldingSetNodeID ID;
Chris Lattnerb7d25532009-02-18 22:53:11 +0000892 ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000893 void *InsertPos = 0;
894 if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattnerb7d25532009-02-18 22:53:11 +0000895 return QualType(EXTQy, CVRQuals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000896
897 // If the base type isn't canonical, this won't be a canonical type either,
898 // so fill in the canonical type field.
Eli Friedman5a61f0e2009-02-27 23:04:43 +0000899 // FIXME: Isn't this also not canonical if the base type is a array
900 // or pointer type? I can't find any documentation for objc_gc, though...
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000901 QualType Canonical;
902 if (!T->isCanonical()) {
Chris Lattnerb7d25532009-02-18 22:53:11 +0000903 Canonical = getObjCGCQualType(CanT, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000904
Chris Lattnerb7d25532009-02-18 22:53:11 +0000905 // Update InsertPos, the previous call could have invalidated it.
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000906 ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
907 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
908 }
Chris Lattnerb7d25532009-02-18 22:53:11 +0000909 ExtQualType *New =
910 new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000911 ExtQualTypes.InsertNode(New, InsertPos);
912 Types.push_back(New);
Chris Lattnerb7d25532009-02-18 22:53:11 +0000913 return QualType(New, CVRQuals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000914}
Chris Lattnera7674d82007-07-13 22:13:22 +0000915
Reid Spencer5f016e22007-07-11 17:01:13 +0000916/// getComplexType - Return the uniqued reference to the type for a complex
917/// number with the specified element type.
918QualType ASTContext::getComplexType(QualType T) {
919 // Unique pointers, to guarantee there is only one pointer of a particular
920 // structure.
921 llvm::FoldingSetNodeID ID;
922 ComplexType::Profile(ID, T);
923
924 void *InsertPos = 0;
925 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
926 return QualType(CT, 0);
927
928 // If the pointee type isn't canonical, this won't be a canonical type either,
929 // so fill in the canonical type field.
930 QualType Canonical;
931 if (!T->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +0000932 Canonical = getComplexType(getCanonicalType(T));
Reid Spencer5f016e22007-07-11 17:01:13 +0000933
934 // Get the new insert position for the node we care about.
935 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +0000936 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +0000937 }
Steve Narofff83820b2009-01-27 22:08:43 +0000938 ComplexType *New = new (*this,8) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +0000939 Types.push_back(New);
940 ComplexTypes.InsertNode(New, InsertPos);
941 return QualType(New, 0);
942}
943
Eli Friedmanf98aba32009-02-13 02:31:07 +0000944QualType ASTContext::getFixedWidthIntType(unsigned Width, bool Signed) {
945 llvm::DenseMap<unsigned, FixedWidthIntType*> &Map = Signed ?
946 SignedFixedWidthIntTypes : UnsignedFixedWidthIntTypes;
947 FixedWidthIntType *&Entry = Map[Width];
948 if (!Entry)
949 Entry = new FixedWidthIntType(Width, Signed);
950 return QualType(Entry, 0);
951}
Reid Spencer5f016e22007-07-11 17:01:13 +0000952
953/// getPointerType - Return the uniqued reference to the type for a pointer to
954/// the specified type.
955QualType ASTContext::getPointerType(QualType T) {
956 // Unique pointers, to guarantee there is only one pointer of a particular
957 // structure.
958 llvm::FoldingSetNodeID ID;
959 PointerType::Profile(ID, T);
960
961 void *InsertPos = 0;
962 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
963 return QualType(PT, 0);
964
965 // If the pointee type isn't canonical, this won't be a canonical type either,
966 // so fill in the canonical type field.
967 QualType Canonical;
968 if (!T->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +0000969 Canonical = getPointerType(getCanonicalType(T));
Reid Spencer5f016e22007-07-11 17:01:13 +0000970
971 // Get the new insert position for the node we care about.
972 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +0000973 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +0000974 }
Steve Narofff83820b2009-01-27 22:08:43 +0000975 PointerType *New = new (*this,8) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +0000976 Types.push_back(New);
977 PointerTypes.InsertNode(New, InsertPos);
978 return QualType(New, 0);
979}
980
Steve Naroff5618bd42008-08-27 16:04:49 +0000981/// getBlockPointerType - Return the uniqued reference to the type for
982/// a pointer to the specified block.
983QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff296e8d52008-08-28 19:20:44 +0000984 assert(T->isFunctionType() && "block of function types only");
985 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +0000986 // structure.
987 llvm::FoldingSetNodeID ID;
988 BlockPointerType::Profile(ID, T);
989
990 void *InsertPos = 0;
991 if (BlockPointerType *PT =
992 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
993 return QualType(PT, 0);
994
Steve Naroff296e8d52008-08-28 19:20:44 +0000995 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +0000996 // type either so fill in the canonical type field.
997 QualType Canonical;
998 if (!T->isCanonical()) {
999 Canonical = getBlockPointerType(getCanonicalType(T));
1000
1001 // Get the new insert position for the node we care about.
1002 BlockPointerType *NewIP =
1003 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001004 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001005 }
Steve Narofff83820b2009-01-27 22:08:43 +00001006 BlockPointerType *New = new (*this,8) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001007 Types.push_back(New);
1008 BlockPointerTypes.InsertNode(New, InsertPos);
1009 return QualType(New, 0);
1010}
1011
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001012/// getLValueReferenceType - Return the uniqued reference to the type for an
1013/// lvalue reference to the specified type.
1014QualType ASTContext::getLValueReferenceType(QualType T) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001015 // Unique pointers, to guarantee there is only one pointer of a particular
1016 // structure.
1017 llvm::FoldingSetNodeID ID;
1018 ReferenceType::Profile(ID, T);
1019
1020 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001021 if (LValueReferenceType *RT =
1022 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001023 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001024
Reid Spencer5f016e22007-07-11 17:01:13 +00001025 // If the referencee type isn't canonical, this won't be a canonical type
1026 // either, so fill in the canonical type field.
1027 QualType Canonical;
1028 if (!T->isCanonical()) {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001029 Canonical = getLValueReferenceType(getCanonicalType(T));
1030
Reid Spencer5f016e22007-07-11 17:01:13 +00001031 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001032 LValueReferenceType *NewIP =
1033 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001034 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001035 }
1036
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001037 LValueReferenceType *New = new (*this,8) LValueReferenceType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001038 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001039 LValueReferenceTypes.InsertNode(New, InsertPos);
1040 return QualType(New, 0);
1041}
1042
1043/// getRValueReferenceType - Return the uniqued reference to the type for an
1044/// rvalue reference to the specified type.
1045QualType ASTContext::getRValueReferenceType(QualType T) {
1046 // Unique pointers, to guarantee there is only one pointer of a particular
1047 // structure.
1048 llvm::FoldingSetNodeID ID;
1049 ReferenceType::Profile(ID, T);
1050
1051 void *InsertPos = 0;
1052 if (RValueReferenceType *RT =
1053 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1054 return QualType(RT, 0);
1055
1056 // If the referencee type isn't canonical, this won't be a canonical type
1057 // either, so fill in the canonical type field.
1058 QualType Canonical;
1059 if (!T->isCanonical()) {
1060 Canonical = getRValueReferenceType(getCanonicalType(T));
1061
1062 // Get the new insert position for the node we care about.
1063 RValueReferenceType *NewIP =
1064 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1065 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1066 }
1067
1068 RValueReferenceType *New = new (*this,8) RValueReferenceType(T, Canonical);
1069 Types.push_back(New);
1070 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001071 return QualType(New, 0);
1072}
1073
Sebastian Redlf30208a2009-01-24 21:16:55 +00001074/// getMemberPointerType - Return the uniqued reference to the type for a
1075/// member pointer to the specified type, in the specified class.
1076QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls)
1077{
1078 // Unique pointers, to guarantee there is only one pointer of a particular
1079 // structure.
1080 llvm::FoldingSetNodeID ID;
1081 MemberPointerType::Profile(ID, T, Cls);
1082
1083 void *InsertPos = 0;
1084 if (MemberPointerType *PT =
1085 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1086 return QualType(PT, 0);
1087
1088 // If the pointee or class type isn't canonical, this won't be a canonical
1089 // type either, so fill in the canonical type field.
1090 QualType Canonical;
1091 if (!T->isCanonical()) {
1092 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1093
1094 // Get the new insert position for the node we care about.
1095 MemberPointerType *NewIP =
1096 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1097 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1098 }
Steve Narofff83820b2009-01-27 22:08:43 +00001099 MemberPointerType *New = new (*this,8) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001100 Types.push_back(New);
1101 MemberPointerTypes.InsertNode(New, InsertPos);
1102 return QualType(New, 0);
1103}
1104
Steve Narofffb22d962007-08-30 01:06:46 +00001105/// getConstantArrayType - Return the unique reference to the type for an
1106/// array of the specified element type.
1107QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001108 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001109 ArrayType::ArraySizeModifier ASM,
1110 unsigned EltTypeQuals) {
Eli Friedman587cbdf2009-05-29 20:17:55 +00001111 assert((EltTy->isDependentType() || EltTy->isConstantSizeType()) &&
1112 "Constant array of VLAs is illegal!");
1113
Chris Lattner38aeec72009-05-13 04:12:56 +00001114 // Convert the array size into a canonical width matching the pointer size for
1115 // the target.
1116 llvm::APInt ArySize(ArySizeIn);
1117 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1118
Reid Spencer5f016e22007-07-11 17:01:13 +00001119 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001120 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001121
1122 void *InsertPos = 0;
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001123 if (ConstantArrayType *ATP =
1124 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001125 return QualType(ATP, 0);
1126
1127 // If the element type isn't canonical, this won't be a canonical type either,
1128 // so fill in the canonical type field.
1129 QualType Canonical;
1130 if (!EltTy->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001131 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroffc9406122007-08-30 18:10:14 +00001132 ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001133 // Get the new insert position for the node we care about.
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001134 ConstantArrayType *NewIP =
1135 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001136 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001137 }
1138
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001139 ConstantArrayType *New =
Steve Narofff83820b2009-01-27 22:08:43 +00001140 new(*this,8)ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001141 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001142 Types.push_back(New);
1143 return QualType(New, 0);
1144}
1145
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001146/// getVariableArrayType - Returns a non-unique reference to the type for a
1147/// variable array of the specified element type.
Steve Naroffc9406122007-08-30 18:10:14 +00001148QualType ASTContext::getVariableArrayType(QualType EltTy, Expr *NumElts,
1149 ArrayType::ArraySizeModifier ASM,
1150 unsigned EltTypeQuals) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001151 // Since we don't unique expressions, it isn't possible to unique VLA's
1152 // that have an expression provided for their size.
1153
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001154 VariableArrayType *New =
Steve Narofff83820b2009-01-27 22:08:43 +00001155 new(*this,8)VariableArrayType(EltTy,QualType(), NumElts, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001156
1157 VariableArrayTypes.push_back(New);
1158 Types.push_back(New);
1159 return QualType(New, 0);
1160}
1161
Douglas Gregor898574e2008-12-05 23:32:09 +00001162/// getDependentSizedArrayType - Returns a non-unique reference to
1163/// the type for a dependently-sized array of the specified element
1164/// type. FIXME: We will need these to be uniqued, or at least
1165/// comparable, at some point.
1166QualType ASTContext::getDependentSizedArrayType(QualType EltTy, Expr *NumElts,
1167 ArrayType::ArraySizeModifier ASM,
1168 unsigned EltTypeQuals) {
1169 assert((NumElts->isTypeDependent() || NumElts->isValueDependent()) &&
1170 "Size must be type- or value-dependent!");
1171
1172 // Since we don't unique expressions, it isn't possible to unique
1173 // dependently-sized array types.
1174
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001175 DependentSizedArrayType *New =
Steve Narofff83820b2009-01-27 22:08:43 +00001176 new (*this,8) DependentSizedArrayType(EltTy, QualType(), NumElts,
1177 ASM, EltTypeQuals);
Douglas Gregor898574e2008-12-05 23:32:09 +00001178
1179 DependentSizedArrayTypes.push_back(New);
1180 Types.push_back(New);
1181 return QualType(New, 0);
1182}
1183
Eli Friedmanc5773c42008-02-15 18:16:39 +00001184QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1185 ArrayType::ArraySizeModifier ASM,
1186 unsigned EltTypeQuals) {
1187 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001188 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001189
1190 void *InsertPos = 0;
1191 if (IncompleteArrayType *ATP =
1192 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1193 return QualType(ATP, 0);
1194
1195 // If the element type isn't canonical, this won't be a canonical type
1196 // either, so fill in the canonical type field.
1197 QualType Canonical;
1198
1199 if (!EltTy->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001200 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001201 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001202
1203 // Get the new insert position for the node we care about.
1204 IncompleteArrayType *NewIP =
1205 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001206 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001207 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001208
Steve Narofff83820b2009-01-27 22:08:43 +00001209 IncompleteArrayType *New = new (*this,8) IncompleteArrayType(EltTy, Canonical,
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001210 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001211
1212 IncompleteArrayTypes.InsertNode(New, InsertPos);
1213 Types.push_back(New);
1214 return QualType(New, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001215}
1216
Steve Naroff73322922007-07-18 18:00:27 +00001217/// getVectorType - Return the unique reference to a vector type of
1218/// the specified element type and size. VectorType must be a built-in type.
1219QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001220 BuiltinType *baseType;
1221
Chris Lattnerf52ab252008-04-06 22:59:24 +00001222 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff73322922007-07-18 18:00:27 +00001223 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Reid Spencer5f016e22007-07-11 17:01:13 +00001224
1225 // Check if we've already instantiated a vector of this type.
1226 llvm::FoldingSetNodeID ID;
Steve Naroff73322922007-07-18 18:00:27 +00001227 VectorType::Profile(ID, vecType, NumElts, Type::Vector);
Reid Spencer5f016e22007-07-11 17:01:13 +00001228 void *InsertPos = 0;
1229 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1230 return QualType(VTP, 0);
1231
1232 // If the element type isn't canonical, this won't be a canonical type either,
1233 // so fill in the canonical type field.
1234 QualType Canonical;
1235 if (!vecType->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001236 Canonical = getVectorType(getCanonicalType(vecType), NumElts);
Reid Spencer5f016e22007-07-11 17:01:13 +00001237
1238 // Get the new insert position for the node we care about.
1239 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001240 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001241 }
Steve Narofff83820b2009-01-27 22:08:43 +00001242 VectorType *New = new (*this,8) VectorType(vecType, NumElts, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001243 VectorTypes.InsertNode(New, InsertPos);
1244 Types.push_back(New);
1245 return QualType(New, 0);
1246}
1247
Nate Begeman213541a2008-04-18 23:10:10 +00001248/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001249/// the specified element type and size. VectorType must be a built-in type.
Nate Begeman213541a2008-04-18 23:10:10 +00001250QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff73322922007-07-18 18:00:27 +00001251 BuiltinType *baseType;
1252
Chris Lattnerf52ab252008-04-06 22:59:24 +00001253 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begeman213541a2008-04-18 23:10:10 +00001254 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Steve Naroff73322922007-07-18 18:00:27 +00001255
1256 // Check if we've already instantiated a vector of this type.
1257 llvm::FoldingSetNodeID ID;
Nate Begeman213541a2008-04-18 23:10:10 +00001258 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector);
Steve Naroff73322922007-07-18 18:00:27 +00001259 void *InsertPos = 0;
1260 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1261 return QualType(VTP, 0);
1262
1263 // If the element type isn't canonical, this won't be a canonical type either,
1264 // so fill in the canonical type field.
1265 QualType Canonical;
1266 if (!vecType->isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001267 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Steve Naroff73322922007-07-18 18:00:27 +00001268
1269 // Get the new insert position for the node we care about.
1270 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001271 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001272 }
Steve Narofff83820b2009-01-27 22:08:43 +00001273 ExtVectorType *New = new (*this,8) ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001274 VectorTypes.InsertNode(New, InsertPos);
1275 Types.push_back(New);
1276 return QualType(New, 0);
1277}
1278
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001279QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
1280 Expr *SizeExpr,
1281 SourceLocation AttrLoc) {
1282 DependentSizedExtVectorType *New =
1283 new (*this,8) DependentSizedExtVectorType(vecType, QualType(),
1284 SizeExpr, AttrLoc);
1285
1286 DependentSizedExtVectorTypes.push_back(New);
1287 Types.push_back(New);
1288 return QualType(New, 0);
1289}
1290
Douglas Gregor72564e72009-02-26 23:50:07 +00001291/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001292///
Douglas Gregor72564e72009-02-26 23:50:07 +00001293QualType ASTContext::getFunctionNoProtoType(QualType ResultTy) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001294 // Unique functions, to guarantee there is only one function of a particular
1295 // structure.
1296 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001297 FunctionNoProtoType::Profile(ID, ResultTy);
Reid Spencer5f016e22007-07-11 17:01:13 +00001298
1299 void *InsertPos = 0;
Douglas Gregor72564e72009-02-26 23:50:07 +00001300 if (FunctionNoProtoType *FT =
1301 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001302 return QualType(FT, 0);
1303
1304 QualType Canonical;
1305 if (!ResultTy->isCanonical()) {
Douglas Gregor72564e72009-02-26 23:50:07 +00001306 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy));
Reid Spencer5f016e22007-07-11 17:01:13 +00001307
1308 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001309 FunctionNoProtoType *NewIP =
1310 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001311 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001312 }
1313
Douglas Gregor72564e72009-02-26 23:50:07 +00001314 FunctionNoProtoType *New =new(*this,8)FunctionNoProtoType(ResultTy,Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001315 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001316 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001317 return QualType(New, 0);
1318}
1319
1320/// getFunctionType - Return a normal function type with a typed argument
1321/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner61710852008-10-05 17:34:18 +00001322QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001323 unsigned NumArgs, bool isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001324 unsigned TypeQuals, bool hasExceptionSpec,
1325 bool hasAnyExceptionSpec, unsigned NumExs,
1326 const QualType *ExArray) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001327 // Unique functions, to guarantee there is only one function of a particular
1328 // structure.
1329 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001330 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001331 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
1332 NumExs, ExArray);
Reid Spencer5f016e22007-07-11 17:01:13 +00001333
1334 void *InsertPos = 0;
Douglas Gregor72564e72009-02-26 23:50:07 +00001335 if (FunctionProtoType *FTP =
1336 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001337 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001338
1339 // Determine whether the type being created is already canonical or not.
Reid Spencer5f016e22007-07-11 17:01:13 +00001340 bool isCanonical = ResultTy->isCanonical();
Sebastian Redl465226e2009-05-27 22:11:52 +00001341 if (hasExceptionSpec)
1342 isCanonical = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001343 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
1344 if (!ArgArray[i]->isCanonical())
1345 isCanonical = false;
1346
1347 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001348 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001349 QualType Canonical;
1350 if (!isCanonical) {
1351 llvm::SmallVector<QualType, 16> CanonicalArgs;
1352 CanonicalArgs.reserve(NumArgs);
1353 for (unsigned i = 0; i != NumArgs; ++i)
Chris Lattnerf52ab252008-04-06 22:59:24 +00001354 CanonicalArgs.push_back(getCanonicalType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001355
Chris Lattnerf52ab252008-04-06 22:59:24 +00001356 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001357 CanonicalArgs.data(), NumArgs,
Sebastian Redlbfa2fcb2009-05-06 23:27:55 +00001358 isVariadic, TypeQuals);
Sebastian Redl465226e2009-05-27 22:11:52 +00001359
Reid Spencer5f016e22007-07-11 17:01:13 +00001360 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001361 FunctionProtoType *NewIP =
1362 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001363 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001364 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001365
Douglas Gregor72564e72009-02-26 23:50:07 +00001366 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001367 // for two variable size arrays (for parameter and exception types) at the
1368 // end of them.
Douglas Gregor72564e72009-02-26 23:50:07 +00001369 FunctionProtoType *FTP =
Sebastian Redl465226e2009-05-27 22:11:52 +00001370 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1371 NumArgs*sizeof(QualType) +
1372 NumExs*sizeof(QualType), 8);
Douglas Gregor72564e72009-02-26 23:50:07 +00001373 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001374 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
1375 ExArray, NumExs, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001376 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001377 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001378 return QualType(FTP, 0);
1379}
1380
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001381/// getTypeDeclType - Return the unique reference to the type for the
1382/// specified type declaration.
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001383QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001384 assert(Decl && "Passed null for Decl param");
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001385 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1386
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001387 if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001388 return getTypedefType(Typedef);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001389 else if (isa<TemplateTypeParmDecl>(Decl)) {
1390 assert(false && "Template type parameter types are always available.");
1391 } else if (ObjCInterfaceDecl *ObjCInterface = dyn_cast<ObjCInterfaceDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001392 return getObjCInterfaceType(ObjCInterface);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001393
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001394 if (RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001395 if (PrevDecl)
1396 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001397 else
1398 Decl->TypeForDecl = new (*this,8) RecordType(Record);
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001399 }
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001400 else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
1401 if (PrevDecl)
1402 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001403 else
1404 Decl->TypeForDecl = new (*this,8) EnumType(Enum);
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001405 }
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001406 else
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001407 assert(false && "TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001408
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001409 if (!PrevDecl) Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001410 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001411}
1412
Reid Spencer5f016e22007-07-11 17:01:13 +00001413/// getTypedefType - Return the unique reference to the type for the
1414/// specified typename decl.
1415QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
1416 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1417
Chris Lattnerf52ab252008-04-06 22:59:24 +00001418 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
Douglas Gregor72564e72009-02-26 23:50:07 +00001419 Decl->TypeForDecl = new(*this,8) TypedefType(Type::Typedef, Decl, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001420 Types.push_back(Decl->TypeForDecl);
1421 return QualType(Decl->TypeForDecl, 0);
1422}
1423
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001424/// getObjCInterfaceType - Return the unique reference to the type for the
Steve Naroff3536b442007-09-06 21:24:23 +00001425/// specified ObjC interface decl.
Daniel Dunbar3b3a4582009-04-22 04:34:53 +00001426QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) {
Steve Naroff3536b442007-09-06 21:24:23 +00001427 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1428
Daniel Dunbar3b3a4582009-04-22 04:34:53 +00001429 ObjCInterfaceDecl *OID = const_cast<ObjCInterfaceDecl*>(Decl);
1430 Decl->TypeForDecl = new(*this,8) ObjCInterfaceType(Type::ObjCInterface, OID);
Steve Naroff3536b442007-09-06 21:24:23 +00001431 Types.push_back(Decl->TypeForDecl);
1432 return QualType(Decl->TypeForDecl, 0);
1433}
1434
Douglas Gregorfab9d672009-02-05 23:33:38 +00001435/// \brief Retrieve the template type parameter type for a template
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001436/// parameter or parameter pack with the given depth, index, and (optionally)
1437/// name.
Douglas Gregorfab9d672009-02-05 23:33:38 +00001438QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001439 bool ParameterPack,
Douglas Gregorfab9d672009-02-05 23:33:38 +00001440 IdentifierInfo *Name) {
1441 llvm::FoldingSetNodeID ID;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001442 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001443 void *InsertPos = 0;
1444 TemplateTypeParmType *TypeParm
1445 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1446
1447 if (TypeParm)
1448 return QualType(TypeParm, 0);
1449
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001450 if (Name) {
1451 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
1452 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, ParameterPack,
1453 Name, Canon);
1454 } else
1455 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001456
1457 Types.push_back(TypeParm);
1458 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1459
1460 return QualType(TypeParm, 0);
1461}
1462
Douglas Gregor55f6b142009-02-09 18:46:07 +00001463QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00001464ASTContext::getTemplateSpecializationType(TemplateName Template,
1465 const TemplateArgument *Args,
1466 unsigned NumArgs,
1467 QualType Canon) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001468 if (!Canon.isNull())
1469 Canon = getCanonicalType(Canon);
Douglas Gregorfc705b82009-02-26 22:19:44 +00001470
Douglas Gregor55f6b142009-02-09 18:46:07 +00001471 llvm::FoldingSetNodeID ID;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001472 TemplateSpecializationType::Profile(ID, Template, Args, NumArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001473
Douglas Gregor55f6b142009-02-09 18:46:07 +00001474 void *InsertPos = 0;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001475 TemplateSpecializationType *Spec
1476 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001477
1478 if (Spec)
1479 return QualType(Spec, 0);
1480
Douglas Gregor7532dc62009-03-30 22:58:21 +00001481 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00001482 sizeof(TemplateArgument) * NumArgs),
1483 8);
Douglas Gregor7532dc62009-03-30 22:58:21 +00001484 Spec = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, Canon);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001485 Types.push_back(Spec);
Douglas Gregor7532dc62009-03-30 22:58:21 +00001486 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001487
1488 return QualType(Spec, 0);
1489}
1490
Douglas Gregore4e5b052009-03-19 00:18:19 +00001491QualType
Douglas Gregorab452ba2009-03-26 23:50:42 +00001492ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
Douglas Gregore4e5b052009-03-19 00:18:19 +00001493 QualType NamedType) {
1494 llvm::FoldingSetNodeID ID;
Douglas Gregorab452ba2009-03-26 23:50:42 +00001495 QualifiedNameType::Profile(ID, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001496
1497 void *InsertPos = 0;
1498 QualifiedNameType *T
1499 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
1500 if (T)
1501 return QualType(T, 0);
1502
Douglas Gregorab452ba2009-03-26 23:50:42 +00001503 T = new (*this) QualifiedNameType(NNS, NamedType,
1504 getCanonicalType(NamedType));
Douglas Gregore4e5b052009-03-19 00:18:19 +00001505 Types.push_back(T);
1506 QualifiedNameTypes.InsertNode(T, InsertPos);
1507 return QualType(T, 0);
1508}
1509
Douglas Gregord57959a2009-03-27 23:10:48 +00001510QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1511 const IdentifierInfo *Name,
1512 QualType Canon) {
1513 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1514
1515 if (Canon.isNull()) {
1516 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1517 if (CanonNNS != NNS)
1518 Canon = getTypenameType(CanonNNS, Name);
1519 }
1520
1521 llvm::FoldingSetNodeID ID;
1522 TypenameType::Profile(ID, NNS, Name);
1523
1524 void *InsertPos = 0;
1525 TypenameType *T
1526 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1527 if (T)
1528 return QualType(T, 0);
1529
1530 T = new (*this) TypenameType(NNS, Name, Canon);
1531 Types.push_back(T);
1532 TypenameTypes.InsertNode(T, InsertPos);
1533 return QualType(T, 0);
1534}
1535
Douglas Gregor17343172009-04-01 00:28:59 +00001536QualType
1537ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1538 const TemplateSpecializationType *TemplateId,
1539 QualType Canon) {
1540 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1541
1542 if (Canon.isNull()) {
1543 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1544 QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
1545 if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
1546 const TemplateSpecializationType *CanonTemplateId
1547 = CanonType->getAsTemplateSpecializationType();
1548 assert(CanonTemplateId &&
1549 "Canonical type must also be a template specialization type");
1550 Canon = getTypenameType(CanonNNS, CanonTemplateId);
1551 }
1552 }
1553
1554 llvm::FoldingSetNodeID ID;
1555 TypenameType::Profile(ID, NNS, TemplateId);
1556
1557 void *InsertPos = 0;
1558 TypenameType *T
1559 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1560 if (T)
1561 return QualType(T, 0);
1562
1563 T = new (*this) TypenameType(NNS, TemplateId, Canon);
1564 Types.push_back(T);
1565 TypenameTypes.InsertNode(T, InsertPos);
1566 return QualType(T, 0);
1567}
1568
Chris Lattner88cb27a2008-04-07 04:56:42 +00001569/// CmpProtocolNames - Comparison predicate for sorting protocols
1570/// alphabetically.
1571static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
1572 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001573 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00001574}
1575
1576static void SortAndUniqueProtocols(ObjCProtocolDecl **&Protocols,
1577 unsigned &NumProtocols) {
1578 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
1579
1580 // Sort protocols, keyed by name.
1581 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
1582
1583 // Remove duplicates.
1584 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
1585 NumProtocols = ProtocolsEnd-Protocols;
1586}
1587
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001588/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
1589/// the given interface decl and the conforming protocol list.
1590QualType ASTContext::getObjCObjectPointerType(ObjCInterfaceDecl *Decl,
1591 ObjCProtocolDecl **Protocols,
1592 unsigned NumProtocols) {
1593 // Sort the protocol list alphabetically to canonicalize it.
1594 if (NumProtocols)
1595 SortAndUniqueProtocols(Protocols, NumProtocols);
1596
1597 llvm::FoldingSetNodeID ID;
1598 ObjCObjectPointerType::Profile(ID, Decl, Protocols, NumProtocols);
1599
1600 void *InsertPos = 0;
1601 if (ObjCObjectPointerType *QT =
1602 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1603 return QualType(QT, 0);
1604
1605 // No Match;
1606 ObjCObjectPointerType *QType =
1607 new (*this,8) ObjCObjectPointerType(Decl, Protocols, NumProtocols);
1608
1609 Types.push_back(QType);
1610 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
1611 return QualType(QType, 0);
1612}
Chris Lattner88cb27a2008-04-07 04:56:42 +00001613
Chris Lattner065f0d72008-04-07 04:44:08 +00001614/// getObjCQualifiedInterfaceType - Return a ObjCQualifiedInterfaceType type for
1615/// the given interface decl and the conforming protocol list.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001616QualType ASTContext::getObjCQualifiedInterfaceType(ObjCInterfaceDecl *Decl,
1617 ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
Chris Lattner88cb27a2008-04-07 04:56:42 +00001618 // Sort the protocol list alphabetically to canonicalize it.
1619 SortAndUniqueProtocols(Protocols, NumProtocols);
1620
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001621 llvm::FoldingSetNodeID ID;
Chris Lattnerb0489812008-04-07 06:38:24 +00001622 ObjCQualifiedInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001623
1624 void *InsertPos = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001625 if (ObjCQualifiedInterfaceType *QT =
1626 ObjCQualifiedInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001627 return QualType(QT, 0);
1628
1629 // No Match;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001630 ObjCQualifiedInterfaceType *QType =
Steve Narofff83820b2009-01-27 22:08:43 +00001631 new (*this,8) ObjCQualifiedInterfaceType(Decl, Protocols, NumProtocols);
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001632
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001633 Types.push_back(QType);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001634 ObjCQualifiedInterfaceTypes.InsertNode(QType, InsertPos);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001635 return QualType(QType, 0);
1636}
1637
Douglas Gregor72564e72009-02-26 23:50:07 +00001638/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
1639/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00001640/// multiple declarations that refer to "typeof(x)" all contain different
1641/// DeclRefExpr's. This doesn't effect the type checker, since it operates
1642/// on canonical type's (which are always unique).
Douglas Gregor72564e72009-02-26 23:50:07 +00001643QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001644 QualType Canonical = getCanonicalType(tofExpr->getType());
Douglas Gregor72564e72009-02-26 23:50:07 +00001645 TypeOfExprType *toe = new (*this,8) TypeOfExprType(tofExpr, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00001646 Types.push_back(toe);
1647 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00001648}
1649
Steve Naroff9752f252007-08-01 18:02:17 +00001650/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
1651/// TypeOfType AST's. The only motivation to unique these nodes would be
1652/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
1653/// an issue. This doesn't effect the type checker, since it operates
1654/// on canonical type's (which are always unique).
Steve Naroffd1861fd2007-07-31 12:34:36 +00001655QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001656 QualType Canonical = getCanonicalType(tofType);
Steve Narofff83820b2009-01-27 22:08:43 +00001657 TypeOfType *tot = new (*this,8) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00001658 Types.push_back(tot);
1659 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00001660}
1661
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00001662/// getDecltypeForExpr - Given an expr, will return the decltype for that
1663/// expression, according to the rules in C++0x [dcl.type.simple]p4
1664static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00001665 if (e->isTypeDependent())
1666 return Context.DependentTy;
1667
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00001668 // If e is an id expression or a class member access, decltype(e) is defined
1669 // as the type of the entity named by e.
1670 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
1671 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
1672 return VD->getType();
1673 }
1674 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
1675 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
1676 return FD->getType();
1677 }
1678 // If e is a function call or an invocation of an overloaded operator,
1679 // (parentheses around e are ignored), decltype(e) is defined as the
1680 // return type of that function.
1681 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
1682 return CE->getCallReturnType();
1683
1684 QualType T = e->getType();
1685
1686 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
1687 // defined as T&, otherwise decltype(e) is defined as T.
1688 if (e->isLvalue(Context) == Expr::LV_Valid)
1689 T = Context.getLValueReferenceType(T);
1690
1691 return T;
1692}
1693
Anders Carlsson395b4752009-06-24 19:06:50 +00001694/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
1695/// DecltypeType AST's. The only motivation to unique these nodes would be
1696/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
1697/// an issue. This doesn't effect the type checker, since it operates
1698/// on canonical type's (which are always unique).
1699QualType ASTContext::getDecltypeType(Expr *e) {
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00001700 QualType T = getDecltypeForExpr(e, *this);
1701 DecltypeType *dt = new (*this, 8) DecltypeType(e, getCanonicalType(T));
Anders Carlsson395b4752009-06-24 19:06:50 +00001702 Types.push_back(dt);
1703 return QualType(dt, 0);
1704}
1705
Reid Spencer5f016e22007-07-11 17:01:13 +00001706/// getTagDeclType - Return the unique reference to the type for the
1707/// specified TagDecl (struct/union/class/enum) decl.
1708QualType ASTContext::getTagDeclType(TagDecl *Decl) {
Ted Kremenekd778f882007-11-26 21:16:01 +00001709 assert (Decl);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001710 return getTypeDeclType(Decl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001711}
1712
1713/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
1714/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
1715/// needs to agree with the definition in <stddef.h>.
1716QualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00001717 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00001718}
1719
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00001720/// getSignedWCharType - Return the type of "signed wchar_t".
1721/// Used when in C++, as a GCC extension.
1722QualType ASTContext::getSignedWCharType() const {
1723 // FIXME: derive from "Target" ?
1724 return WCharTy;
1725}
1726
1727/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
1728/// Used when in C++, as a GCC extension.
1729QualType ASTContext::getUnsignedWCharType() const {
1730 // FIXME: derive from "Target" ?
1731 return UnsignedIntTy;
1732}
1733
Chris Lattner8b9023b2007-07-13 03:05:23 +00001734/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
1735/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
1736QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00001737 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00001738}
1739
Chris Lattnere6327742008-04-02 05:18:44 +00001740//===----------------------------------------------------------------------===//
1741// Type Operators
1742//===----------------------------------------------------------------------===//
1743
Chris Lattner77c96472008-04-06 22:41:35 +00001744/// getCanonicalType - Return the canonical (structural) type corresponding to
1745/// the specified potentially non-canonical type. The non-canonical version
1746/// of a type may have many "decorated" versions of types. Decorators can
1747/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
1748/// to be free of any of these, allowing two canonical types to be compared
1749/// for exact equality with a simple pointer comparison.
1750QualType ASTContext::getCanonicalType(QualType T) {
1751 QualType CanType = T.getTypePtr()->getCanonicalTypeInternal();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001752
1753 // If the result has type qualifiers, make sure to canonicalize them as well.
1754 unsigned TypeQuals = T.getCVRQualifiers() | CanType.getCVRQualifiers();
1755 if (TypeQuals == 0) return CanType;
1756
1757 // If the type qualifiers are on an array type, get the canonical type of the
1758 // array with the qualifiers applied to the element type.
1759 ArrayType *AT = dyn_cast<ArrayType>(CanType);
1760 if (!AT)
1761 return CanType.getQualifiedType(TypeQuals);
1762
1763 // Get the canonical version of the element with the extra qualifiers on it.
1764 // This can recursively sink qualifiers through multiple levels of arrays.
1765 QualType NewEltTy=AT->getElementType().getWithAdditionalQualifiers(TypeQuals);
1766 NewEltTy = getCanonicalType(NewEltTy);
1767
1768 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
1769 return getConstantArrayType(NewEltTy, CAT->getSize(),CAT->getSizeModifier(),
1770 CAT->getIndexTypeQualifier());
1771 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
1772 return getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
1773 IAT->getIndexTypeQualifier());
1774
Douglas Gregor898574e2008-12-05 23:32:09 +00001775 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
1776 return getDependentSizedArrayType(NewEltTy, DSAT->getSizeExpr(),
1777 DSAT->getSizeModifier(),
1778 DSAT->getIndexTypeQualifier());
1779
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001780 VariableArrayType *VAT = cast<VariableArrayType>(AT);
1781 return getVariableArrayType(NewEltTy, VAT->getSizeExpr(),
1782 VAT->getSizeModifier(),
1783 VAT->getIndexTypeQualifier());
1784}
1785
Douglas Gregor7da97d02009-05-10 22:57:19 +00001786Decl *ASTContext::getCanonicalDecl(Decl *D) {
Douglas Gregorc4ccf012009-05-10 22:59:12 +00001787 if (!D)
1788 return 0;
1789
Douglas Gregor7da97d02009-05-10 22:57:19 +00001790 if (TagDecl *Tag = dyn_cast<TagDecl>(D)) {
1791 QualType T = getTagDeclType(Tag);
1792 return cast<TagDecl>(cast<TagType>(T.getTypePtr()->CanonicalType)
1793 ->getDecl());
1794 }
1795
1796 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(D)) {
1797 while (Template->getPreviousDeclaration())
1798 Template = Template->getPreviousDeclaration();
1799 return Template;
1800 }
1801
1802 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
1803 while (Function->getPreviousDeclaration())
1804 Function = Function->getPreviousDeclaration();
1805 return const_cast<FunctionDecl *>(Function);
1806 }
1807
Douglas Gregor127102b2009-06-29 20:59:39 +00001808 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
1809 while (FunTmpl->getPreviousDeclaration())
1810 FunTmpl = FunTmpl->getPreviousDeclaration();
1811 return FunTmpl;
1812 }
1813
Douglas Gregor7da97d02009-05-10 22:57:19 +00001814 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
1815 while (Var->getPreviousDeclaration())
1816 Var = Var->getPreviousDeclaration();
1817 return const_cast<VarDecl *>(Var);
1818 }
1819
1820 return D;
1821}
1822
Douglas Gregor25a3ef72009-05-07 06:41:52 +00001823TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
1824 // If this template name refers to a template, the canonical
1825 // template name merely stores the template itself.
1826 if (TemplateDecl *Template = Name.getAsTemplateDecl())
Douglas Gregor7da97d02009-05-10 22:57:19 +00001827 return TemplateName(cast<TemplateDecl>(getCanonicalDecl(Template)));
Douglas Gregor25a3ef72009-05-07 06:41:52 +00001828
1829 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
1830 assert(DTN && "Non-dependent template names must refer to template decls.");
1831 return DTN->CanonicalTemplateName;
1832}
1833
Douglas Gregord57959a2009-03-27 23:10:48 +00001834NestedNameSpecifier *
1835ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
1836 if (!NNS)
1837 return 0;
1838
1839 switch (NNS->getKind()) {
1840 case NestedNameSpecifier::Identifier:
1841 // Canonicalize the prefix but keep the identifier the same.
1842 return NestedNameSpecifier::Create(*this,
1843 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
1844 NNS->getAsIdentifier());
1845
1846 case NestedNameSpecifier::Namespace:
1847 // A namespace is canonical; build a nested-name-specifier with
1848 // this namespace and no prefix.
1849 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
1850
1851 case NestedNameSpecifier::TypeSpec:
1852 case NestedNameSpecifier::TypeSpecWithTemplate: {
1853 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
1854 NestedNameSpecifier *Prefix = 0;
1855
1856 // FIXME: This isn't the right check!
1857 if (T->isDependentType())
1858 Prefix = getCanonicalNestedNameSpecifier(NNS->getPrefix());
1859
1860 return NestedNameSpecifier::Create(*this, Prefix,
1861 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
1862 T.getTypePtr());
1863 }
1864
1865 case NestedNameSpecifier::Global:
1866 // The global specifier is canonical and unique.
1867 return NNS;
1868 }
1869
1870 // Required to silence a GCC warning
1871 return 0;
1872}
1873
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001874
1875const ArrayType *ASTContext::getAsArrayType(QualType T) {
1876 // Handle the non-qualified case efficiently.
1877 if (T.getCVRQualifiers() == 0) {
1878 // Handle the common positive case fast.
1879 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
1880 return AT;
1881 }
1882
1883 // Handle the common negative case fast, ignoring CVR qualifiers.
1884 QualType CType = T->getCanonicalTypeInternal();
1885
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001886 // Make sure to look through type qualifiers (like ExtQuals) for the negative
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001887 // test.
1888 if (!isa<ArrayType>(CType) &&
1889 !isa<ArrayType>(CType.getUnqualifiedType()))
1890 return 0;
1891
1892 // Apply any CVR qualifiers from the array type to the element type. This
1893 // implements C99 6.7.3p8: "If the specification of an array type includes
1894 // any type qualifiers, the element type is so qualified, not the array type."
1895
1896 // If we get here, we either have type qualifiers on the type, or we have
1897 // sugar such as a typedef in the way. If we have type qualifiers on the type
1898 // we must propagate them down into the elemeng type.
1899 unsigned CVRQuals = T.getCVRQualifiers();
1900 unsigned AddrSpace = 0;
1901 Type *Ty = T.getTypePtr();
1902
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001903 // Rip through ExtQualType's and typedefs to get to a concrete type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001904 while (1) {
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001905 if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(Ty)) {
1906 AddrSpace = EXTQT->getAddressSpace();
1907 Ty = EXTQT->getBaseType();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001908 } else {
1909 T = Ty->getDesugaredType();
1910 if (T.getTypePtr() == Ty && T.getCVRQualifiers() == 0)
1911 break;
1912 CVRQuals |= T.getCVRQualifiers();
1913 Ty = T.getTypePtr();
1914 }
1915 }
1916
1917 // If we have a simple case, just return now.
1918 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
1919 if (ATy == 0 || (AddrSpace == 0 && CVRQuals == 0))
1920 return ATy;
1921
1922 // Otherwise, we have an array and we have qualifiers on it. Push the
1923 // qualifiers into the array element type and return a new array type.
1924 // Get the canonical version of the element with the extra qualifiers on it.
1925 // This can recursively sink qualifiers through multiple levels of arrays.
1926 QualType NewEltTy = ATy->getElementType();
1927 if (AddrSpace)
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001928 NewEltTy = getAddrSpaceQualType(NewEltTy, AddrSpace);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001929 NewEltTy = NewEltTy.getWithAdditionalQualifiers(CVRQuals);
1930
1931 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
1932 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
1933 CAT->getSizeModifier(),
1934 CAT->getIndexTypeQualifier()));
1935 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
1936 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
1937 IAT->getSizeModifier(),
1938 IAT->getIndexTypeQualifier()));
Douglas Gregor898574e2008-12-05 23:32:09 +00001939
Douglas Gregor898574e2008-12-05 23:32:09 +00001940 if (const DependentSizedArrayType *DSAT
1941 = dyn_cast<DependentSizedArrayType>(ATy))
1942 return cast<ArrayType>(
1943 getDependentSizedArrayType(NewEltTy,
1944 DSAT->getSizeExpr(),
1945 DSAT->getSizeModifier(),
1946 DSAT->getIndexTypeQualifier()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001947
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001948 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
1949 return cast<ArrayType>(getVariableArrayType(NewEltTy, VAT->getSizeExpr(),
1950 VAT->getSizeModifier(),
1951 VAT->getIndexTypeQualifier()));
Chris Lattner77c96472008-04-06 22:41:35 +00001952}
1953
1954
Chris Lattnere6327742008-04-02 05:18:44 +00001955/// getArrayDecayedType - Return the properly qualified result of decaying the
1956/// specified array type to a pointer. This operation is non-trivial when
1957/// handling typedefs etc. The canonical type of "T" must be an array type,
1958/// this returns a pointer to a properly qualified element of the array.
1959///
1960/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
1961QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001962 // Get the element type with 'getAsArrayType' so that we don't lose any
1963 // typedefs in the element type of the array. This also handles propagation
1964 // of type qualifiers from the array type into the element type if present
1965 // (C99 6.7.3p8).
1966 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
1967 assert(PrettyArrayType && "Not an array type!");
Chris Lattnere6327742008-04-02 05:18:44 +00001968
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001969 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00001970
1971 // int x[restrict 4] -> int *restrict
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001972 return PtrTy.getQualifiedType(PrettyArrayType->getIndexTypeQualifier());
Chris Lattnere6327742008-04-02 05:18:44 +00001973}
1974
Daniel Dunbard786f6a2009-01-05 22:14:37 +00001975QualType ASTContext::getBaseElementType(const VariableArrayType *VAT) {
Anders Carlsson6183a992008-12-21 03:44:36 +00001976 QualType ElemTy = VAT->getElementType();
1977
1978 if (const VariableArrayType *VAT = getAsVariableArrayType(ElemTy))
1979 return getBaseElementType(VAT);
1980
1981 return ElemTy;
1982}
1983
Reid Spencer5f016e22007-07-11 17:01:13 +00001984/// getFloatingRank - Return a relative rank for floating point types.
1985/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00001986static FloatingRank getFloatingRank(QualType T) {
Christopher Lambebb97e92008-02-04 02:31:56 +00001987 if (const ComplexType *CT = T->getAsComplexType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001988 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00001989
Daniel Dunbard786f6a2009-01-05 22:14:37 +00001990 assert(T->getAsBuiltinType() && "getFloatingRank(): not a floating type");
Christopher Lambebb97e92008-02-04 02:31:56 +00001991 switch (T->getAsBuiltinType()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00001992 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00001993 case BuiltinType::Float: return FloatRank;
1994 case BuiltinType::Double: return DoubleRank;
1995 case BuiltinType::LongDouble: return LongDoubleRank;
1996 }
1997}
1998
Steve Naroff716c7302007-08-27 01:41:48 +00001999/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2000/// point or a complex type (based on typeDomain/typeSize).
2001/// 'typeDomain' is a real floating point or complex type.
2002/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00002003QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2004 QualType Domain) const {
2005 FloatingRank EltRank = getFloatingRank(Size);
2006 if (Domain->isComplexType()) {
2007 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00002008 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00002009 case FloatRank: return FloatComplexTy;
2010 case DoubleRank: return DoubleComplexTy;
2011 case LongDoubleRank: return LongDoubleComplexTy;
2012 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002013 }
Chris Lattner1361b112008-04-06 23:58:54 +00002014
2015 assert(Domain->isRealFloatingType() && "Unknown domain!");
2016 switch (EltRank) {
2017 default: assert(0 && "getFloatingRank(): illegal value for rank");
2018 case FloatRank: return FloatTy;
2019 case DoubleRank: return DoubleTy;
2020 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00002021 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002022}
2023
Chris Lattner7cfeb082008-04-06 23:55:33 +00002024/// getFloatingTypeOrder - Compare the rank of the two specified floating
2025/// point types, ignoring the domain of the type (i.e. 'double' ==
2026/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
2027/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00002028int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2029 FloatingRank LHSR = getFloatingRank(LHS);
2030 FloatingRank RHSR = getFloatingRank(RHS);
2031
2032 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002033 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00002034 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002035 return 1;
2036 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002037}
2038
Chris Lattnerf52ab252008-04-06 22:59:24 +00002039/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2040/// routine will assert if passed a built-in type that isn't an integer or enum,
2041/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00002042unsigned ASTContext::getIntegerRank(Type *T) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002043 assert(T->isCanonical() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00002044 if (EnumType* ET = dyn_cast<EnumType>(T))
2045 T = ET->getDecl()->getIntegerType().getTypePtr();
2046
2047 // There are two things which impact the integer rank: the width, and
2048 // the ordering of builtins. The builtin ordering is encoded in the
2049 // bottom three bits; the width is encoded in the bits above that.
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002050 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T))
Eli Friedmanf98aba32009-02-13 02:31:07 +00002051 return FWIT->getWidth() << 3;
Eli Friedmanf98aba32009-02-13 02:31:07 +00002052
Chris Lattnerf52ab252008-04-06 22:59:24 +00002053 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00002054 default: assert(0 && "getIntegerRank(): not a built-in integer");
2055 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002056 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002057 case BuiltinType::Char_S:
2058 case BuiltinType::Char_U:
2059 case BuiltinType::SChar:
2060 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002061 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002062 case BuiltinType::Short:
2063 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002064 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002065 case BuiltinType::Int:
2066 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002067 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002068 case BuiltinType::Long:
2069 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002070 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002071 case BuiltinType::LongLong:
2072 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002073 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00002074 case BuiltinType::Int128:
2075 case BuiltinType::UInt128:
2076 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00002077 }
2078}
2079
Chris Lattner7cfeb082008-04-06 23:55:33 +00002080/// getIntegerTypeOrder - Returns the highest ranked integer type:
2081/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
2082/// LHS < RHS, return -1.
2083int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002084 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2085 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00002086 if (LHSC == RHSC) return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00002087
Chris Lattnerf52ab252008-04-06 22:59:24 +00002088 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2089 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002090
Chris Lattner7cfeb082008-04-06 23:55:33 +00002091 unsigned LHSRank = getIntegerRank(LHSC);
2092 unsigned RHSRank = getIntegerRank(RHSC);
Reid Spencer5f016e22007-07-11 17:01:13 +00002093
Chris Lattner7cfeb082008-04-06 23:55:33 +00002094 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2095 if (LHSRank == RHSRank) return 0;
2096 return LHSRank > RHSRank ? 1 : -1;
2097 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002098
Chris Lattner7cfeb082008-04-06 23:55:33 +00002099 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2100 if (LHSUnsigned) {
2101 // If the unsigned [LHS] type is larger, return it.
2102 if (LHSRank >= RHSRank)
2103 return 1;
2104
2105 // If the signed type can represent all values of the unsigned type, it
2106 // wins. Because we are dealing with 2's complement and types that are
2107 // powers of two larger than each other, this is always safe.
2108 return -1;
2109 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00002110
Chris Lattner7cfeb082008-04-06 23:55:33 +00002111 // If the unsigned [RHS] type is larger, return it.
2112 if (RHSRank >= LHSRank)
2113 return -1;
2114
2115 // If the signed type can represent all values of the unsigned type, it
2116 // wins. Because we are dealing with 2's complement and types that are
2117 // powers of two larger than each other, this is always safe.
2118 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002119}
Anders Carlsson71993dd2007-08-17 05:31:46 +00002120
2121// getCFConstantStringType - Return the type used for constant CFStrings.
2122QualType ASTContext::getCFConstantStringType() {
2123 if (!CFConstantStringTypeDecl) {
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002124 CFConstantStringTypeDecl =
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002125 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002126 &Idents.get("NSConstantString"));
Anders Carlssonf06273f2007-11-19 00:25:30 +00002127 QualType FieldTypes[4];
Anders Carlsson71993dd2007-08-17 05:31:46 +00002128
2129 // const int *isa;
2130 FieldTypes[0] = getPointerType(IntTy.getQualifiedType(QualType::Const));
Anders Carlssonf06273f2007-11-19 00:25:30 +00002131 // int flags;
2132 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00002133 // const char *str;
Anders Carlssonf06273f2007-11-19 00:25:30 +00002134 FieldTypes[2] = getPointerType(CharTy.getQualifiedType(QualType::Const));
Anders Carlsson71993dd2007-08-17 05:31:46 +00002135 // long length;
Anders Carlssonf06273f2007-11-19 00:25:30 +00002136 FieldTypes[3] = LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002137
Anders Carlsson71993dd2007-08-17 05:31:46 +00002138 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002139 for (unsigned i = 0; i < 4; ++i) {
2140 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
2141 SourceLocation(), 0,
2142 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002143 /*Mutable=*/false);
Douglas Gregor6ab35242009-04-09 21:40:53 +00002144 CFConstantStringTypeDecl->addDecl(*this, Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002145 }
2146
2147 CFConstantStringTypeDecl->completeDefinition(*this);
Anders Carlsson71993dd2007-08-17 05:31:46 +00002148 }
2149
2150 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00002151}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002152
Douglas Gregor319ac892009-04-23 22:29:11 +00002153void ASTContext::setCFConstantStringType(QualType T) {
2154 const RecordType *Rec = T->getAsRecordType();
2155 assert(Rec && "Invalid CFConstantStringType");
2156 CFConstantStringTypeDecl = Rec->getDecl();
2157}
2158
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002159QualType ASTContext::getObjCFastEnumerationStateType()
2160{
2161 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00002162 ObjCFastEnumerationStateTypeDecl =
2163 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2164 &Idents.get("__objcFastEnumerationState"));
2165
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002166 QualType FieldTypes[] = {
2167 UnsignedLongTy,
2168 getPointerType(ObjCIdType),
2169 getPointerType(UnsignedLongTy),
2170 getConstantArrayType(UnsignedLongTy,
2171 llvm::APInt(32, 5), ArrayType::Normal, 0)
2172 };
2173
Douglas Gregor44b43212008-12-11 16:49:14 +00002174 for (size_t i = 0; i < 4; ++i) {
2175 FieldDecl *Field = FieldDecl::Create(*this,
2176 ObjCFastEnumerationStateTypeDecl,
2177 SourceLocation(), 0,
2178 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002179 /*Mutable=*/false);
Douglas Gregor6ab35242009-04-09 21:40:53 +00002180 ObjCFastEnumerationStateTypeDecl->addDecl(*this, Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002181 }
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002182
Douglas Gregor44b43212008-12-11 16:49:14 +00002183 ObjCFastEnumerationStateTypeDecl->completeDefinition(*this);
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002184 }
2185
2186 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2187}
2188
Douglas Gregor319ac892009-04-23 22:29:11 +00002189void ASTContext::setObjCFastEnumerationStateType(QualType T) {
2190 const RecordType *Rec = T->getAsRecordType();
2191 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
2192 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
2193}
2194
Anders Carlssone8c49532007-10-29 06:33:42 +00002195// This returns true if a type has been typedefed to BOOL:
2196// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00002197static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00002198 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00002199 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
2200 return II->isStr("BOOL");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002201
2202 return false;
2203}
2204
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002205/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002206/// purpose.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002207int ASTContext::getObjCEncodingTypeSize(QualType type) {
Chris Lattner98be4942008-03-05 18:54:05 +00002208 uint64_t sz = getTypeSize(type);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002209
2210 // Make all integer and enum types at least as large as an int
2211 if (sz > 0 && type->isIntegralType())
Chris Lattner98be4942008-03-05 18:54:05 +00002212 sz = std::max(sz, getTypeSize(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002213 // Treat arrays as pointers, since that's how they're passed in.
2214 else if (type->isArrayType())
Chris Lattner98be4942008-03-05 18:54:05 +00002215 sz = getTypeSize(VoidPtrTy);
2216 return sz / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002217}
2218
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002219/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002220/// declaration.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002221void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00002222 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002223 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002224 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002225 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002226 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002227 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002228 // Compute size of all parameters.
2229 // Start with computing size of a pointer in number of bytes.
2230 // FIXME: There might(should) be a better way of doing this computation!
2231 SourceLocation Loc;
Chris Lattner98be4942008-03-05 18:54:05 +00002232 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002233 // The first two arguments (self and _cmd) are pointers; account for
2234 // their size.
2235 int ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00002236 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2237 E = Decl->param_end(); PI != E; ++PI) {
2238 QualType PType = (*PI)->getType();
2239 int sz = getObjCEncodingTypeSize(PType);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002240 assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002241 ParmOffset += sz;
2242 }
2243 S += llvm::utostr(ParmOffset);
2244 S += "@0:";
2245 S += llvm::utostr(PtrSize);
2246
2247 // Argument types.
2248 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00002249 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2250 E = Decl->param_end(); PI != E; ++PI) {
2251 ParmVarDecl *PVDecl = *PI;
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00002252 QualType PType = PVDecl->getOriginalType();
2253 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00002254 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
2255 // Use array's original type only if it has known number of
2256 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00002257 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00002258 PType = PVDecl->getType();
2259 } else if (PType->isFunctionType())
2260 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002261 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002262 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00002263 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002264 getObjCEncodingForType(PType, S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002265 S += llvm::utostr(ParmOffset);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002266 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002267 }
2268}
2269
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002270/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00002271/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002272/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
2273/// NULL when getting encodings for protocol properties.
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00002274/// Property attributes are stored as a comma-delimited C string. The simple
2275/// attributes readonly and bycopy are encoded as single characters. The
2276/// parametrized attributes, getter=name, setter=name, and ivar=name, are
2277/// encoded as single characters, followed by an identifier. Property types
2278/// are also encoded as a parametrized attribute. The characters used to encode
2279/// these attributes are defined by the following enumeration:
2280/// @code
2281/// enum PropertyAttributes {
2282/// kPropertyReadOnly = 'R', // property is read-only.
2283/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
2284/// kPropertyByref = '&', // property is a reference to the value last assigned
2285/// kPropertyDynamic = 'D', // property is dynamic
2286/// kPropertyGetter = 'G', // followed by getter selector name
2287/// kPropertySetter = 'S', // followed by setter selector name
2288/// kPropertyInstanceVariable = 'V' // followed by instance variable name
2289/// kPropertyType = 't' // followed by old-style type encoding.
2290/// kPropertyWeak = 'W' // 'weak' property
2291/// kPropertyStrong = 'P' // property GC'able
2292/// kPropertyNonAtomic = 'N' // property non-atomic
2293/// };
2294/// @endcode
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002295void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
2296 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00002297 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002298 // Collect information from the property implementation decl(s).
2299 bool Dynamic = false;
2300 ObjCPropertyImplDecl *SynthesizePID = 0;
2301
2302 // FIXME: Duplicated code due to poor abstraction.
2303 if (Container) {
2304 if (const ObjCCategoryImplDecl *CID =
2305 dyn_cast<ObjCCategoryImplDecl>(Container)) {
2306 for (ObjCCategoryImplDecl::propimpl_iterator
Douglas Gregor653f1b12009-04-23 01:02:12 +00002307 i = CID->propimpl_begin(*this), e = CID->propimpl_end(*this);
2308 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002309 ObjCPropertyImplDecl *PID = *i;
2310 if (PID->getPropertyDecl() == PD) {
2311 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2312 Dynamic = true;
2313 } else {
2314 SynthesizePID = PID;
2315 }
2316 }
2317 }
2318 } else {
Chris Lattner61710852008-10-05 17:34:18 +00002319 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002320 for (ObjCCategoryImplDecl::propimpl_iterator
Douglas Gregor653f1b12009-04-23 01:02:12 +00002321 i = OID->propimpl_begin(*this), e = OID->propimpl_end(*this);
2322 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002323 ObjCPropertyImplDecl *PID = *i;
2324 if (PID->getPropertyDecl() == PD) {
2325 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2326 Dynamic = true;
2327 } else {
2328 SynthesizePID = PID;
2329 }
2330 }
2331 }
2332 }
2333 }
2334
2335 // FIXME: This is not very efficient.
2336 S = "T";
2337
2338 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002339 // GCC has some special rules regarding encoding of properties which
2340 // closely resembles encoding of ivars.
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002341 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002342 true /* outermost type */,
2343 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002344
2345 if (PD->isReadOnly()) {
2346 S += ",R";
2347 } else {
2348 switch (PD->getSetterKind()) {
2349 case ObjCPropertyDecl::Assign: break;
2350 case ObjCPropertyDecl::Copy: S += ",C"; break;
2351 case ObjCPropertyDecl::Retain: S += ",&"; break;
2352 }
2353 }
2354
2355 // It really isn't clear at all what this means, since properties
2356 // are "dynamic by default".
2357 if (Dynamic)
2358 S += ",D";
2359
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002360 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
2361 S += ",N";
2362
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002363 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
2364 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002365 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002366 }
2367
2368 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
2369 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002370 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002371 }
2372
2373 if (SynthesizePID) {
2374 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
2375 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00002376 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002377 }
2378
2379 // FIXME: OBJCGC: weak & strong
2380}
2381
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002382/// getLegacyIntegralTypeEncoding -
2383/// Another legacy compatibility encoding: 32-bit longs are encoded as
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002384/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002385/// 'i' or 'I' instead if encoding a struct field, or a pointer!
2386///
2387void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
2388 if (dyn_cast<TypedefType>(PointeeTy.getTypePtr())) {
2389 if (const BuiltinType *BT = PointeeTy->getAsBuiltinType()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002390 if (BT->getKind() == BuiltinType::ULong &&
2391 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002392 PointeeTy = UnsignedIntTy;
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002393 else
2394 if (BT->getKind() == BuiltinType::Long &&
2395 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002396 PointeeTy = IntTy;
2397 }
2398 }
2399}
2400
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002401void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002402 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002403 // We follow the behavior of gcc, expanding structures which are
2404 // directly pointed to, and expanding embedded structures. Note that
2405 // these rules are sufficient to prevent recursive encoding of the
2406 // same type.
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00002407 getObjCEncodingForTypeImpl(T, S, true, true, Field,
2408 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002409}
2410
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002411static void EncodeBitField(const ASTContext *Context, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002412 const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002413 const Expr *E = FD->getBitWidth();
2414 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
2415 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Eli Friedman9a901bb2009-04-26 19:19:15 +00002416 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002417 S += 'b';
2418 S += llvm::utostr(N);
2419}
2420
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002421void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
2422 bool ExpandPointedToStructures,
2423 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002424 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002425 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002426 bool EncodingProperty) {
Anders Carlssone8c49532007-10-29 06:33:42 +00002427 if (const BuiltinType *BT = T->getAsBuiltinType()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002428 if (FD && FD->isBitField()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002429 EncodeBitField(this, S, FD);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002430 }
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002431 else {
2432 char encoding;
2433 switch (BT->getKind()) {
2434 default: assert(0 && "Unhandled builtin type kind");
2435 case BuiltinType::Void: encoding = 'v'; break;
2436 case BuiltinType::Bool: encoding = 'B'; break;
2437 case BuiltinType::Char_U:
2438 case BuiltinType::UChar: encoding = 'C'; break;
2439 case BuiltinType::UShort: encoding = 'S'; break;
2440 case BuiltinType::UInt: encoding = 'I'; break;
Fariborz Jahanian72696e12009-02-11 22:31:45 +00002441 case BuiltinType::ULong:
2442 encoding =
2443 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
2444 break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002445 case BuiltinType::UInt128: encoding = 'T'; break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002446 case BuiltinType::ULongLong: encoding = 'Q'; break;
2447 case BuiltinType::Char_S:
2448 case BuiltinType::SChar: encoding = 'c'; break;
2449 case BuiltinType::Short: encoding = 's'; break;
2450 case BuiltinType::Int: encoding = 'i'; break;
Fariborz Jahanian72696e12009-02-11 22:31:45 +00002451 case BuiltinType::Long:
2452 encoding =
2453 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
2454 break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002455 case BuiltinType::LongLong: encoding = 'q'; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002456 case BuiltinType::Int128: encoding = 't'; break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002457 case BuiltinType::Float: encoding = 'f'; break;
2458 case BuiltinType::Double: encoding = 'd'; break;
2459 case BuiltinType::LongDouble: encoding = 'd'; break;
2460 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002461
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002462 S += encoding;
2463 }
Anders Carlssonc612f7b2009-04-09 21:55:45 +00002464 } else if (const ComplexType *CT = T->getAsComplexType()) {
2465 S += 'j';
2466 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
2467 false);
2468 } else if (T->isObjCQualifiedIdType()) {
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002469 getObjCEncodingForTypeImpl(getObjCIdType(), S,
2470 ExpandPointedToStructures,
2471 ExpandStructures, FD);
2472 if (FD || EncodingProperty) {
2473 // Note that we do extended encoding of protocol qualifer list
2474 // Only when doing ivar or property encoding.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002475 const ObjCObjectPointerType *QIDT = T->getAsObjCQualifiedIdType();
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002476 S += '"';
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002477 for (ObjCObjectPointerType::qual_iterator I = QIDT->qual_begin(),
Steve Naroff446ee4e2009-05-27 16:21:00 +00002478 E = QIDT->qual_end(); I != E; ++I) {
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002479 S += '<';
Steve Naroff446ee4e2009-05-27 16:21:00 +00002480 S += (*I)->getNameAsString();
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002481 S += '>';
2482 }
2483 S += '"';
2484 }
2485 return;
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002486 }
2487 else if (const PointerType *PT = T->getAsPointerType()) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002488 QualType PointeeTy = PT->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002489 bool isReadOnly = false;
2490 // For historical/compatibility reasons, the read-only qualifier of the
2491 // pointee gets emitted _before_ the '^'. The read-only qualifier of
2492 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
2493 // Also, do not emit the 'r' for anything but the outermost type!
2494 if (dyn_cast<TypedefType>(T.getTypePtr())) {
2495 if (OutermostType && T.isConstQualified()) {
2496 isReadOnly = true;
2497 S += 'r';
2498 }
2499 }
2500 else if (OutermostType) {
2501 QualType P = PointeeTy;
2502 while (P->getAsPointerType())
2503 P = P->getAsPointerType()->getPointeeType();
2504 if (P.isConstQualified()) {
2505 isReadOnly = true;
2506 S += 'r';
2507 }
2508 }
2509 if (isReadOnly) {
2510 // Another legacy compatibility encoding. Some ObjC qualifier and type
2511 // combinations need to be rearranged.
2512 // Rewrite "in const" from "nr" to "rn"
2513 const char * s = S.c_str();
2514 int len = S.length();
2515 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
2516 std::string replace = "rn";
2517 S.replace(S.end()-2, S.end(), replace);
2518 }
2519 }
Steve Naroff389bf462009-02-12 17:52:19 +00002520 if (isObjCIdStructType(PointeeTy)) {
Fariborz Jahanianc2939bc2007-10-30 17:06:23 +00002521 S += '@';
2522 return;
Fariborz Jahanianc166d732008-12-19 00:14:49 +00002523 }
2524 else if (PointeeTy->isObjCInterfaceType()) {
Fariborz Jahanianbb99bde2009-02-16 21:41:04 +00002525 if (!EncodingProperty &&
Fariborz Jahanian225dfd72009-02-16 22:09:26 +00002526 isa<TypedefType>(PointeeTy.getTypePtr())) {
Fariborz Jahanian3e1b16c2008-12-23 21:30:15 +00002527 // Another historical/compatibility reason.
2528 // We encode the underlying type which comes out as
2529 // {...};
2530 S += '^';
2531 getObjCEncodingForTypeImpl(PointeeTy, S,
2532 false, ExpandPointedToStructures,
2533 NULL);
2534 return;
2535 }
Fariborz Jahanianc166d732008-12-19 00:14:49 +00002536 S += '@';
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002537 if (FD || EncodingProperty) {
Fariborz Jahanian86f938b2009-02-21 18:23:24 +00002538 const ObjCInterfaceType *OIT =
2539 PointeeTy.getUnqualifiedType()->getAsObjCInterfaceType();
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002540 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanianadcaf542008-12-20 19:17:01 +00002541 S += '"';
2542 S += OI->getNameAsCString();
Steve Naroff446ee4e2009-05-27 16:21:00 +00002543 for (ObjCInterfaceType::qual_iterator I = OIT->qual_begin(),
2544 E = OIT->qual_end(); I != E; ++I) {
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002545 S += '<';
Steve Naroff446ee4e2009-05-27 16:21:00 +00002546 S += (*I)->getNameAsString();
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002547 S += '>';
2548 }
Fariborz Jahanianadcaf542008-12-20 19:17:01 +00002549 S += '"';
2550 }
Fariborz Jahanianc166d732008-12-19 00:14:49 +00002551 return;
Steve Naroff389bf462009-02-12 17:52:19 +00002552 } else if (isObjCClassStructType(PointeeTy)) {
Anders Carlsson8baaca52007-10-31 02:53:19 +00002553 S += '#';
2554 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002555 } else if (isObjCSelType(PointeeTy)) {
Anders Carlsson8baaca52007-10-31 02:53:19 +00002556 S += ':';
2557 return;
Fariborz Jahanianc2939bc2007-10-30 17:06:23 +00002558 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002559
2560 if (PointeeTy->isCharType()) {
2561 // char pointer types should be encoded as '*' unless it is a
2562 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00002563 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002564 S += '*';
2565 return;
2566 }
2567 }
2568
2569 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002570 getLegacyIntegralTypeEncoding(PointeeTy);
2571
2572 getObjCEncodingForTypeImpl(PointeeTy, S,
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002573 false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002574 NULL);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002575 } else if (const ArrayType *AT =
2576 // Ignore type qualifiers etc.
2577 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00002578 if (isa<IncompleteArrayType>(AT)) {
2579 // Incomplete arrays are encoded as a pointer to the array element.
2580 S += '^';
2581
2582 getObjCEncodingForTypeImpl(AT->getElementType(), S,
2583 false, ExpandStructures, FD);
2584 } else {
2585 S += '[';
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002586
Anders Carlsson559a8332009-02-22 01:38:57 +00002587 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
2588 S += llvm::utostr(CAT->getSize().getZExtValue());
2589 else {
2590 //Variable length arrays are encoded as a regular array with 0 elements.
2591 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
2592 S += '0';
2593 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002594
Anders Carlsson559a8332009-02-22 01:38:57 +00002595 getObjCEncodingForTypeImpl(AT->getElementType(), S,
2596 false, ExpandStructures, FD);
2597 S += ']';
2598 }
Anders Carlssonc0a87b72007-10-30 00:06:20 +00002599 } else if (T->getAsFunctionType()) {
2600 S += '?';
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00002601 } else if (const RecordType *RTy = T->getAsRecordType()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002602 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002603 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00002604 // Anonymous structures print as '?'
2605 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
2606 S += II->getName();
2607 } else {
2608 S += '?';
2609 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002610 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002611 S += '=';
Douglas Gregor6ab35242009-04-09 21:40:53 +00002612 for (RecordDecl::field_iterator Field = RDecl->field_begin(*this),
2613 FieldEnd = RDecl->field_end(*this);
Douglas Gregor44b43212008-12-11 16:49:14 +00002614 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002615 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002616 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00002617 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002618 S += '"';
2619 }
2620
2621 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002622 if (Field->isBitField()) {
2623 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
2624 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002625 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002626 QualType qt = Field->getType();
2627 getLegacyIntegralTypeEncoding(qt);
2628 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002629 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002630 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002631 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00002632 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002633 S += RDecl->isUnion() ? ')' : '}';
Steve Naroff5e711242007-12-12 22:30:11 +00002634 } else if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002635 if (FD && FD->isBitField())
2636 EncodeBitField(this, S, FD);
2637 else
2638 S += 'i';
Steve Naroff485eeff2008-09-24 15:05:44 +00002639 } else if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00002640 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002641 } else if (T->isObjCInterfaceType()) {
2642 // @encode(class_name)
2643 ObjCInterfaceDecl *OI = T->getAsObjCInterfaceType()->getDecl();
2644 S += '{';
2645 const IdentifierInfo *II = OI->getIdentifier();
2646 S += II->getName();
2647 S += '=';
Chris Lattnerf1690852009-03-31 08:48:01 +00002648 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002649 CollectObjCIvars(OI, RecFields);
Chris Lattnerf1690852009-03-31 08:48:01 +00002650 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002651 if (RecFields[i]->isBitField())
2652 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2653 RecFields[i]);
2654 else
2655 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2656 FD);
2657 }
2658 S += '}';
2659 }
2660 else
Steve Narofff69cc5d2008-01-30 19:17:43 +00002661 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002662}
2663
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002664void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002665 std::string& S) const {
2666 if (QT & Decl::OBJC_TQ_In)
2667 S += 'n';
2668 if (QT & Decl::OBJC_TQ_Inout)
2669 S += 'N';
2670 if (QT & Decl::OBJC_TQ_Out)
2671 S += 'o';
2672 if (QT & Decl::OBJC_TQ_Bycopy)
2673 S += 'O';
2674 if (QT & Decl::OBJC_TQ_Byref)
2675 S += 'R';
2676 if (QT & Decl::OBJC_TQ_Oneway)
2677 S += 'V';
2678}
2679
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002680void ASTContext::setBuiltinVaListType(QualType T)
2681{
2682 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
2683
2684 BuiltinVaListType = T;
2685}
2686
Douglas Gregor319ac892009-04-23 22:29:11 +00002687void ASTContext::setObjCIdType(QualType T)
Steve Naroff7e219e42007-10-15 14:41:52 +00002688{
Douglas Gregor319ac892009-04-23 22:29:11 +00002689 ObjCIdType = T;
2690
2691 const TypedefType *TT = T->getAsTypedefType();
2692 if (!TT)
2693 return;
2694
2695 TypedefDecl *TD = TT->getDecl();
Steve Naroff7e219e42007-10-15 14:41:52 +00002696
2697 // typedef struct objc_object *id;
2698 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00002699 // User error - caller will issue diagnostics.
2700 if (!ptr)
2701 return;
Steve Naroff7e219e42007-10-15 14:41:52 +00002702 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00002703 // User error - caller will issue diagnostics.
2704 if (!rec)
2705 return;
Steve Naroff7e219e42007-10-15 14:41:52 +00002706 IdStructType = rec;
2707}
2708
Douglas Gregor319ac892009-04-23 22:29:11 +00002709void ASTContext::setObjCSelType(QualType T)
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002710{
Douglas Gregor319ac892009-04-23 22:29:11 +00002711 ObjCSelType = T;
2712
2713 const TypedefType *TT = T->getAsTypedefType();
2714 if (!TT)
2715 return;
2716 TypedefDecl *TD = TT->getDecl();
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002717
2718 // typedef struct objc_selector *SEL;
2719 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00002720 if (!ptr)
2721 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002722 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00002723 if (!rec)
2724 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002725 SelStructType = rec;
2726}
2727
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002728void ASTContext::setObjCProtoType(QualType QT)
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00002729{
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002730 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00002731}
2732
Douglas Gregor319ac892009-04-23 22:29:11 +00002733void ASTContext::setObjCClassType(QualType T)
Anders Carlsson8baaca52007-10-31 02:53:19 +00002734{
Douglas Gregor319ac892009-04-23 22:29:11 +00002735 ObjCClassType = T;
2736
2737 const TypedefType *TT = T->getAsTypedefType();
2738 if (!TT)
2739 return;
2740 TypedefDecl *TD = TT->getDecl();
Anders Carlsson8baaca52007-10-31 02:53:19 +00002741
2742 // typedef struct objc_class *Class;
2743 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
2744 assert(ptr && "'Class' incorrectly typed");
2745 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
2746 assert(rec && "'Class' incorrectly typed");
2747 ClassStructType = rec;
2748}
2749
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002750void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
2751 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00002752 "'NSConstantString' type already set!");
2753
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002754 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00002755}
2756
Douglas Gregor7532dc62009-03-30 22:58:21 +00002757/// \brief Retrieve the template name that represents a qualified
2758/// template name such as \c std::vector.
2759TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
2760 bool TemplateKeyword,
2761 TemplateDecl *Template) {
2762 llvm::FoldingSetNodeID ID;
2763 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
2764
2765 void *InsertPos = 0;
2766 QualifiedTemplateName *QTN =
2767 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
2768 if (!QTN) {
2769 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
2770 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
2771 }
2772
2773 return TemplateName(QTN);
2774}
2775
2776/// \brief Retrieve the template name that represents a dependent
2777/// template name such as \c MetaFun::template apply.
2778TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
2779 const IdentifierInfo *Name) {
2780 assert(NNS->isDependent() && "Nested name specifier must be dependent");
2781
2782 llvm::FoldingSetNodeID ID;
2783 DependentTemplateName::Profile(ID, NNS, Name);
2784
2785 void *InsertPos = 0;
2786 DependentTemplateName *QTN =
2787 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
2788
2789 if (QTN)
2790 return TemplateName(QTN);
2791
2792 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2793 if (CanonNNS == NNS) {
2794 QTN = new (*this,4) DependentTemplateName(NNS, Name);
2795 } else {
2796 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
2797 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
2798 }
2799
2800 DependentTemplateNames.InsertNode(QTN, InsertPos);
2801 return TemplateName(QTN);
2802}
2803
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002804/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00002805/// TargetInfo, produce the corresponding type. The unsigned @p Type
2806/// is actually a value of type @c TargetInfo::IntType.
2807QualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002808 switch (Type) {
2809 case TargetInfo::NoInt: return QualType();
2810 case TargetInfo::SignedShort: return ShortTy;
2811 case TargetInfo::UnsignedShort: return UnsignedShortTy;
2812 case TargetInfo::SignedInt: return IntTy;
2813 case TargetInfo::UnsignedInt: return UnsignedIntTy;
2814 case TargetInfo::SignedLong: return LongTy;
2815 case TargetInfo::UnsignedLong: return UnsignedLongTy;
2816 case TargetInfo::SignedLongLong: return LongLongTy;
2817 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
2818 }
2819
2820 assert(false && "Unhandled TargetInfo::IntType value");
Daniel Dunbarb3ac5432008-11-11 01:16:00 +00002821 return QualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002822}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00002823
2824//===----------------------------------------------------------------------===//
2825// Type Predicates.
2826//===----------------------------------------------------------------------===//
2827
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00002828/// isObjCNSObjectType - Return true if this is an NSObject object using
2829/// NSObject attribute on a c-style pointer type.
2830/// FIXME - Make it work directly on types.
2831///
2832bool ASTContext::isObjCNSObjectType(QualType Ty) const {
2833 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
2834 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00002835 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00002836 return true;
2837 }
2838 return false;
2839}
2840
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00002841/// isObjCObjectPointerType - Returns true if type is an Objective-C pointer
2842/// to an object type. This includes "id" and "Class" (two 'special' pointers
2843/// to struct), Interface* (pointer to ObjCInterfaceType) and id<P> (qualified
2844/// ID type).
2845bool ASTContext::isObjCObjectPointerType(QualType Ty) const {
Steve Naroffd4617772009-02-23 18:36:16 +00002846 if (Ty->isObjCQualifiedIdType())
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00002847 return true;
2848
Steve Naroff6ae98502008-10-21 18:24:04 +00002849 // Blocks are objects.
2850 if (Ty->isBlockPointerType())
2851 return true;
2852
2853 // All other object types are pointers.
Chris Lattner16ede0e2009-04-12 23:51:02 +00002854 const PointerType *PT = Ty->getAsPointerType();
2855 if (PT == 0)
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00002856 return false;
2857
Chris Lattner16ede0e2009-04-12 23:51:02 +00002858 // If this a pointer to an interface (e.g. NSString*), it is ok.
2859 if (PT->getPointeeType()->isObjCInterfaceType() ||
2860 // If is has NSObject attribute, OK as well.
2861 isObjCNSObjectType(Ty))
2862 return true;
2863
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00002864 // Check to see if this is 'id' or 'Class', both of which are typedefs for
2865 // pointer types. This looks for the typedef specifically, not for the
Chris Lattner16ede0e2009-04-12 23:51:02 +00002866 // underlying type. Iteratively strip off typedefs so that we can handle
2867 // typedefs of typedefs.
2868 while (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
2869 if (Ty.getUnqualifiedType() == getObjCIdType() ||
2870 Ty.getUnqualifiedType() == getObjCClassType())
2871 return true;
2872
2873 Ty = TDT->getDecl()->getUnderlyingType();
2874 }
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00002875
Chris Lattner16ede0e2009-04-12 23:51:02 +00002876 return false;
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00002877}
2878
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00002879/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
2880/// garbage collection attribute.
2881///
2882QualType::GCAttrTypes ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
Chris Lattnerb7d25532009-02-18 22:53:11 +00002883 QualType::GCAttrTypes GCAttrs = QualType::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00002884 if (getLangOptions().ObjC1 &&
2885 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00002886 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00002887 // Default behavious under objective-c's gc is for objective-c pointers
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00002888 // (or pointers to them) be treated as though they were declared
2889 // as __strong.
2890 if (GCAttrs == QualType::GCNone) {
2891 if (isObjCObjectPointerType(Ty))
2892 GCAttrs = QualType::Strong;
2893 else if (Ty->isPointerType())
2894 return getObjCGCAttrKind(Ty->getAsPointerType()->getPointeeType());
2895 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00002896 // Non-pointers have none gc'able attribute regardless of the attribute
2897 // set on them.
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00002898 else if (!Ty->isPointerType() && !isObjCObjectPointerType(Ty))
Fariborz Jahanianc2112182009-04-11 00:00:54 +00002899 return QualType::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00002900 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00002901 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00002902}
2903
Chris Lattner6ac46a42008-04-07 06:51:04 +00002904//===----------------------------------------------------------------------===//
2905// Type Compatibility Testing
2906//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00002907
Chris Lattner6ac46a42008-04-07 06:51:04 +00002908/// areCompatVectorTypes - Return true if the two specified vector types are
2909/// compatible.
2910static bool areCompatVectorTypes(const VectorType *LHS,
2911 const VectorType *RHS) {
2912 assert(LHS->isCanonical() && RHS->isCanonical());
2913 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00002914 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00002915}
2916
Eli Friedman3d815e72008-08-22 00:56:42 +00002917/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00002918/// compatible for assignment from RHS to LHS. This handles validation of any
2919/// protocol qualifiers on the LHS or RHS.
2920///
Eli Friedman3d815e72008-08-22 00:56:42 +00002921bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
2922 const ObjCInterfaceType *RHS) {
Chris Lattner6ac46a42008-04-07 06:51:04 +00002923 // Verify that the base decls are compatible: the RHS must be a subclass of
2924 // the LHS.
2925 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
2926 return false;
2927
2928 // RHS must have a superset of the protocols in the LHS. If the LHS is not
2929 // protocol qualified at all, then we are good.
2930 if (!isa<ObjCQualifiedInterfaceType>(LHS))
2931 return true;
2932
2933 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
2934 // isn't a superset.
2935 if (!isa<ObjCQualifiedInterfaceType>(RHS))
2936 return true; // FIXME: should return false!
2937
2938 // Finally, we must have two protocol-qualified interfaces.
2939 const ObjCQualifiedInterfaceType *LHSP =cast<ObjCQualifiedInterfaceType>(LHS);
2940 const ObjCQualifiedInterfaceType *RHSP =cast<ObjCQualifiedInterfaceType>(RHS);
Chris Lattner6ac46a42008-04-07 06:51:04 +00002941
Steve Naroff91b0b0c2009-03-01 16:12:44 +00002942 // All LHS protocols must have a presence on the RHS.
2943 assert(LHSP->qual_begin() != LHSP->qual_end() && "Empty LHS protocol list?");
Chris Lattner6ac46a42008-04-07 06:51:04 +00002944
Steve Naroff91b0b0c2009-03-01 16:12:44 +00002945 for (ObjCQualifiedInterfaceType::qual_iterator LHSPI = LHSP->qual_begin(),
2946 LHSPE = LHSP->qual_end();
2947 LHSPI != LHSPE; LHSPI++) {
2948 bool RHSImplementsProtocol = false;
2949
2950 // If the RHS doesn't implement the protocol on the left, the types
2951 // are incompatible.
2952 for (ObjCQualifiedInterfaceType::qual_iterator RHSPI = RHSP->qual_begin(),
2953 RHSPE = RHSP->qual_end();
2954 !RHSImplementsProtocol && (RHSPI != RHSPE); RHSPI++) {
2955 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier()))
2956 RHSImplementsProtocol = true;
2957 }
2958 // FIXME: For better diagnostics, consider passing back the protocol name.
2959 if (!RHSImplementsProtocol)
2960 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00002961 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00002962 // The RHS implements all protocols listed on the LHS.
2963 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00002964}
2965
Steve Naroff389bf462009-02-12 17:52:19 +00002966bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
2967 // get the "pointed to" types
2968 const PointerType *LHSPT = LHS->getAsPointerType();
2969 const PointerType *RHSPT = RHS->getAsPointerType();
2970
2971 if (!LHSPT || !RHSPT)
2972 return false;
2973
2974 QualType lhptee = LHSPT->getPointeeType();
2975 QualType rhptee = RHSPT->getPointeeType();
2976 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2977 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2978 // ID acts sort of like void* for ObjC interfaces
2979 if (LHSIface && isObjCIdStructType(rhptee))
2980 return true;
2981 if (RHSIface && isObjCIdStructType(lhptee))
2982 return true;
2983 if (!LHSIface || !RHSIface)
2984 return false;
2985 return canAssignObjCInterfaces(LHSIface, RHSIface) ||
2986 canAssignObjCInterfaces(RHSIface, LHSIface);
2987}
2988
Steve Naroffec0550f2007-10-15 20:41:53 +00002989/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
2990/// both shall have the identically qualified version of a compatible type.
2991/// C99 6.2.7p1: Two types have compatible types if their types are the
2992/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman3d815e72008-08-22 00:56:42 +00002993bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
2994 return !mergeTypes(LHS, RHS).isNull();
2995}
2996
2997QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
2998 const FunctionType *lbase = lhs->getAsFunctionType();
2999 const FunctionType *rbase = rhs->getAsFunctionType();
Douglas Gregor72564e72009-02-26 23:50:07 +00003000 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
3001 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00003002 bool allLTypes = true;
3003 bool allRTypes = true;
3004
3005 // Check return type
3006 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
3007 if (retType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00003008 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
3009 allLTypes = false;
3010 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
3011 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00003012
3013 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00003014 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
3015 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00003016 unsigned lproto_nargs = lproto->getNumArgs();
3017 unsigned rproto_nargs = rproto->getNumArgs();
3018
3019 // Compatible functions must have the same number of arguments
3020 if (lproto_nargs != rproto_nargs)
3021 return QualType();
3022
3023 // Variadic and non-variadic functions aren't compatible
3024 if (lproto->isVariadic() != rproto->isVariadic())
3025 return QualType();
3026
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003027 if (lproto->getTypeQuals() != rproto->getTypeQuals())
3028 return QualType();
3029
Eli Friedman3d815e72008-08-22 00:56:42 +00003030 // Check argument compatibility
3031 llvm::SmallVector<QualType, 10> types;
3032 for (unsigned i = 0; i < lproto_nargs; i++) {
3033 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
3034 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
3035 QualType argtype = mergeTypes(largtype, rargtype);
3036 if (argtype.isNull()) return QualType();
3037 types.push_back(argtype);
Chris Lattner61710852008-10-05 17:34:18 +00003038 if (getCanonicalType(argtype) != getCanonicalType(largtype))
3039 allLTypes = false;
3040 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
3041 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00003042 }
3043 if (allLTypes) return lhs;
3044 if (allRTypes) return rhs;
3045 return getFunctionType(retType, types.begin(), types.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003046 lproto->isVariadic(), lproto->getTypeQuals());
Eli Friedman3d815e72008-08-22 00:56:42 +00003047 }
3048
3049 if (lproto) allRTypes = false;
3050 if (rproto) allLTypes = false;
3051
Douglas Gregor72564e72009-02-26 23:50:07 +00003052 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00003053 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00003054 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00003055 if (proto->isVariadic()) return QualType();
3056 // Check that the types are compatible with the types that
3057 // would result from default argument promotions (C99 6.7.5.3p15).
3058 // The only types actually affected are promotable integer
3059 // types and floats, which would be passed as a different
3060 // type depending on whether the prototype is visible.
3061 unsigned proto_nargs = proto->getNumArgs();
3062 for (unsigned i = 0; i < proto_nargs; ++i) {
3063 QualType argTy = proto->getArgType(i);
3064 if (argTy->isPromotableIntegerType() ||
3065 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
3066 return QualType();
3067 }
3068
3069 if (allLTypes) return lhs;
3070 if (allRTypes) return rhs;
3071 return getFunctionType(retType, proto->arg_type_begin(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003072 proto->getNumArgs(), lproto->isVariadic(),
3073 lproto->getTypeQuals());
Eli Friedman3d815e72008-08-22 00:56:42 +00003074 }
3075
3076 if (allLTypes) return lhs;
3077 if (allRTypes) return rhs;
Douglas Gregor72564e72009-02-26 23:50:07 +00003078 return getFunctionNoProtoType(retType);
Eli Friedman3d815e72008-08-22 00:56:42 +00003079}
3080
3081QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
Bill Wendling43d69752007-12-03 07:33:35 +00003082 // C++ [expr]: If an expression initially has the type "reference to T", the
3083 // type is adjusted to "T" prior to any further analysis, the expression
3084 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003085 // expression is an lvalue unless the reference is an rvalue reference and
3086 // the expression is a function call (possibly inside parentheses).
Eli Friedman3d815e72008-08-22 00:56:42 +00003087 // FIXME: C++ shouldn't be going through here! The rules are different
3088 // enough that they should be handled separately.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003089 // FIXME: Merging of lvalue and rvalue references is incorrect. C++ *really*
3090 // shouldn't be going through here!
Eli Friedman3d815e72008-08-22 00:56:42 +00003091 if (const ReferenceType *RT = LHS->getAsReferenceType())
Chris Lattnerc4e40592008-04-07 04:07:56 +00003092 LHS = RT->getPointeeType();
Eli Friedman3d815e72008-08-22 00:56:42 +00003093 if (const ReferenceType *RT = RHS->getAsReferenceType())
Chris Lattnerc4e40592008-04-07 04:07:56 +00003094 RHS = RT->getPointeeType();
Chris Lattnerf3692dc2008-04-07 05:37:56 +00003095
Eli Friedman3d815e72008-08-22 00:56:42 +00003096 QualType LHSCan = getCanonicalType(LHS),
3097 RHSCan = getCanonicalType(RHS);
3098
3099 // If two types are identical, they are compatible.
3100 if (LHSCan == RHSCan)
3101 return LHS;
3102
3103 // If the qualifiers are different, the types aren't compatible
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003104 // Note that we handle extended qualifiers later, in the
3105 // case for ExtQualType.
3106 if (LHSCan.getCVRQualifiers() != RHSCan.getCVRQualifiers())
Eli Friedman3d815e72008-08-22 00:56:42 +00003107 return QualType();
3108
Eli Friedman852d63b2009-06-01 01:22:52 +00003109 Type::TypeClass LHSClass = LHSCan->getTypeClass();
3110 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00003111
Chris Lattner1adb8832008-01-14 05:45:46 +00003112 // We want to consider the two function types to be the same for these
3113 // comparisons, just force one to the other.
3114 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
3115 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00003116
Eli Friedman07d25872009-06-02 05:28:56 +00003117 // Strip off objc_gc attributes off the top level so they can be merged.
3118 // This is a complete mess, but the attribute itself doesn't make much sense.
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003119 if (RHSClass == Type::ExtQual) {
Eli Friedman07d25872009-06-02 05:28:56 +00003120 QualType::GCAttrTypes GCAttr = RHSCan.getObjCGCAttr();
3121 if (GCAttr != QualType::GCNone) {
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003122 QualType::GCAttrTypes GCLHSAttr = LHSCan.getObjCGCAttr();
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003123 // __weak attribute must appear on both declarations.
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003124 // __strong attribue is redundant if other decl is an objective-c
3125 // object pointer (or decorated with __strong attribute); otherwise
3126 // issue error.
3127 if ((GCAttr == QualType::Weak && GCLHSAttr != GCAttr) ||
3128 (GCAttr == QualType::Strong && GCLHSAttr != GCAttr &&
3129 LHSCan->isPointerType() && !isObjCObjectPointerType(LHSCan) &&
3130 !isObjCIdStructType(LHSCan->getAsPointerType()->getPointeeType())))
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003131 return QualType();
3132
Eli Friedman07d25872009-06-02 05:28:56 +00003133 RHS = QualType(cast<ExtQualType>(RHS.getDesugaredType())->getBaseType(),
3134 RHS.getCVRQualifiers());
3135 QualType Result = mergeTypes(LHS, RHS);
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003136 if (!Result.isNull()) {
3137 if (Result.getObjCGCAttr() == QualType::GCNone)
3138 Result = getObjCGCQualType(Result, GCAttr);
3139 else if (Result.getObjCGCAttr() != GCAttr)
3140 Result = QualType();
3141 }
Eli Friedman07d25872009-06-02 05:28:56 +00003142 return Result;
3143 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003144 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003145 if (LHSClass == Type::ExtQual) {
Eli Friedman07d25872009-06-02 05:28:56 +00003146 QualType::GCAttrTypes GCAttr = LHSCan.getObjCGCAttr();
3147 if (GCAttr != QualType::GCNone) {
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003148 QualType::GCAttrTypes GCRHSAttr = RHSCan.getObjCGCAttr();
3149 // __weak attribute must appear on both declarations. __strong
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003150 // __strong attribue is redundant if other decl is an objective-c
3151 // object pointer (or decorated with __strong attribute); otherwise
3152 // issue error.
3153 if ((GCAttr == QualType::Weak && GCRHSAttr != GCAttr) ||
3154 (GCAttr == QualType::Strong && GCRHSAttr != GCAttr &&
3155 RHSCan->isPointerType() && !isObjCObjectPointerType(RHSCan) &&
3156 !isObjCIdStructType(RHSCan->getAsPointerType()->getPointeeType())))
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003157 return QualType();
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003158
Eli Friedman07d25872009-06-02 05:28:56 +00003159 LHS = QualType(cast<ExtQualType>(LHS.getDesugaredType())->getBaseType(),
3160 LHS.getCVRQualifiers());
3161 QualType Result = mergeTypes(LHS, RHS);
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003162 if (!Result.isNull()) {
3163 if (Result.getObjCGCAttr() == QualType::GCNone)
3164 Result = getObjCGCQualType(Result, GCAttr);
3165 else if (Result.getObjCGCAttr() != GCAttr)
3166 Result = QualType();
3167 }
Eli Friedman354e53d2009-06-02 07:45:37 +00003168 return Result;
Eli Friedman07d25872009-06-02 05:28:56 +00003169 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003170 }
3171
Eli Friedman4c721d32008-02-12 08:23:06 +00003172 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00003173 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
3174 LHSClass = Type::ConstantArray;
3175 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
3176 RHSClass = Type::ConstantArray;
Steve Naroffec0550f2007-10-15 20:41:53 +00003177
Nate Begeman213541a2008-04-18 23:10:10 +00003178 // Canonicalize ExtVector -> Vector.
3179 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
3180 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Chris Lattnera36a61f2008-04-07 05:43:21 +00003181
Chris Lattnerb0489812008-04-07 06:38:24 +00003182 // Consider qualified interfaces and interfaces the same.
3183 if (LHSClass == Type::ObjCQualifiedInterface) LHSClass = Type::ObjCInterface;
3184 if (RHSClass == Type::ObjCQualifiedInterface) RHSClass = Type::ObjCInterface;
Eli Friedman3d815e72008-08-22 00:56:42 +00003185
Chris Lattnera36a61f2008-04-07 05:43:21 +00003186 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00003187 if (LHSClass != RHSClass) {
Steve Naroff5fd659d2009-02-21 16:18:07 +00003188 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
3189 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
Fariborz Jahanianc8d2e772009-04-15 21:54:48 +00003190
Steve Naroffd824c9c2009-04-14 15:11:46 +00003191 // 'id' and 'Class' act sort of like void* for ObjC interfaces
3192 if (LHSIface && (isObjCIdStructType(RHS) || isObjCClassStructType(RHS)))
Steve Naroff5fd659d2009-02-21 16:18:07 +00003193 return LHS;
Steve Naroffd824c9c2009-04-14 15:11:46 +00003194 if (RHSIface && (isObjCIdStructType(LHS) || isObjCClassStructType(LHS)))
Steve Naroff5fd659d2009-02-21 16:18:07 +00003195 return RHS;
3196
Steve Naroffbc76dd02008-12-10 22:14:21 +00003197 // ID is compatible with all qualified id types.
3198 if (LHS->isObjCQualifiedIdType()) {
3199 if (const PointerType *PT = RHS->getAsPointerType()) {
3200 QualType pType = PT->getPointeeType();
Steve Naroffd824c9c2009-04-14 15:11:46 +00003201 if (isObjCIdStructType(pType) || isObjCClassStructType(pType))
Steve Naroffbc76dd02008-12-10 22:14:21 +00003202 return LHS;
3203 // FIXME: need to use ObjCQualifiedIdTypesAreCompatible(LHS, RHS, true).
3204 // Unfortunately, this API is part of Sema (which we don't have access
3205 // to. Need to refactor. The following check is insufficient, since we
3206 // need to make sure the class implements the protocol.
3207 if (pType->isObjCInterfaceType())
3208 return LHS;
3209 }
3210 }
3211 if (RHS->isObjCQualifiedIdType()) {
3212 if (const PointerType *PT = LHS->getAsPointerType()) {
3213 QualType pType = PT->getPointeeType();
Steve Naroffd824c9c2009-04-14 15:11:46 +00003214 if (isObjCIdStructType(pType) || isObjCClassStructType(pType))
Steve Naroffbc76dd02008-12-10 22:14:21 +00003215 return RHS;
3216 // FIXME: need to use ObjCQualifiedIdTypesAreCompatible(LHS, RHS, true).
3217 // Unfortunately, this API is part of Sema (which we don't have access
3218 // to. Need to refactor. The following check is insufficient, since we
3219 // need to make sure the class implements the protocol.
3220 if (pType->isObjCInterfaceType())
3221 return RHS;
3222 }
3223 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003224 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
3225 // a signed integer type, or an unsigned integer type.
Eli Friedman3d815e72008-08-22 00:56:42 +00003226 if (const EnumType* ETy = LHS->getAsEnumType()) {
3227 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
3228 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00003229 }
Eli Friedman3d815e72008-08-22 00:56:42 +00003230 if (const EnumType* ETy = RHS->getAsEnumType()) {
3231 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
3232 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00003233 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003234
Eli Friedman3d815e72008-08-22 00:56:42 +00003235 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00003236 }
Eli Friedman3d815e72008-08-22 00:56:42 +00003237
Steve Naroff4a746782008-01-09 22:43:08 +00003238 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00003239 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00003240#define TYPE(Class, Base)
3241#define ABSTRACT_TYPE(Class, Base)
3242#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3243#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3244#include "clang/AST/TypeNodes.def"
3245 assert(false && "Non-canonical and dependent types shouldn't get here");
3246 return QualType();
3247
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003248 case Type::LValueReference:
3249 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00003250 case Type::MemberPointer:
3251 assert(false && "C++ should never be in mergeTypes");
3252 return QualType();
3253
3254 case Type::IncompleteArray:
3255 case Type::VariableArray:
3256 case Type::FunctionProto:
3257 case Type::ExtVector:
3258 case Type::ObjCQualifiedInterface:
3259 assert(false && "Types are eliminated above");
3260 return QualType();
3261
Chris Lattner1adb8832008-01-14 05:45:46 +00003262 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00003263 {
3264 // Merge two pointer types, while trying to preserve typedef info
3265 QualType LHSPointee = LHS->getAsPointerType()->getPointeeType();
3266 QualType RHSPointee = RHS->getAsPointerType()->getPointeeType();
3267 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
3268 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00003269 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00003270 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00003271 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00003272 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00003273 return getPointerType(ResultType);
3274 }
Steve Naroffc0febd52008-12-10 17:49:55 +00003275 case Type::BlockPointer:
3276 {
3277 // Merge two block pointer types, while trying to preserve typedef info
3278 QualType LHSPointee = LHS->getAsBlockPointerType()->getPointeeType();
3279 QualType RHSPointee = RHS->getAsBlockPointerType()->getPointeeType();
3280 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
3281 if (ResultType.isNull()) return QualType();
3282 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
3283 return LHS;
3284 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
3285 return RHS;
3286 return getBlockPointerType(ResultType);
3287 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003288 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00003289 {
3290 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
3291 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
3292 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
3293 return QualType();
3294
3295 QualType LHSElem = getAsArrayType(LHS)->getElementType();
3296 QualType RHSElem = getAsArrayType(RHS)->getElementType();
3297 QualType ResultType = mergeTypes(LHSElem, RHSElem);
3298 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00003299 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3300 return LHS;
3301 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3302 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00003303 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
3304 ArrayType::ArraySizeModifier(), 0);
3305 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
3306 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00003307 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
3308 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00003309 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3310 return LHS;
3311 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3312 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00003313 if (LVAT) {
3314 // FIXME: This isn't correct! But tricky to implement because
3315 // the array's size has to be the size of LHS, but the type
3316 // has to be different.
3317 return LHS;
3318 }
3319 if (RVAT) {
3320 // FIXME: This isn't correct! But tricky to implement because
3321 // the array's size has to be the size of RHS, but the type
3322 // has to be different.
3323 return RHS;
3324 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00003325 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
3326 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Chris Lattner61710852008-10-05 17:34:18 +00003327 return getIncompleteArrayType(ResultType, ArrayType::ArraySizeModifier(),0);
Eli Friedman3d815e72008-08-22 00:56:42 +00003328 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003329 case Type::FunctionNoProto:
Eli Friedman3d815e72008-08-22 00:56:42 +00003330 return mergeFunctionTypes(LHS, RHS);
Douglas Gregor72564e72009-02-26 23:50:07 +00003331 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00003332 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00003333 // FIXME: Why are these compatible?
Steve Naroff389bf462009-02-12 17:52:19 +00003334 if (isObjCIdStructType(LHS) && isObjCClassStructType(RHS)) return LHS;
3335 if (isObjCClassStructType(LHS) && isObjCIdStructType(RHS)) return LHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00003336 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00003337 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00003338 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00003339 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00003340 case Type::Complex:
3341 // Distinct complex types are incompatible.
3342 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00003343 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003344 // FIXME: The merged type should be an ExtVector!
Eli Friedman3d815e72008-08-22 00:56:42 +00003345 if (areCompatVectorTypes(LHS->getAsVectorType(), RHS->getAsVectorType()))
3346 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00003347 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00003348 case Type::ObjCInterface: {
Steve Naroff5fd659d2009-02-21 16:18:07 +00003349 // Check if the interfaces are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003350 // FIXME: This should be type compatibility, e.g. whether
3351 // "LHS x; RHS x;" at global scope is legal.
Steve Naroff5fd659d2009-02-21 16:18:07 +00003352 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
3353 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
3354 if (LHSIface && RHSIface &&
3355 canAssignObjCInterfaces(LHSIface, RHSIface))
3356 return LHS;
3357
Eli Friedman3d815e72008-08-22 00:56:42 +00003358 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00003359 }
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003360 case Type::ObjCObjectPointer:
3361 // FIXME: finish
Steve Naroffbc76dd02008-12-10 22:14:21 +00003362 // Distinct qualified id's are not compatible.
3363 return QualType();
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003364 case Type::FixedWidthInt:
3365 // Distinct fixed-width integers are not compatible.
3366 return QualType();
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003367 case Type::ExtQual:
3368 // FIXME: ExtQual types can be compatible even if they're not
3369 // identical!
3370 return QualType();
3371 // First attempt at an implementation, but I'm not really sure it's
3372 // right...
3373#if 0
3374 ExtQualType* LQual = cast<ExtQualType>(LHSCan);
3375 ExtQualType* RQual = cast<ExtQualType>(RHSCan);
3376 if (LQual->getAddressSpace() != RQual->getAddressSpace() ||
3377 LQual->getObjCGCAttr() != RQual->getObjCGCAttr())
3378 return QualType();
3379 QualType LHSBase, RHSBase, ResultType, ResCanUnqual;
3380 LHSBase = QualType(LQual->getBaseType(), 0);
3381 RHSBase = QualType(RQual->getBaseType(), 0);
3382 ResultType = mergeTypes(LHSBase, RHSBase);
3383 if (ResultType.isNull()) return QualType();
3384 ResCanUnqual = getCanonicalType(ResultType).getUnqualifiedType();
3385 if (LHSCan.getUnqualifiedType() == ResCanUnqual)
3386 return LHS;
3387 if (RHSCan.getUnqualifiedType() == ResCanUnqual)
3388 return RHS;
3389 ResultType = getAddrSpaceQualType(ResultType, LQual->getAddressSpace());
3390 ResultType = getObjCGCQualType(ResultType, LQual->getObjCGCAttr());
3391 ResultType.setCVRQualifiers(LHSCan.getCVRQualifiers());
3392 return ResultType;
3393#endif
Douglas Gregor7532dc62009-03-30 22:58:21 +00003394
3395 case Type::TemplateSpecialization:
3396 assert(false && "Dependent types have no size");
3397 break;
Steve Naroffec0550f2007-10-15 20:41:53 +00003398 }
Douglas Gregor72564e72009-02-26 23:50:07 +00003399
3400 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00003401}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00003402
Chris Lattner5426bf62008-04-07 07:01:58 +00003403//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00003404// Integer Predicates
3405//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00003406
Eli Friedmanad74a752008-06-28 06:23:08 +00003407unsigned ASTContext::getIntWidth(QualType T) {
3408 if (T == BoolTy)
3409 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00003410 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T)) {
3411 return FWIT->getWidth();
3412 }
3413 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00003414 return (unsigned)getTypeSize(T);
3415}
3416
3417QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
3418 assert(T->isSignedIntegerType() && "Unexpected type");
3419 if (const EnumType* ETy = T->getAsEnumType())
3420 T = ETy->getDecl()->getIntegerType();
3421 const BuiltinType* BTy = T->getAsBuiltinType();
3422 assert (BTy && "Unexpected signed integer type");
3423 switch (BTy->getKind()) {
3424 case BuiltinType::Char_S:
3425 case BuiltinType::SChar:
3426 return UnsignedCharTy;
3427 case BuiltinType::Short:
3428 return UnsignedShortTy;
3429 case BuiltinType::Int:
3430 return UnsignedIntTy;
3431 case BuiltinType::Long:
3432 return UnsignedLongTy;
3433 case BuiltinType::LongLong:
3434 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00003435 case BuiltinType::Int128:
3436 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00003437 default:
3438 assert(0 && "Unexpected signed integer type");
3439 return QualType();
3440 }
3441}
3442
Douglas Gregor2cf26342009-04-09 22:27:44 +00003443ExternalASTSource::~ExternalASTSource() { }
3444
3445void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00003446
3447
3448//===----------------------------------------------------------------------===//
3449// Builtin Type Computation
3450//===----------------------------------------------------------------------===//
3451
3452/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
3453/// pointer over the consumed characters. This returns the resultant type.
3454static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
3455 ASTContext::GetBuiltinTypeError &Error,
3456 bool AllowTypeModifiers = true) {
3457 // Modifiers.
3458 int HowLong = 0;
3459 bool Signed = false, Unsigned = false;
3460
3461 // Read the modifiers first.
3462 bool Done = false;
3463 while (!Done) {
3464 switch (*Str++) {
3465 default: Done = true; --Str; break;
3466 case 'S':
3467 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
3468 assert(!Signed && "Can't use 'S' modifier multiple times!");
3469 Signed = true;
3470 break;
3471 case 'U':
3472 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
3473 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
3474 Unsigned = true;
3475 break;
3476 case 'L':
3477 assert(HowLong <= 2 && "Can't have LLLL modifier");
3478 ++HowLong;
3479 break;
3480 }
3481 }
3482
3483 QualType Type;
3484
3485 // Read the base type.
3486 switch (*Str++) {
3487 default: assert(0 && "Unknown builtin type letter!");
3488 case 'v':
3489 assert(HowLong == 0 && !Signed && !Unsigned &&
3490 "Bad modifiers used with 'v'!");
3491 Type = Context.VoidTy;
3492 break;
3493 case 'f':
3494 assert(HowLong == 0 && !Signed && !Unsigned &&
3495 "Bad modifiers used with 'f'!");
3496 Type = Context.FloatTy;
3497 break;
3498 case 'd':
3499 assert(HowLong < 2 && !Signed && !Unsigned &&
3500 "Bad modifiers used with 'd'!");
3501 if (HowLong)
3502 Type = Context.LongDoubleTy;
3503 else
3504 Type = Context.DoubleTy;
3505 break;
3506 case 's':
3507 assert(HowLong == 0 && "Bad modifiers used with 's'!");
3508 if (Unsigned)
3509 Type = Context.UnsignedShortTy;
3510 else
3511 Type = Context.ShortTy;
3512 break;
3513 case 'i':
3514 if (HowLong == 3)
3515 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
3516 else if (HowLong == 2)
3517 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
3518 else if (HowLong == 1)
3519 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
3520 else
3521 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
3522 break;
3523 case 'c':
3524 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
3525 if (Signed)
3526 Type = Context.SignedCharTy;
3527 else if (Unsigned)
3528 Type = Context.UnsignedCharTy;
3529 else
3530 Type = Context.CharTy;
3531 break;
3532 case 'b': // boolean
3533 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
3534 Type = Context.BoolTy;
3535 break;
3536 case 'z': // size_t.
3537 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
3538 Type = Context.getSizeType();
3539 break;
3540 case 'F':
3541 Type = Context.getCFConstantStringType();
3542 break;
3543 case 'a':
3544 Type = Context.getBuiltinVaListType();
3545 assert(!Type.isNull() && "builtin va list type not initialized!");
3546 break;
3547 case 'A':
3548 // This is a "reference" to a va_list; however, what exactly
3549 // this means depends on how va_list is defined. There are two
3550 // different kinds of va_list: ones passed by value, and ones
3551 // passed by reference. An example of a by-value va_list is
3552 // x86, where va_list is a char*. An example of by-ref va_list
3553 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
3554 // we want this argument to be a char*&; for x86-64, we want
3555 // it to be a __va_list_tag*.
3556 Type = Context.getBuiltinVaListType();
3557 assert(!Type.isNull() && "builtin va list type not initialized!");
3558 if (Type->isArrayType()) {
3559 Type = Context.getArrayDecayedType(Type);
3560 } else {
3561 Type = Context.getLValueReferenceType(Type);
3562 }
3563 break;
3564 case 'V': {
3565 char *End;
3566
3567 unsigned NumElements = strtoul(Str, &End, 10);
3568 assert(End != Str && "Missing vector size");
3569
3570 Str = End;
3571
3572 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
3573 Type = Context.getVectorType(ElementType, NumElements);
3574 break;
3575 }
3576 case 'P': {
3577 IdentifierInfo *II = &Context.Idents.get("FILE");
3578 DeclContext::lookup_result Lookup
3579 = Context.getTranslationUnitDecl()->lookup(Context, II);
3580 if (Lookup.first != Lookup.second && isa<TypeDecl>(*Lookup.first)) {
3581 Type = Context.getTypeDeclType(cast<TypeDecl>(*Lookup.first));
3582 break;
3583 }
3584 else {
3585 Error = ASTContext::GE_Missing_FILE;
3586 return QualType();
3587 }
3588 }
3589 }
3590
3591 if (!AllowTypeModifiers)
3592 return Type;
3593
3594 Done = false;
3595 while (!Done) {
3596 switch (*Str++) {
3597 default: Done = true; --Str; break;
3598 case '*':
3599 Type = Context.getPointerType(Type);
3600 break;
3601 case '&':
3602 Type = Context.getLValueReferenceType(Type);
3603 break;
3604 // FIXME: There's no way to have a built-in with an rvalue ref arg.
3605 case 'C':
3606 Type = Type.getQualifiedType(QualType::Const);
3607 break;
3608 }
3609 }
3610
3611 return Type;
3612}
3613
3614/// GetBuiltinType - Return the type for the specified builtin.
3615QualType ASTContext::GetBuiltinType(unsigned id,
3616 GetBuiltinTypeError &Error) {
3617 const char *TypeStr = BuiltinInfo.GetTypeString(id);
3618
3619 llvm::SmallVector<QualType, 8> ArgTypes;
3620
3621 Error = GE_None;
3622 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
3623 if (Error != GE_None)
3624 return QualType();
3625 while (TypeStr[0] && TypeStr[0] != '.') {
3626 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
3627 if (Error != GE_None)
3628 return QualType();
3629
3630 // Do array -> pointer decay. The builtin should use the decayed type.
3631 if (Ty->isArrayType())
3632 Ty = getArrayDecayedType(Ty);
3633
3634 ArgTypes.push_back(Ty);
3635 }
3636
3637 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
3638 "'.' should only occur at end of builtin type list!");
3639
3640 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
3641 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
3642 return getFunctionNoProtoType(ResType);
3643 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
3644 TypeStr[0] == '.', 0);
3645}