blob: 7f945db1d30c31404549af908e9ebb7913e878d0 [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) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000633 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
634 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian98200742009-05-12 18:14:29 +0000635 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) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000649 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
650 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian98200742009-05-12 18:14:29 +0000651 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;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000665 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
666 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000667 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;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000680 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
681 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000682 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.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000788 NewEntry->InitializeLayout(std::distance(D->field_begin(), D->field_end()));
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000789 bool IsUnion = D->isUnion();
Chris Lattner464175b2007-07-18 17:52:12 +0000790
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000791 unsigned StructPacking = 0;
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000792 if (const PackedAttr *PA = D->getAttr<PackedAttr>())
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000793 StructPacking = PA->getAlignment();
794
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000795 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>())
Devang Patel8b277042008-06-04 21:22:16 +0000796 NewEntry->SetAlignment(std::max(NewEntry->getAlignment(),
797 AA->getAlignment()));
Anders Carlsson8af226a2008-02-18 07:13:09 +0000798
Eli Friedman4bd998b2008-05-30 09:31:38 +0000799 // Layout each field, for now, just sequentially, respecting alignment. In
800 // the future, this will need to be tweakable by targets.
Douglas Gregor44b43212008-12-11 16:49:14 +0000801 unsigned FieldIdx = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000802 for (RecordDecl::field_iterator Field = D->field_begin(),
803 FieldEnd = D->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +0000804 Field != FieldEnd; (void)++Field, ++FieldIdx)
805 NewEntry->LayoutField(*Field, FieldIdx, IsUnion, StructPacking, *this);
Eli Friedman4bd998b2008-05-30 09:31:38 +0000806
807 // Finally, round the size of the total struct up to the alignment of the
808 // struct itself.
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000809 NewEntry->FinalizeLayout(getLangOptions().CPlusPlus);
Chris Lattner5d2a6302007-07-18 18:26:58 +0000810 return *NewEntry;
Chris Lattner464175b2007-07-18 17:52:12 +0000811}
812
Chris Lattnera7674d82007-07-13 22:13:22 +0000813//===----------------------------------------------------------------------===//
814// Type creation/memoization methods
815//===----------------------------------------------------------------------===//
816
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000817QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerf52ab252008-04-06 22:59:24 +0000818 QualType CanT = getCanonicalType(T);
819 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +0000820 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +0000821
822 // If we are composing extended qualifiers together, merge together into one
823 // ExtQualType node.
824 unsigned CVRQuals = T.getCVRQualifiers();
825 QualType::GCAttrTypes GCAttr = QualType::GCNone;
826 Type *TypeNode = T.getTypePtr();
Chris Lattnerf46699c2008-02-20 20:55:12 +0000827
Chris Lattnerb7d25532009-02-18 22:53:11 +0000828 if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
829 // If this type already has an address space specified, it cannot get
830 // another one.
831 assert(EQT->getAddressSpace() == 0 &&
832 "Type cannot be in multiple addr spaces!");
833 GCAttr = EQT->getObjCGCAttr();
834 TypeNode = EQT->getBaseType();
835 }
Chris Lattnerf46699c2008-02-20 20:55:12 +0000836
Chris Lattnerb7d25532009-02-18 22:53:11 +0000837 // Check if we've already instantiated this type.
Christopher Lambebb97e92008-02-04 02:31:56 +0000838 llvm::FoldingSetNodeID ID;
Chris Lattnerb7d25532009-02-18 22:53:11 +0000839 ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
Christopher Lambebb97e92008-02-04 02:31:56 +0000840 void *InsertPos = 0;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000841 if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattnerb7d25532009-02-18 22:53:11 +0000842 return QualType(EXTQy, CVRQuals);
843
Christopher Lambebb97e92008-02-04 02:31:56 +0000844 // If the base type isn't canonical, this won't be a canonical type either,
845 // so fill in the canonical type field.
846 QualType Canonical;
Chris Lattnerb7d25532009-02-18 22:53:11 +0000847 if (!TypeNode->isCanonical()) {
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000848 Canonical = getAddrSpaceQualType(CanT, AddressSpace);
Christopher Lambebb97e92008-02-04 02:31:56 +0000849
Chris Lattnerb7d25532009-02-18 22:53:11 +0000850 // Update InsertPos, the previous call could have invalidated it.
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000851 ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +0000852 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Christopher Lambebb97e92008-02-04 02:31:56 +0000853 }
Chris Lattnerb7d25532009-02-18 22:53:11 +0000854 ExtQualType *New =
855 new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000856 ExtQualTypes.InsertNode(New, InsertPos);
Christopher Lambebb97e92008-02-04 02:31:56 +0000857 Types.push_back(New);
Chris Lattnerb7d25532009-02-18 22:53:11 +0000858 return QualType(New, CVRQuals);
Christopher Lambebb97e92008-02-04 02:31:56 +0000859}
860
Chris Lattnerb7d25532009-02-18 22:53:11 +0000861QualType ASTContext::getObjCGCQualType(QualType T,
862 QualType::GCAttrTypes GCAttr) {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000863 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +0000864 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000865 return T;
866
Fariborz Jahanian4027cd12009-06-03 17:15:17 +0000867 if (T->isPointerType()) {
868 QualType Pointee = T->getAsPointerType()->getPointeeType();
869 if (Pointee->isPointerType()) {
870 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
871 return getPointerType(ResultType);
872 }
873 }
Chris Lattnerb7d25532009-02-18 22:53:11 +0000874 // If we are composing extended qualifiers together, merge together into one
875 // ExtQualType node.
876 unsigned CVRQuals = T.getCVRQualifiers();
877 Type *TypeNode = T.getTypePtr();
878 unsigned AddressSpace = 0;
879
880 if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
881 // If this type already has an address space specified, it cannot get
882 // another one.
883 assert(EQT->getObjCGCAttr() == QualType::GCNone &&
884 "Type cannot be in multiple addr spaces!");
885 AddressSpace = EQT->getAddressSpace();
886 TypeNode = EQT->getBaseType();
887 }
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000888
889 // Check if we've already instantiated an gc qual'd type of this type.
890 llvm::FoldingSetNodeID ID;
Chris Lattnerb7d25532009-02-18 22:53:11 +0000891 ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000892 void *InsertPos = 0;
893 if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattnerb7d25532009-02-18 22:53:11 +0000894 return QualType(EXTQy, CVRQuals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000895
896 // If the base type isn't canonical, this won't be a canonical type either,
897 // so fill in the canonical type field.
Eli Friedman5a61f0e2009-02-27 23:04:43 +0000898 // FIXME: Isn't this also not canonical if the base type is a array
899 // or pointer type? I can't find any documentation for objc_gc, though...
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000900 QualType Canonical;
901 if (!T->isCanonical()) {
Chris Lattnerb7d25532009-02-18 22:53:11 +0000902 Canonical = getObjCGCQualType(CanT, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000903
Chris Lattnerb7d25532009-02-18 22:53:11 +0000904 // Update InsertPos, the previous call could have invalidated it.
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000905 ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
906 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
907 }
Chris Lattnerb7d25532009-02-18 22:53:11 +0000908 ExtQualType *New =
909 new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000910 ExtQualTypes.InsertNode(New, InsertPos);
911 Types.push_back(New);
Chris Lattnerb7d25532009-02-18 22:53:11 +0000912 return QualType(New, CVRQuals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000913}
Chris Lattnera7674d82007-07-13 22:13:22 +0000914
Reid Spencer5f016e22007-07-11 17:01:13 +0000915/// getComplexType - Return the uniqued reference to the type for a complex
916/// number with the specified element type.
917QualType ASTContext::getComplexType(QualType T) {
918 // Unique pointers, to guarantee there is only one pointer of a particular
919 // structure.
920 llvm::FoldingSetNodeID ID;
921 ComplexType::Profile(ID, T);
922
923 void *InsertPos = 0;
924 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
925 return QualType(CT, 0);
926
927 // If the pointee type isn't canonical, this won't be a canonical type either,
928 // so fill in the canonical type field.
929 QualType Canonical;
930 if (!T->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +0000931 Canonical = getComplexType(getCanonicalType(T));
Reid Spencer5f016e22007-07-11 17:01:13 +0000932
933 // Get the new insert position for the node we care about.
934 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +0000935 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +0000936 }
Steve Narofff83820b2009-01-27 22:08:43 +0000937 ComplexType *New = new (*this,8) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +0000938 Types.push_back(New);
939 ComplexTypes.InsertNode(New, InsertPos);
940 return QualType(New, 0);
941}
942
Eli Friedmanf98aba32009-02-13 02:31:07 +0000943QualType ASTContext::getFixedWidthIntType(unsigned Width, bool Signed) {
944 llvm::DenseMap<unsigned, FixedWidthIntType*> &Map = Signed ?
945 SignedFixedWidthIntTypes : UnsignedFixedWidthIntTypes;
946 FixedWidthIntType *&Entry = Map[Width];
947 if (!Entry)
948 Entry = new FixedWidthIntType(Width, Signed);
949 return QualType(Entry, 0);
950}
Reid Spencer5f016e22007-07-11 17:01:13 +0000951
952/// getPointerType - Return the uniqued reference to the type for a pointer to
953/// the specified type.
954QualType ASTContext::getPointerType(QualType T) {
955 // Unique pointers, to guarantee there is only one pointer of a particular
956 // structure.
957 llvm::FoldingSetNodeID ID;
958 PointerType::Profile(ID, T);
959
960 void *InsertPos = 0;
961 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
962 return QualType(PT, 0);
963
964 // If the pointee type isn't canonical, this won't be a canonical type either,
965 // so fill in the canonical type field.
966 QualType Canonical;
967 if (!T->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +0000968 Canonical = getPointerType(getCanonicalType(T));
Reid Spencer5f016e22007-07-11 17:01:13 +0000969
970 // Get the new insert position for the node we care about.
971 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +0000972 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +0000973 }
Steve Narofff83820b2009-01-27 22:08:43 +0000974 PointerType *New = new (*this,8) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +0000975 Types.push_back(New);
976 PointerTypes.InsertNode(New, InsertPos);
977 return QualType(New, 0);
978}
979
Steve Naroff5618bd42008-08-27 16:04:49 +0000980/// getBlockPointerType - Return the uniqued reference to the type for
981/// a pointer to the specified block.
982QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff296e8d52008-08-28 19:20:44 +0000983 assert(T->isFunctionType() && "block of function types only");
984 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +0000985 // structure.
986 llvm::FoldingSetNodeID ID;
987 BlockPointerType::Profile(ID, T);
988
989 void *InsertPos = 0;
990 if (BlockPointerType *PT =
991 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
992 return QualType(PT, 0);
993
Steve Naroff296e8d52008-08-28 19:20:44 +0000994 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +0000995 // type either so fill in the canonical type field.
996 QualType Canonical;
997 if (!T->isCanonical()) {
998 Canonical = getBlockPointerType(getCanonicalType(T));
999
1000 // Get the new insert position for the node we care about.
1001 BlockPointerType *NewIP =
1002 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001003 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001004 }
Steve Narofff83820b2009-01-27 22:08:43 +00001005 BlockPointerType *New = new (*this,8) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001006 Types.push_back(New);
1007 BlockPointerTypes.InsertNode(New, InsertPos);
1008 return QualType(New, 0);
1009}
1010
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001011/// getLValueReferenceType - Return the uniqued reference to the type for an
1012/// lvalue reference to the specified type.
1013QualType ASTContext::getLValueReferenceType(QualType T) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001014 // Unique pointers, to guarantee there is only one pointer of a particular
1015 // structure.
1016 llvm::FoldingSetNodeID ID;
1017 ReferenceType::Profile(ID, T);
1018
1019 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001020 if (LValueReferenceType *RT =
1021 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001022 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001023
Reid Spencer5f016e22007-07-11 17:01:13 +00001024 // If the referencee type isn't canonical, this won't be a canonical type
1025 // either, so fill in the canonical type field.
1026 QualType Canonical;
1027 if (!T->isCanonical()) {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001028 Canonical = getLValueReferenceType(getCanonicalType(T));
1029
Reid Spencer5f016e22007-07-11 17:01:13 +00001030 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001031 LValueReferenceType *NewIP =
1032 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001033 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001034 }
1035
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001036 LValueReferenceType *New = new (*this,8) LValueReferenceType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001037 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001038 LValueReferenceTypes.InsertNode(New, InsertPos);
1039 return QualType(New, 0);
1040}
1041
1042/// getRValueReferenceType - Return the uniqued reference to the type for an
1043/// rvalue reference to the specified type.
1044QualType ASTContext::getRValueReferenceType(QualType T) {
1045 // Unique pointers, to guarantee there is only one pointer of a particular
1046 // structure.
1047 llvm::FoldingSetNodeID ID;
1048 ReferenceType::Profile(ID, T);
1049
1050 void *InsertPos = 0;
1051 if (RValueReferenceType *RT =
1052 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1053 return QualType(RT, 0);
1054
1055 // If the referencee type isn't canonical, this won't be a canonical type
1056 // either, so fill in the canonical type field.
1057 QualType Canonical;
1058 if (!T->isCanonical()) {
1059 Canonical = getRValueReferenceType(getCanonicalType(T));
1060
1061 // Get the new insert position for the node we care about.
1062 RValueReferenceType *NewIP =
1063 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1064 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1065 }
1066
1067 RValueReferenceType *New = new (*this,8) RValueReferenceType(T, Canonical);
1068 Types.push_back(New);
1069 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001070 return QualType(New, 0);
1071}
1072
Sebastian Redlf30208a2009-01-24 21:16:55 +00001073/// getMemberPointerType - Return the uniqued reference to the type for a
1074/// member pointer to the specified type, in the specified class.
1075QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls)
1076{
1077 // Unique pointers, to guarantee there is only one pointer of a particular
1078 // structure.
1079 llvm::FoldingSetNodeID ID;
1080 MemberPointerType::Profile(ID, T, Cls);
1081
1082 void *InsertPos = 0;
1083 if (MemberPointerType *PT =
1084 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1085 return QualType(PT, 0);
1086
1087 // If the pointee or class type isn't canonical, this won't be a canonical
1088 // type either, so fill in the canonical type field.
1089 QualType Canonical;
1090 if (!T->isCanonical()) {
1091 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1092
1093 // Get the new insert position for the node we care about.
1094 MemberPointerType *NewIP =
1095 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1096 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1097 }
Steve Narofff83820b2009-01-27 22:08:43 +00001098 MemberPointerType *New = new (*this,8) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001099 Types.push_back(New);
1100 MemberPointerTypes.InsertNode(New, InsertPos);
1101 return QualType(New, 0);
1102}
1103
Steve Narofffb22d962007-08-30 01:06:46 +00001104/// getConstantArrayType - Return the unique reference to the type for an
1105/// array of the specified element type.
1106QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001107 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001108 ArrayType::ArraySizeModifier ASM,
1109 unsigned EltTypeQuals) {
Eli Friedman587cbdf2009-05-29 20:17:55 +00001110 assert((EltTy->isDependentType() || EltTy->isConstantSizeType()) &&
1111 "Constant array of VLAs is illegal!");
1112
Chris Lattner38aeec72009-05-13 04:12:56 +00001113 // Convert the array size into a canonical width matching the pointer size for
1114 // the target.
1115 llvm::APInt ArySize(ArySizeIn);
1116 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1117
Reid Spencer5f016e22007-07-11 17:01:13 +00001118 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001119 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001120
1121 void *InsertPos = 0;
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001122 if (ConstantArrayType *ATP =
1123 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001124 return QualType(ATP, 0);
1125
1126 // If the element type isn't canonical, this won't be a canonical type either,
1127 // so fill in the canonical type field.
1128 QualType Canonical;
1129 if (!EltTy->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001130 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroffc9406122007-08-30 18:10:14 +00001131 ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001132 // Get the new insert position for the node we care about.
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001133 ConstantArrayType *NewIP =
1134 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001135 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001136 }
1137
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001138 ConstantArrayType *New =
Steve Narofff83820b2009-01-27 22:08:43 +00001139 new(*this,8)ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001140 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001141 Types.push_back(New);
1142 return QualType(New, 0);
1143}
1144
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001145/// getVariableArrayType - Returns a non-unique reference to the type for a
1146/// variable array of the specified element type.
Steve Naroffc9406122007-08-30 18:10:14 +00001147QualType ASTContext::getVariableArrayType(QualType EltTy, Expr *NumElts,
1148 ArrayType::ArraySizeModifier ASM,
1149 unsigned EltTypeQuals) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001150 // Since we don't unique expressions, it isn't possible to unique VLA's
1151 // that have an expression provided for their size.
1152
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001153 VariableArrayType *New =
Steve Narofff83820b2009-01-27 22:08:43 +00001154 new(*this,8)VariableArrayType(EltTy,QualType(), NumElts, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001155
1156 VariableArrayTypes.push_back(New);
1157 Types.push_back(New);
1158 return QualType(New, 0);
1159}
1160
Douglas Gregor898574e2008-12-05 23:32:09 +00001161/// getDependentSizedArrayType - Returns a non-unique reference to
1162/// the type for a dependently-sized array of the specified element
1163/// type. FIXME: We will need these to be uniqued, or at least
1164/// comparable, at some point.
1165QualType ASTContext::getDependentSizedArrayType(QualType EltTy, Expr *NumElts,
1166 ArrayType::ArraySizeModifier ASM,
1167 unsigned EltTypeQuals) {
1168 assert((NumElts->isTypeDependent() || NumElts->isValueDependent()) &&
1169 "Size must be type- or value-dependent!");
1170
1171 // Since we don't unique expressions, it isn't possible to unique
1172 // dependently-sized array types.
1173
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001174 DependentSizedArrayType *New =
Steve Narofff83820b2009-01-27 22:08:43 +00001175 new (*this,8) DependentSizedArrayType(EltTy, QualType(), NumElts,
1176 ASM, EltTypeQuals);
Douglas Gregor898574e2008-12-05 23:32:09 +00001177
1178 DependentSizedArrayTypes.push_back(New);
1179 Types.push_back(New);
1180 return QualType(New, 0);
1181}
1182
Eli Friedmanc5773c42008-02-15 18:16:39 +00001183QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1184 ArrayType::ArraySizeModifier ASM,
1185 unsigned EltTypeQuals) {
1186 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001187 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001188
1189 void *InsertPos = 0;
1190 if (IncompleteArrayType *ATP =
1191 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1192 return QualType(ATP, 0);
1193
1194 // If the element type isn't canonical, this won't be a canonical type
1195 // either, so fill in the canonical type field.
1196 QualType Canonical;
1197
1198 if (!EltTy->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001199 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001200 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001201
1202 // Get the new insert position for the node we care about.
1203 IncompleteArrayType *NewIP =
1204 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001205 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001206 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001207
Steve Narofff83820b2009-01-27 22:08:43 +00001208 IncompleteArrayType *New = new (*this,8) IncompleteArrayType(EltTy, Canonical,
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001209 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001210
1211 IncompleteArrayTypes.InsertNode(New, InsertPos);
1212 Types.push_back(New);
1213 return QualType(New, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001214}
1215
Steve Naroff73322922007-07-18 18:00:27 +00001216/// getVectorType - Return the unique reference to a vector type of
1217/// the specified element type and size. VectorType must be a built-in type.
1218QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001219 BuiltinType *baseType;
1220
Chris Lattnerf52ab252008-04-06 22:59:24 +00001221 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff73322922007-07-18 18:00:27 +00001222 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Reid Spencer5f016e22007-07-11 17:01:13 +00001223
1224 // Check if we've already instantiated a vector of this type.
1225 llvm::FoldingSetNodeID ID;
Steve Naroff73322922007-07-18 18:00:27 +00001226 VectorType::Profile(ID, vecType, NumElts, Type::Vector);
Reid Spencer5f016e22007-07-11 17:01:13 +00001227 void *InsertPos = 0;
1228 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1229 return QualType(VTP, 0);
1230
1231 // If the element type isn't canonical, this won't be a canonical type either,
1232 // so fill in the canonical type field.
1233 QualType Canonical;
1234 if (!vecType->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001235 Canonical = getVectorType(getCanonicalType(vecType), NumElts);
Reid Spencer5f016e22007-07-11 17:01:13 +00001236
1237 // Get the new insert position for the node we care about.
1238 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001239 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001240 }
Steve Narofff83820b2009-01-27 22:08:43 +00001241 VectorType *New = new (*this,8) VectorType(vecType, NumElts, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001242 VectorTypes.InsertNode(New, InsertPos);
1243 Types.push_back(New);
1244 return QualType(New, 0);
1245}
1246
Nate Begeman213541a2008-04-18 23:10:10 +00001247/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001248/// the specified element type and size. VectorType must be a built-in type.
Nate Begeman213541a2008-04-18 23:10:10 +00001249QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff73322922007-07-18 18:00:27 +00001250 BuiltinType *baseType;
1251
Chris Lattnerf52ab252008-04-06 22:59:24 +00001252 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begeman213541a2008-04-18 23:10:10 +00001253 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Steve Naroff73322922007-07-18 18:00:27 +00001254
1255 // Check if we've already instantiated a vector of this type.
1256 llvm::FoldingSetNodeID ID;
Nate Begeman213541a2008-04-18 23:10:10 +00001257 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector);
Steve Naroff73322922007-07-18 18:00:27 +00001258 void *InsertPos = 0;
1259 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1260 return QualType(VTP, 0);
1261
1262 // If the element type isn't canonical, this won't be a canonical type either,
1263 // so fill in the canonical type field.
1264 QualType Canonical;
1265 if (!vecType->isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001266 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Steve Naroff73322922007-07-18 18:00:27 +00001267
1268 // Get the new insert position for the node we care about.
1269 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001270 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001271 }
Steve Narofff83820b2009-01-27 22:08:43 +00001272 ExtVectorType *New = new (*this,8) ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001273 VectorTypes.InsertNode(New, InsertPos);
1274 Types.push_back(New);
1275 return QualType(New, 0);
1276}
1277
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001278QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
1279 Expr *SizeExpr,
1280 SourceLocation AttrLoc) {
1281 DependentSizedExtVectorType *New =
1282 new (*this,8) DependentSizedExtVectorType(vecType, QualType(),
1283 SizeExpr, AttrLoc);
1284
1285 DependentSizedExtVectorTypes.push_back(New);
1286 Types.push_back(New);
1287 return QualType(New, 0);
1288}
1289
Douglas Gregor72564e72009-02-26 23:50:07 +00001290/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001291///
Douglas Gregor72564e72009-02-26 23:50:07 +00001292QualType ASTContext::getFunctionNoProtoType(QualType ResultTy) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001293 // Unique functions, to guarantee there is only one function of a particular
1294 // structure.
1295 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001296 FunctionNoProtoType::Profile(ID, ResultTy);
Reid Spencer5f016e22007-07-11 17:01:13 +00001297
1298 void *InsertPos = 0;
Douglas Gregor72564e72009-02-26 23:50:07 +00001299 if (FunctionNoProtoType *FT =
1300 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001301 return QualType(FT, 0);
1302
1303 QualType Canonical;
1304 if (!ResultTy->isCanonical()) {
Douglas Gregor72564e72009-02-26 23:50:07 +00001305 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy));
Reid Spencer5f016e22007-07-11 17:01:13 +00001306
1307 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001308 FunctionNoProtoType *NewIP =
1309 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001310 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001311 }
1312
Douglas Gregor72564e72009-02-26 23:50:07 +00001313 FunctionNoProtoType *New =new(*this,8)FunctionNoProtoType(ResultTy,Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001314 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001315 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001316 return QualType(New, 0);
1317}
1318
1319/// getFunctionType - Return a normal function type with a typed argument
1320/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner61710852008-10-05 17:34:18 +00001321QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001322 unsigned NumArgs, bool isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001323 unsigned TypeQuals, bool hasExceptionSpec,
1324 bool hasAnyExceptionSpec, unsigned NumExs,
1325 const QualType *ExArray) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001326 // Unique functions, to guarantee there is only one function of a particular
1327 // structure.
1328 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001329 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001330 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
1331 NumExs, ExArray);
Reid Spencer5f016e22007-07-11 17:01:13 +00001332
1333 void *InsertPos = 0;
Douglas Gregor72564e72009-02-26 23:50:07 +00001334 if (FunctionProtoType *FTP =
1335 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001336 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001337
1338 // Determine whether the type being created is already canonical or not.
Reid Spencer5f016e22007-07-11 17:01:13 +00001339 bool isCanonical = ResultTy->isCanonical();
Sebastian Redl465226e2009-05-27 22:11:52 +00001340 if (hasExceptionSpec)
1341 isCanonical = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001342 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
1343 if (!ArgArray[i]->isCanonical())
1344 isCanonical = false;
1345
1346 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001347 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001348 QualType Canonical;
1349 if (!isCanonical) {
1350 llvm::SmallVector<QualType, 16> CanonicalArgs;
1351 CanonicalArgs.reserve(NumArgs);
1352 for (unsigned i = 0; i != NumArgs; ++i)
Chris Lattnerf52ab252008-04-06 22:59:24 +00001353 CanonicalArgs.push_back(getCanonicalType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001354
Chris Lattnerf52ab252008-04-06 22:59:24 +00001355 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001356 CanonicalArgs.data(), NumArgs,
Sebastian Redlbfa2fcb2009-05-06 23:27:55 +00001357 isVariadic, TypeQuals);
Sebastian Redl465226e2009-05-27 22:11:52 +00001358
Reid Spencer5f016e22007-07-11 17:01:13 +00001359 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001360 FunctionProtoType *NewIP =
1361 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001362 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001363 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001364
Douglas Gregor72564e72009-02-26 23:50:07 +00001365 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001366 // for two variable size arrays (for parameter and exception types) at the
1367 // end of them.
Douglas Gregor72564e72009-02-26 23:50:07 +00001368 FunctionProtoType *FTP =
Sebastian Redl465226e2009-05-27 22:11:52 +00001369 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1370 NumArgs*sizeof(QualType) +
1371 NumExs*sizeof(QualType), 8);
Douglas Gregor72564e72009-02-26 23:50:07 +00001372 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001373 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
1374 ExArray, NumExs, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001375 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001376 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001377 return QualType(FTP, 0);
1378}
1379
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001380/// getTypeDeclType - Return the unique reference to the type for the
1381/// specified type declaration.
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001382QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001383 assert(Decl && "Passed null for Decl param");
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001384 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1385
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001386 if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001387 return getTypedefType(Typedef);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001388 else if (isa<TemplateTypeParmDecl>(Decl)) {
1389 assert(false && "Template type parameter types are always available.");
1390 } else if (ObjCInterfaceDecl *ObjCInterface = dyn_cast<ObjCInterfaceDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001391 return getObjCInterfaceType(ObjCInterface);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001392
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001393 if (RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001394 if (PrevDecl)
1395 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001396 else
1397 Decl->TypeForDecl = new (*this,8) RecordType(Record);
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001398 }
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001399 else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
1400 if (PrevDecl)
1401 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001402 else
1403 Decl->TypeForDecl = new (*this,8) EnumType(Enum);
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001404 }
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001405 else
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001406 assert(false && "TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001407
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001408 if (!PrevDecl) Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001409 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001410}
1411
Reid Spencer5f016e22007-07-11 17:01:13 +00001412/// getTypedefType - Return the unique reference to the type for the
1413/// specified typename decl.
1414QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
1415 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1416
Chris Lattnerf52ab252008-04-06 22:59:24 +00001417 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
Douglas Gregor72564e72009-02-26 23:50:07 +00001418 Decl->TypeForDecl = new(*this,8) TypedefType(Type::Typedef, Decl, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001419 Types.push_back(Decl->TypeForDecl);
1420 return QualType(Decl->TypeForDecl, 0);
1421}
1422
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001423/// getObjCInterfaceType - Return the unique reference to the type for the
Steve Naroff3536b442007-09-06 21:24:23 +00001424/// specified ObjC interface decl.
Daniel Dunbar3b3a4582009-04-22 04:34:53 +00001425QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) {
Steve Naroff3536b442007-09-06 21:24:23 +00001426 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1427
Daniel Dunbar3b3a4582009-04-22 04:34:53 +00001428 ObjCInterfaceDecl *OID = const_cast<ObjCInterfaceDecl*>(Decl);
1429 Decl->TypeForDecl = new(*this,8) ObjCInterfaceType(Type::ObjCInterface, OID);
Steve Naroff3536b442007-09-06 21:24:23 +00001430 Types.push_back(Decl->TypeForDecl);
1431 return QualType(Decl->TypeForDecl, 0);
1432}
1433
Douglas Gregorfab9d672009-02-05 23:33:38 +00001434/// \brief Retrieve the template type parameter type for a template
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001435/// parameter or parameter pack with the given depth, index, and (optionally)
1436/// name.
Douglas Gregorfab9d672009-02-05 23:33:38 +00001437QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001438 bool ParameterPack,
Douglas Gregorfab9d672009-02-05 23:33:38 +00001439 IdentifierInfo *Name) {
1440 llvm::FoldingSetNodeID ID;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001441 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001442 void *InsertPos = 0;
1443 TemplateTypeParmType *TypeParm
1444 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1445
1446 if (TypeParm)
1447 return QualType(TypeParm, 0);
1448
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001449 if (Name) {
1450 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
1451 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, ParameterPack,
1452 Name, Canon);
1453 } else
1454 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001455
1456 Types.push_back(TypeParm);
1457 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1458
1459 return QualType(TypeParm, 0);
1460}
1461
Douglas Gregor55f6b142009-02-09 18:46:07 +00001462QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00001463ASTContext::getTemplateSpecializationType(TemplateName Template,
1464 const TemplateArgument *Args,
1465 unsigned NumArgs,
1466 QualType Canon) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001467 if (!Canon.isNull())
1468 Canon = getCanonicalType(Canon);
Douglas Gregorfc705b82009-02-26 22:19:44 +00001469
Douglas Gregor55f6b142009-02-09 18:46:07 +00001470 llvm::FoldingSetNodeID ID;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001471 TemplateSpecializationType::Profile(ID, Template, Args, NumArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001472
Douglas Gregor55f6b142009-02-09 18:46:07 +00001473 void *InsertPos = 0;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001474 TemplateSpecializationType *Spec
1475 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001476
1477 if (Spec)
1478 return QualType(Spec, 0);
1479
Douglas Gregor7532dc62009-03-30 22:58:21 +00001480 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00001481 sizeof(TemplateArgument) * NumArgs),
1482 8);
Douglas Gregor7532dc62009-03-30 22:58:21 +00001483 Spec = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, Canon);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001484 Types.push_back(Spec);
Douglas Gregor7532dc62009-03-30 22:58:21 +00001485 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001486
1487 return QualType(Spec, 0);
1488}
1489
Douglas Gregore4e5b052009-03-19 00:18:19 +00001490QualType
Douglas Gregorab452ba2009-03-26 23:50:42 +00001491ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
Douglas Gregore4e5b052009-03-19 00:18:19 +00001492 QualType NamedType) {
1493 llvm::FoldingSetNodeID ID;
Douglas Gregorab452ba2009-03-26 23:50:42 +00001494 QualifiedNameType::Profile(ID, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001495
1496 void *InsertPos = 0;
1497 QualifiedNameType *T
1498 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
1499 if (T)
1500 return QualType(T, 0);
1501
Douglas Gregorab452ba2009-03-26 23:50:42 +00001502 T = new (*this) QualifiedNameType(NNS, NamedType,
1503 getCanonicalType(NamedType));
Douglas Gregore4e5b052009-03-19 00:18:19 +00001504 Types.push_back(T);
1505 QualifiedNameTypes.InsertNode(T, InsertPos);
1506 return QualType(T, 0);
1507}
1508
Douglas Gregord57959a2009-03-27 23:10:48 +00001509QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1510 const IdentifierInfo *Name,
1511 QualType Canon) {
1512 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1513
1514 if (Canon.isNull()) {
1515 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1516 if (CanonNNS != NNS)
1517 Canon = getTypenameType(CanonNNS, Name);
1518 }
1519
1520 llvm::FoldingSetNodeID ID;
1521 TypenameType::Profile(ID, NNS, Name);
1522
1523 void *InsertPos = 0;
1524 TypenameType *T
1525 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1526 if (T)
1527 return QualType(T, 0);
1528
1529 T = new (*this) TypenameType(NNS, Name, Canon);
1530 Types.push_back(T);
1531 TypenameTypes.InsertNode(T, InsertPos);
1532 return QualType(T, 0);
1533}
1534
Douglas Gregor17343172009-04-01 00:28:59 +00001535QualType
1536ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1537 const TemplateSpecializationType *TemplateId,
1538 QualType Canon) {
1539 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1540
1541 if (Canon.isNull()) {
1542 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1543 QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
1544 if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
1545 const TemplateSpecializationType *CanonTemplateId
1546 = CanonType->getAsTemplateSpecializationType();
1547 assert(CanonTemplateId &&
1548 "Canonical type must also be a template specialization type");
1549 Canon = getTypenameType(CanonNNS, CanonTemplateId);
1550 }
1551 }
1552
1553 llvm::FoldingSetNodeID ID;
1554 TypenameType::Profile(ID, NNS, TemplateId);
1555
1556 void *InsertPos = 0;
1557 TypenameType *T
1558 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1559 if (T)
1560 return QualType(T, 0);
1561
1562 T = new (*this) TypenameType(NNS, TemplateId, Canon);
1563 Types.push_back(T);
1564 TypenameTypes.InsertNode(T, InsertPos);
1565 return QualType(T, 0);
1566}
1567
Chris Lattner88cb27a2008-04-07 04:56:42 +00001568/// CmpProtocolNames - Comparison predicate for sorting protocols
1569/// alphabetically.
1570static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
1571 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001572 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00001573}
1574
1575static void SortAndUniqueProtocols(ObjCProtocolDecl **&Protocols,
1576 unsigned &NumProtocols) {
1577 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
1578
1579 // Sort protocols, keyed by name.
1580 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
1581
1582 // Remove duplicates.
1583 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
1584 NumProtocols = ProtocolsEnd-Protocols;
1585}
1586
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001587/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
1588/// the given interface decl and the conforming protocol list.
1589QualType ASTContext::getObjCObjectPointerType(ObjCInterfaceDecl *Decl,
1590 ObjCProtocolDecl **Protocols,
1591 unsigned NumProtocols) {
1592 // Sort the protocol list alphabetically to canonicalize it.
1593 if (NumProtocols)
1594 SortAndUniqueProtocols(Protocols, NumProtocols);
1595
1596 llvm::FoldingSetNodeID ID;
1597 ObjCObjectPointerType::Profile(ID, Decl, Protocols, NumProtocols);
1598
1599 void *InsertPos = 0;
1600 if (ObjCObjectPointerType *QT =
1601 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1602 return QualType(QT, 0);
1603
1604 // No Match;
1605 ObjCObjectPointerType *QType =
1606 new (*this,8) ObjCObjectPointerType(Decl, Protocols, NumProtocols);
1607
1608 Types.push_back(QType);
1609 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
1610 return QualType(QType, 0);
1611}
Chris Lattner88cb27a2008-04-07 04:56:42 +00001612
Chris Lattner065f0d72008-04-07 04:44:08 +00001613/// getObjCQualifiedInterfaceType - Return a ObjCQualifiedInterfaceType type for
1614/// the given interface decl and the conforming protocol list.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001615QualType ASTContext::getObjCQualifiedInterfaceType(ObjCInterfaceDecl *Decl,
1616 ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
Chris Lattner88cb27a2008-04-07 04:56:42 +00001617 // Sort the protocol list alphabetically to canonicalize it.
1618 SortAndUniqueProtocols(Protocols, NumProtocols);
1619
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001620 llvm::FoldingSetNodeID ID;
Chris Lattnerb0489812008-04-07 06:38:24 +00001621 ObjCQualifiedInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001622
1623 void *InsertPos = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001624 if (ObjCQualifiedInterfaceType *QT =
1625 ObjCQualifiedInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001626 return QualType(QT, 0);
1627
1628 // No Match;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001629 ObjCQualifiedInterfaceType *QType =
Steve Narofff83820b2009-01-27 22:08:43 +00001630 new (*this,8) ObjCQualifiedInterfaceType(Decl, Protocols, NumProtocols);
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001631
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001632 Types.push_back(QType);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001633 ObjCQualifiedInterfaceTypes.InsertNode(QType, InsertPos);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001634 return QualType(QType, 0);
1635}
1636
Douglas Gregor72564e72009-02-26 23:50:07 +00001637/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
1638/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00001639/// multiple declarations that refer to "typeof(x)" all contain different
1640/// DeclRefExpr's. This doesn't effect the type checker, since it operates
1641/// on canonical type's (which are always unique).
Douglas Gregor72564e72009-02-26 23:50:07 +00001642QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001643 QualType Canonical = getCanonicalType(tofExpr->getType());
Douglas Gregor72564e72009-02-26 23:50:07 +00001644 TypeOfExprType *toe = new (*this,8) TypeOfExprType(tofExpr, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00001645 Types.push_back(toe);
1646 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00001647}
1648
Steve Naroff9752f252007-08-01 18:02:17 +00001649/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
1650/// TypeOfType AST's. The only motivation to unique these nodes would be
1651/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
1652/// an issue. This doesn't effect the type checker, since it operates
1653/// on canonical type's (which are always unique).
Steve Naroffd1861fd2007-07-31 12:34:36 +00001654QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001655 QualType Canonical = getCanonicalType(tofType);
Steve Narofff83820b2009-01-27 22:08:43 +00001656 TypeOfType *tot = new (*this,8) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00001657 Types.push_back(tot);
1658 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00001659}
1660
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00001661/// getDecltypeForExpr - Given an expr, will return the decltype for that
1662/// expression, according to the rules in C++0x [dcl.type.simple]p4
1663static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00001664 if (e->isTypeDependent())
1665 return Context.DependentTy;
1666
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00001667 // If e is an id expression or a class member access, decltype(e) is defined
1668 // as the type of the entity named by e.
1669 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
1670 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
1671 return VD->getType();
1672 }
1673 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
1674 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
1675 return FD->getType();
1676 }
1677 // If e is a function call or an invocation of an overloaded operator,
1678 // (parentheses around e are ignored), decltype(e) is defined as the
1679 // return type of that function.
1680 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
1681 return CE->getCallReturnType();
1682
1683 QualType T = e->getType();
1684
1685 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
1686 // defined as T&, otherwise decltype(e) is defined as T.
1687 if (e->isLvalue(Context) == Expr::LV_Valid)
1688 T = Context.getLValueReferenceType(T);
1689
1690 return T;
1691}
1692
Anders Carlsson395b4752009-06-24 19:06:50 +00001693/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
1694/// DecltypeType AST's. The only motivation to unique these nodes would be
1695/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
1696/// an issue. This doesn't effect the type checker, since it operates
1697/// on canonical type's (which are always unique).
1698QualType ASTContext::getDecltypeType(Expr *e) {
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00001699 QualType T = getDecltypeForExpr(e, *this);
1700 DecltypeType *dt = new (*this, 8) DecltypeType(e, getCanonicalType(T));
Anders Carlsson395b4752009-06-24 19:06:50 +00001701 Types.push_back(dt);
1702 return QualType(dt, 0);
1703}
1704
Reid Spencer5f016e22007-07-11 17:01:13 +00001705/// getTagDeclType - Return the unique reference to the type for the
1706/// specified TagDecl (struct/union/class/enum) decl.
1707QualType ASTContext::getTagDeclType(TagDecl *Decl) {
Ted Kremenekd778f882007-11-26 21:16:01 +00001708 assert (Decl);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001709 return getTypeDeclType(Decl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001710}
1711
1712/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
1713/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
1714/// needs to agree with the definition in <stddef.h>.
1715QualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00001716 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00001717}
1718
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00001719/// getSignedWCharType - Return the type of "signed wchar_t".
1720/// Used when in C++, as a GCC extension.
1721QualType ASTContext::getSignedWCharType() const {
1722 // FIXME: derive from "Target" ?
1723 return WCharTy;
1724}
1725
1726/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
1727/// Used when in C++, as a GCC extension.
1728QualType ASTContext::getUnsignedWCharType() const {
1729 // FIXME: derive from "Target" ?
1730 return UnsignedIntTy;
1731}
1732
Chris Lattner8b9023b2007-07-13 03:05:23 +00001733/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
1734/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
1735QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00001736 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00001737}
1738
Chris Lattnere6327742008-04-02 05:18:44 +00001739//===----------------------------------------------------------------------===//
1740// Type Operators
1741//===----------------------------------------------------------------------===//
1742
Chris Lattner77c96472008-04-06 22:41:35 +00001743/// getCanonicalType - Return the canonical (structural) type corresponding to
1744/// the specified potentially non-canonical type. The non-canonical version
1745/// of a type may have many "decorated" versions of types. Decorators can
1746/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
1747/// to be free of any of these, allowing two canonical types to be compared
1748/// for exact equality with a simple pointer comparison.
1749QualType ASTContext::getCanonicalType(QualType T) {
1750 QualType CanType = T.getTypePtr()->getCanonicalTypeInternal();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001751
1752 // If the result has type qualifiers, make sure to canonicalize them as well.
1753 unsigned TypeQuals = T.getCVRQualifiers() | CanType.getCVRQualifiers();
1754 if (TypeQuals == 0) return CanType;
1755
1756 // If the type qualifiers are on an array type, get the canonical type of the
1757 // array with the qualifiers applied to the element type.
1758 ArrayType *AT = dyn_cast<ArrayType>(CanType);
1759 if (!AT)
1760 return CanType.getQualifiedType(TypeQuals);
1761
1762 // Get the canonical version of the element with the extra qualifiers on it.
1763 // This can recursively sink qualifiers through multiple levels of arrays.
1764 QualType NewEltTy=AT->getElementType().getWithAdditionalQualifiers(TypeQuals);
1765 NewEltTy = getCanonicalType(NewEltTy);
1766
1767 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
1768 return getConstantArrayType(NewEltTy, CAT->getSize(),CAT->getSizeModifier(),
1769 CAT->getIndexTypeQualifier());
1770 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
1771 return getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
1772 IAT->getIndexTypeQualifier());
1773
Douglas Gregor898574e2008-12-05 23:32:09 +00001774 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
1775 return getDependentSizedArrayType(NewEltTy, DSAT->getSizeExpr(),
1776 DSAT->getSizeModifier(),
1777 DSAT->getIndexTypeQualifier());
1778
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001779 VariableArrayType *VAT = cast<VariableArrayType>(AT);
1780 return getVariableArrayType(NewEltTy, VAT->getSizeExpr(),
1781 VAT->getSizeModifier(),
1782 VAT->getIndexTypeQualifier());
1783}
1784
Douglas Gregor7da97d02009-05-10 22:57:19 +00001785Decl *ASTContext::getCanonicalDecl(Decl *D) {
Douglas Gregorc4ccf012009-05-10 22:59:12 +00001786 if (!D)
1787 return 0;
1788
Douglas Gregor7da97d02009-05-10 22:57:19 +00001789 if (TagDecl *Tag = dyn_cast<TagDecl>(D)) {
1790 QualType T = getTagDeclType(Tag);
1791 return cast<TagDecl>(cast<TagType>(T.getTypePtr()->CanonicalType)
1792 ->getDecl());
1793 }
1794
1795 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(D)) {
1796 while (Template->getPreviousDeclaration())
1797 Template = Template->getPreviousDeclaration();
1798 return Template;
1799 }
1800
1801 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
1802 while (Function->getPreviousDeclaration())
1803 Function = Function->getPreviousDeclaration();
1804 return const_cast<FunctionDecl *>(Function);
1805 }
1806
Douglas Gregor127102b2009-06-29 20:59:39 +00001807 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
1808 while (FunTmpl->getPreviousDeclaration())
1809 FunTmpl = FunTmpl->getPreviousDeclaration();
1810 return FunTmpl;
1811 }
1812
Douglas Gregor7da97d02009-05-10 22:57:19 +00001813 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
1814 while (Var->getPreviousDeclaration())
1815 Var = Var->getPreviousDeclaration();
1816 return const_cast<VarDecl *>(Var);
1817 }
1818
1819 return D;
1820}
1821
Douglas Gregor25a3ef72009-05-07 06:41:52 +00001822TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
1823 // If this template name refers to a template, the canonical
1824 // template name merely stores the template itself.
1825 if (TemplateDecl *Template = Name.getAsTemplateDecl())
Douglas Gregor7da97d02009-05-10 22:57:19 +00001826 return TemplateName(cast<TemplateDecl>(getCanonicalDecl(Template)));
Douglas Gregor25a3ef72009-05-07 06:41:52 +00001827
1828 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
1829 assert(DTN && "Non-dependent template names must refer to template decls.");
1830 return DTN->CanonicalTemplateName;
1831}
1832
Douglas Gregord57959a2009-03-27 23:10:48 +00001833NestedNameSpecifier *
1834ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
1835 if (!NNS)
1836 return 0;
1837
1838 switch (NNS->getKind()) {
1839 case NestedNameSpecifier::Identifier:
1840 // Canonicalize the prefix but keep the identifier the same.
1841 return NestedNameSpecifier::Create(*this,
1842 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
1843 NNS->getAsIdentifier());
1844
1845 case NestedNameSpecifier::Namespace:
1846 // A namespace is canonical; build a nested-name-specifier with
1847 // this namespace and no prefix.
1848 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
1849
1850 case NestedNameSpecifier::TypeSpec:
1851 case NestedNameSpecifier::TypeSpecWithTemplate: {
1852 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
1853 NestedNameSpecifier *Prefix = 0;
1854
1855 // FIXME: This isn't the right check!
1856 if (T->isDependentType())
1857 Prefix = getCanonicalNestedNameSpecifier(NNS->getPrefix());
1858
1859 return NestedNameSpecifier::Create(*this, Prefix,
1860 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
1861 T.getTypePtr());
1862 }
1863
1864 case NestedNameSpecifier::Global:
1865 // The global specifier is canonical and unique.
1866 return NNS;
1867 }
1868
1869 // Required to silence a GCC warning
1870 return 0;
1871}
1872
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001873
1874const ArrayType *ASTContext::getAsArrayType(QualType T) {
1875 // Handle the non-qualified case efficiently.
1876 if (T.getCVRQualifiers() == 0) {
1877 // Handle the common positive case fast.
1878 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
1879 return AT;
1880 }
1881
1882 // Handle the common negative case fast, ignoring CVR qualifiers.
1883 QualType CType = T->getCanonicalTypeInternal();
1884
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001885 // Make sure to look through type qualifiers (like ExtQuals) for the negative
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001886 // test.
1887 if (!isa<ArrayType>(CType) &&
1888 !isa<ArrayType>(CType.getUnqualifiedType()))
1889 return 0;
1890
1891 // Apply any CVR qualifiers from the array type to the element type. This
1892 // implements C99 6.7.3p8: "If the specification of an array type includes
1893 // any type qualifiers, the element type is so qualified, not the array type."
1894
1895 // If we get here, we either have type qualifiers on the type, or we have
1896 // sugar such as a typedef in the way. If we have type qualifiers on the type
1897 // we must propagate them down into the elemeng type.
1898 unsigned CVRQuals = T.getCVRQualifiers();
1899 unsigned AddrSpace = 0;
1900 Type *Ty = T.getTypePtr();
1901
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001902 // Rip through ExtQualType's and typedefs to get to a concrete type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001903 while (1) {
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001904 if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(Ty)) {
1905 AddrSpace = EXTQT->getAddressSpace();
1906 Ty = EXTQT->getBaseType();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001907 } else {
1908 T = Ty->getDesugaredType();
1909 if (T.getTypePtr() == Ty && T.getCVRQualifiers() == 0)
1910 break;
1911 CVRQuals |= T.getCVRQualifiers();
1912 Ty = T.getTypePtr();
1913 }
1914 }
1915
1916 // If we have a simple case, just return now.
1917 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
1918 if (ATy == 0 || (AddrSpace == 0 && CVRQuals == 0))
1919 return ATy;
1920
1921 // Otherwise, we have an array and we have qualifiers on it. Push the
1922 // qualifiers into the array element type and return a new array type.
1923 // Get the canonical version of the element with the extra qualifiers on it.
1924 // This can recursively sink qualifiers through multiple levels of arrays.
1925 QualType NewEltTy = ATy->getElementType();
1926 if (AddrSpace)
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001927 NewEltTy = getAddrSpaceQualType(NewEltTy, AddrSpace);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001928 NewEltTy = NewEltTy.getWithAdditionalQualifiers(CVRQuals);
1929
1930 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
1931 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
1932 CAT->getSizeModifier(),
1933 CAT->getIndexTypeQualifier()));
1934 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
1935 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
1936 IAT->getSizeModifier(),
1937 IAT->getIndexTypeQualifier()));
Douglas Gregor898574e2008-12-05 23:32:09 +00001938
Douglas Gregor898574e2008-12-05 23:32:09 +00001939 if (const DependentSizedArrayType *DSAT
1940 = dyn_cast<DependentSizedArrayType>(ATy))
1941 return cast<ArrayType>(
1942 getDependentSizedArrayType(NewEltTy,
1943 DSAT->getSizeExpr(),
1944 DSAT->getSizeModifier(),
1945 DSAT->getIndexTypeQualifier()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001946
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001947 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
1948 return cast<ArrayType>(getVariableArrayType(NewEltTy, VAT->getSizeExpr(),
1949 VAT->getSizeModifier(),
1950 VAT->getIndexTypeQualifier()));
Chris Lattner77c96472008-04-06 22:41:35 +00001951}
1952
1953
Chris Lattnere6327742008-04-02 05:18:44 +00001954/// getArrayDecayedType - Return the properly qualified result of decaying the
1955/// specified array type to a pointer. This operation is non-trivial when
1956/// handling typedefs etc. The canonical type of "T" must be an array type,
1957/// this returns a pointer to a properly qualified element of the array.
1958///
1959/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
1960QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001961 // Get the element type with 'getAsArrayType' so that we don't lose any
1962 // typedefs in the element type of the array. This also handles propagation
1963 // of type qualifiers from the array type into the element type if present
1964 // (C99 6.7.3p8).
1965 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
1966 assert(PrettyArrayType && "Not an array type!");
Chris Lattnere6327742008-04-02 05:18:44 +00001967
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001968 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00001969
1970 // int x[restrict 4] -> int *restrict
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001971 return PtrTy.getQualifiedType(PrettyArrayType->getIndexTypeQualifier());
Chris Lattnere6327742008-04-02 05:18:44 +00001972}
1973
Daniel Dunbard786f6a2009-01-05 22:14:37 +00001974QualType ASTContext::getBaseElementType(const VariableArrayType *VAT) {
Anders Carlsson6183a992008-12-21 03:44:36 +00001975 QualType ElemTy = VAT->getElementType();
1976
1977 if (const VariableArrayType *VAT = getAsVariableArrayType(ElemTy))
1978 return getBaseElementType(VAT);
1979
1980 return ElemTy;
1981}
1982
Reid Spencer5f016e22007-07-11 17:01:13 +00001983/// getFloatingRank - Return a relative rank for floating point types.
1984/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00001985static FloatingRank getFloatingRank(QualType T) {
Christopher Lambebb97e92008-02-04 02:31:56 +00001986 if (const ComplexType *CT = T->getAsComplexType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001987 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00001988
Daniel Dunbard786f6a2009-01-05 22:14:37 +00001989 assert(T->getAsBuiltinType() && "getFloatingRank(): not a floating type");
Christopher Lambebb97e92008-02-04 02:31:56 +00001990 switch (T->getAsBuiltinType()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00001991 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00001992 case BuiltinType::Float: return FloatRank;
1993 case BuiltinType::Double: return DoubleRank;
1994 case BuiltinType::LongDouble: return LongDoubleRank;
1995 }
1996}
1997
Steve Naroff716c7302007-08-27 01:41:48 +00001998/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
1999/// point or a complex type (based on typeDomain/typeSize).
2000/// 'typeDomain' is a real floating point or complex type.
2001/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00002002QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2003 QualType Domain) const {
2004 FloatingRank EltRank = getFloatingRank(Size);
2005 if (Domain->isComplexType()) {
2006 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00002007 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00002008 case FloatRank: return FloatComplexTy;
2009 case DoubleRank: return DoubleComplexTy;
2010 case LongDoubleRank: return LongDoubleComplexTy;
2011 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002012 }
Chris Lattner1361b112008-04-06 23:58:54 +00002013
2014 assert(Domain->isRealFloatingType() && "Unknown domain!");
2015 switch (EltRank) {
2016 default: assert(0 && "getFloatingRank(): illegal value for rank");
2017 case FloatRank: return FloatTy;
2018 case DoubleRank: return DoubleTy;
2019 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00002020 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002021}
2022
Chris Lattner7cfeb082008-04-06 23:55:33 +00002023/// getFloatingTypeOrder - Compare the rank of the two specified floating
2024/// point types, ignoring the domain of the type (i.e. 'double' ==
2025/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
2026/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00002027int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2028 FloatingRank LHSR = getFloatingRank(LHS);
2029 FloatingRank RHSR = getFloatingRank(RHS);
2030
2031 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002032 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00002033 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002034 return 1;
2035 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002036}
2037
Chris Lattnerf52ab252008-04-06 22:59:24 +00002038/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2039/// routine will assert if passed a built-in type that isn't an integer or enum,
2040/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00002041unsigned ASTContext::getIntegerRank(Type *T) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002042 assert(T->isCanonical() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00002043 if (EnumType* ET = dyn_cast<EnumType>(T))
2044 T = ET->getDecl()->getIntegerType().getTypePtr();
2045
2046 // There are two things which impact the integer rank: the width, and
2047 // the ordering of builtins. The builtin ordering is encoded in the
2048 // bottom three bits; the width is encoded in the bits above that.
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002049 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T))
Eli Friedmanf98aba32009-02-13 02:31:07 +00002050 return FWIT->getWidth() << 3;
Eli Friedmanf98aba32009-02-13 02:31:07 +00002051
Chris Lattnerf52ab252008-04-06 22:59:24 +00002052 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00002053 default: assert(0 && "getIntegerRank(): not a built-in integer");
2054 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002055 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002056 case BuiltinType::Char_S:
2057 case BuiltinType::Char_U:
2058 case BuiltinType::SChar:
2059 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002060 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002061 case BuiltinType::Short:
2062 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002063 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002064 case BuiltinType::Int:
2065 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002066 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002067 case BuiltinType::Long:
2068 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002069 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002070 case BuiltinType::LongLong:
2071 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002072 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00002073 case BuiltinType::Int128:
2074 case BuiltinType::UInt128:
2075 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00002076 }
2077}
2078
Chris Lattner7cfeb082008-04-06 23:55:33 +00002079/// getIntegerTypeOrder - Returns the highest ranked integer type:
2080/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
2081/// LHS < RHS, return -1.
2082int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002083 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2084 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00002085 if (LHSC == RHSC) return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00002086
Chris Lattnerf52ab252008-04-06 22:59:24 +00002087 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2088 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002089
Chris Lattner7cfeb082008-04-06 23:55:33 +00002090 unsigned LHSRank = getIntegerRank(LHSC);
2091 unsigned RHSRank = getIntegerRank(RHSC);
Reid Spencer5f016e22007-07-11 17:01:13 +00002092
Chris Lattner7cfeb082008-04-06 23:55:33 +00002093 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2094 if (LHSRank == RHSRank) return 0;
2095 return LHSRank > RHSRank ? 1 : -1;
2096 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002097
Chris Lattner7cfeb082008-04-06 23:55:33 +00002098 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2099 if (LHSUnsigned) {
2100 // If the unsigned [LHS] type is larger, return it.
2101 if (LHSRank >= RHSRank)
2102 return 1;
2103
2104 // If the signed type can represent all values of the unsigned type, it
2105 // wins. Because we are dealing with 2's complement and types that are
2106 // powers of two larger than each other, this is always safe.
2107 return -1;
2108 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00002109
Chris Lattner7cfeb082008-04-06 23:55:33 +00002110 // If the unsigned [RHS] type is larger, return it.
2111 if (RHSRank >= LHSRank)
2112 return -1;
2113
2114 // If the signed type can represent all values of the unsigned type, it
2115 // wins. Because we are dealing with 2's complement and types that are
2116 // powers of two larger than each other, this is always safe.
2117 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002118}
Anders Carlsson71993dd2007-08-17 05:31:46 +00002119
2120// getCFConstantStringType - Return the type used for constant CFStrings.
2121QualType ASTContext::getCFConstantStringType() {
2122 if (!CFConstantStringTypeDecl) {
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002123 CFConstantStringTypeDecl =
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002124 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002125 &Idents.get("NSConstantString"));
Anders Carlssonf06273f2007-11-19 00:25:30 +00002126 QualType FieldTypes[4];
Anders Carlsson71993dd2007-08-17 05:31:46 +00002127
2128 // const int *isa;
2129 FieldTypes[0] = getPointerType(IntTy.getQualifiedType(QualType::Const));
Anders Carlssonf06273f2007-11-19 00:25:30 +00002130 // int flags;
2131 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00002132 // const char *str;
Anders Carlssonf06273f2007-11-19 00:25:30 +00002133 FieldTypes[2] = getPointerType(CharTy.getQualifiedType(QualType::Const));
Anders Carlsson71993dd2007-08-17 05:31:46 +00002134 // long length;
Anders Carlssonf06273f2007-11-19 00:25:30 +00002135 FieldTypes[3] = LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002136
Anders Carlsson71993dd2007-08-17 05:31:46 +00002137 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002138 for (unsigned i = 0; i < 4; ++i) {
2139 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
2140 SourceLocation(), 0,
2141 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002142 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002143 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002144 }
2145
2146 CFConstantStringTypeDecl->completeDefinition(*this);
Anders Carlsson71993dd2007-08-17 05:31:46 +00002147 }
2148
2149 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00002150}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002151
Douglas Gregor319ac892009-04-23 22:29:11 +00002152void ASTContext::setCFConstantStringType(QualType T) {
2153 const RecordType *Rec = T->getAsRecordType();
2154 assert(Rec && "Invalid CFConstantStringType");
2155 CFConstantStringTypeDecl = Rec->getDecl();
2156}
2157
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002158QualType ASTContext::getObjCFastEnumerationStateType()
2159{
2160 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00002161 ObjCFastEnumerationStateTypeDecl =
2162 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2163 &Idents.get("__objcFastEnumerationState"));
2164
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002165 QualType FieldTypes[] = {
2166 UnsignedLongTy,
2167 getPointerType(ObjCIdType),
2168 getPointerType(UnsignedLongTy),
2169 getConstantArrayType(UnsignedLongTy,
2170 llvm::APInt(32, 5), ArrayType::Normal, 0)
2171 };
2172
Douglas Gregor44b43212008-12-11 16:49:14 +00002173 for (size_t i = 0; i < 4; ++i) {
2174 FieldDecl *Field = FieldDecl::Create(*this,
2175 ObjCFastEnumerationStateTypeDecl,
2176 SourceLocation(), 0,
2177 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002178 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002179 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002180 }
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002181
Douglas Gregor44b43212008-12-11 16:49:14 +00002182 ObjCFastEnumerationStateTypeDecl->completeDefinition(*this);
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002183 }
2184
2185 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2186}
2187
Douglas Gregor319ac892009-04-23 22:29:11 +00002188void ASTContext::setObjCFastEnumerationStateType(QualType T) {
2189 const RecordType *Rec = T->getAsRecordType();
2190 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
2191 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
2192}
2193
Anders Carlssone8c49532007-10-29 06:33:42 +00002194// This returns true if a type has been typedefed to BOOL:
2195// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00002196static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00002197 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00002198 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
2199 return II->isStr("BOOL");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002200
2201 return false;
2202}
2203
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002204/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002205/// purpose.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002206int ASTContext::getObjCEncodingTypeSize(QualType type) {
Chris Lattner98be4942008-03-05 18:54:05 +00002207 uint64_t sz = getTypeSize(type);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002208
2209 // Make all integer and enum types at least as large as an int
2210 if (sz > 0 && type->isIntegralType())
Chris Lattner98be4942008-03-05 18:54:05 +00002211 sz = std::max(sz, getTypeSize(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002212 // Treat arrays as pointers, since that's how they're passed in.
2213 else if (type->isArrayType())
Chris Lattner98be4942008-03-05 18:54:05 +00002214 sz = getTypeSize(VoidPtrTy);
2215 return sz / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002216}
2217
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002218/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002219/// declaration.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002220void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00002221 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002222 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002223 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002224 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002225 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002226 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002227 // Compute size of all parameters.
2228 // Start with computing size of a pointer in number of bytes.
2229 // FIXME: There might(should) be a better way of doing this computation!
2230 SourceLocation Loc;
Chris Lattner98be4942008-03-05 18:54:05 +00002231 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002232 // The first two arguments (self and _cmd) are pointers; account for
2233 // their size.
2234 int ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00002235 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2236 E = Decl->param_end(); PI != E; ++PI) {
2237 QualType PType = (*PI)->getType();
2238 int sz = getObjCEncodingTypeSize(PType);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002239 assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002240 ParmOffset += sz;
2241 }
2242 S += llvm::utostr(ParmOffset);
2243 S += "@0:";
2244 S += llvm::utostr(PtrSize);
2245
2246 // Argument types.
2247 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00002248 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2249 E = Decl->param_end(); PI != E; ++PI) {
2250 ParmVarDecl *PVDecl = *PI;
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00002251 QualType PType = PVDecl->getOriginalType();
2252 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00002253 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
2254 // Use array's original type only if it has known number of
2255 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00002256 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00002257 PType = PVDecl->getType();
2258 } else if (PType->isFunctionType())
2259 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002260 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002261 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00002262 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002263 getObjCEncodingForType(PType, S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002264 S += llvm::utostr(ParmOffset);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002265 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002266 }
2267}
2268
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002269/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00002270/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002271/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
2272/// NULL when getting encodings for protocol properties.
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00002273/// Property attributes are stored as a comma-delimited C string. The simple
2274/// attributes readonly and bycopy are encoded as single characters. The
2275/// parametrized attributes, getter=name, setter=name, and ivar=name, are
2276/// encoded as single characters, followed by an identifier. Property types
2277/// are also encoded as a parametrized attribute. The characters used to encode
2278/// these attributes are defined by the following enumeration:
2279/// @code
2280/// enum PropertyAttributes {
2281/// kPropertyReadOnly = 'R', // property is read-only.
2282/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
2283/// kPropertyByref = '&', // property is a reference to the value last assigned
2284/// kPropertyDynamic = 'D', // property is dynamic
2285/// kPropertyGetter = 'G', // followed by getter selector name
2286/// kPropertySetter = 'S', // followed by setter selector name
2287/// kPropertyInstanceVariable = 'V' // followed by instance variable name
2288/// kPropertyType = 't' // followed by old-style type encoding.
2289/// kPropertyWeak = 'W' // 'weak' property
2290/// kPropertyStrong = 'P' // property GC'able
2291/// kPropertyNonAtomic = 'N' // property non-atomic
2292/// };
2293/// @endcode
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002294void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
2295 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00002296 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002297 // Collect information from the property implementation decl(s).
2298 bool Dynamic = false;
2299 ObjCPropertyImplDecl *SynthesizePID = 0;
2300
2301 // FIXME: Duplicated code due to poor abstraction.
2302 if (Container) {
2303 if (const ObjCCategoryImplDecl *CID =
2304 dyn_cast<ObjCCategoryImplDecl>(Container)) {
2305 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002306 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00002307 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002308 ObjCPropertyImplDecl *PID = *i;
2309 if (PID->getPropertyDecl() == PD) {
2310 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2311 Dynamic = true;
2312 } else {
2313 SynthesizePID = PID;
2314 }
2315 }
2316 }
2317 } else {
Chris Lattner61710852008-10-05 17:34:18 +00002318 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002319 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002320 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00002321 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002322 ObjCPropertyImplDecl *PID = *i;
2323 if (PID->getPropertyDecl() == PD) {
2324 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2325 Dynamic = true;
2326 } else {
2327 SynthesizePID = PID;
2328 }
2329 }
2330 }
2331 }
2332 }
2333
2334 // FIXME: This is not very efficient.
2335 S = "T";
2336
2337 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002338 // GCC has some special rules regarding encoding of properties which
2339 // closely resembles encoding of ivars.
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002340 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002341 true /* outermost type */,
2342 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002343
2344 if (PD->isReadOnly()) {
2345 S += ",R";
2346 } else {
2347 switch (PD->getSetterKind()) {
2348 case ObjCPropertyDecl::Assign: break;
2349 case ObjCPropertyDecl::Copy: S += ",C"; break;
2350 case ObjCPropertyDecl::Retain: S += ",&"; break;
2351 }
2352 }
2353
2354 // It really isn't clear at all what this means, since properties
2355 // are "dynamic by default".
2356 if (Dynamic)
2357 S += ",D";
2358
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002359 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
2360 S += ",N";
2361
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002362 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
2363 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002364 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002365 }
2366
2367 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
2368 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002369 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002370 }
2371
2372 if (SynthesizePID) {
2373 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
2374 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00002375 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002376 }
2377
2378 // FIXME: OBJCGC: weak & strong
2379}
2380
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002381/// getLegacyIntegralTypeEncoding -
2382/// Another legacy compatibility encoding: 32-bit longs are encoded as
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002383/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002384/// 'i' or 'I' instead if encoding a struct field, or a pointer!
2385///
2386void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
2387 if (dyn_cast<TypedefType>(PointeeTy.getTypePtr())) {
2388 if (const BuiltinType *BT = PointeeTy->getAsBuiltinType()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002389 if (BT->getKind() == BuiltinType::ULong &&
2390 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002391 PointeeTy = UnsignedIntTy;
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002392 else
2393 if (BT->getKind() == BuiltinType::Long &&
2394 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002395 PointeeTy = IntTy;
2396 }
2397 }
2398}
2399
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002400void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002401 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002402 // We follow the behavior of gcc, expanding structures which are
2403 // directly pointed to, and expanding embedded structures. Note that
2404 // these rules are sufficient to prevent recursive encoding of the
2405 // same type.
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00002406 getObjCEncodingForTypeImpl(T, S, true, true, Field,
2407 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002408}
2409
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002410static void EncodeBitField(const ASTContext *Context, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002411 const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002412 const Expr *E = FD->getBitWidth();
2413 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
2414 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Eli Friedman9a901bb2009-04-26 19:19:15 +00002415 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002416 S += 'b';
2417 S += llvm::utostr(N);
2418}
2419
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002420void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
2421 bool ExpandPointedToStructures,
2422 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002423 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002424 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002425 bool EncodingProperty) {
Anders Carlssone8c49532007-10-29 06:33:42 +00002426 if (const BuiltinType *BT = T->getAsBuiltinType()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002427 if (FD && FD->isBitField()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002428 EncodeBitField(this, S, FD);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002429 }
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002430 else {
2431 char encoding;
2432 switch (BT->getKind()) {
2433 default: assert(0 && "Unhandled builtin type kind");
2434 case BuiltinType::Void: encoding = 'v'; break;
2435 case BuiltinType::Bool: encoding = 'B'; break;
2436 case BuiltinType::Char_U:
2437 case BuiltinType::UChar: encoding = 'C'; break;
2438 case BuiltinType::UShort: encoding = 'S'; break;
2439 case BuiltinType::UInt: encoding = 'I'; break;
Fariborz Jahanian72696e12009-02-11 22:31:45 +00002440 case BuiltinType::ULong:
2441 encoding =
2442 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
2443 break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002444 case BuiltinType::UInt128: encoding = 'T'; break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002445 case BuiltinType::ULongLong: encoding = 'Q'; break;
2446 case BuiltinType::Char_S:
2447 case BuiltinType::SChar: encoding = 'c'; break;
2448 case BuiltinType::Short: encoding = 's'; break;
2449 case BuiltinType::Int: encoding = 'i'; break;
Fariborz Jahanian72696e12009-02-11 22:31:45 +00002450 case BuiltinType::Long:
2451 encoding =
2452 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
2453 break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002454 case BuiltinType::LongLong: encoding = 'q'; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002455 case BuiltinType::Int128: encoding = 't'; break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002456 case BuiltinType::Float: encoding = 'f'; break;
2457 case BuiltinType::Double: encoding = 'd'; break;
2458 case BuiltinType::LongDouble: encoding = 'd'; break;
2459 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002460
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002461 S += encoding;
2462 }
Anders Carlssonc612f7b2009-04-09 21:55:45 +00002463 } else if (const ComplexType *CT = T->getAsComplexType()) {
2464 S += 'j';
2465 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
2466 false);
2467 } else if (T->isObjCQualifiedIdType()) {
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002468 getObjCEncodingForTypeImpl(getObjCIdType(), S,
2469 ExpandPointedToStructures,
2470 ExpandStructures, FD);
2471 if (FD || EncodingProperty) {
2472 // Note that we do extended encoding of protocol qualifer list
2473 // Only when doing ivar or property encoding.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002474 const ObjCObjectPointerType *QIDT = T->getAsObjCQualifiedIdType();
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002475 S += '"';
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002476 for (ObjCObjectPointerType::qual_iterator I = QIDT->qual_begin(),
Steve Naroff446ee4e2009-05-27 16:21:00 +00002477 E = QIDT->qual_end(); I != E; ++I) {
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002478 S += '<';
Steve Naroff446ee4e2009-05-27 16:21:00 +00002479 S += (*I)->getNameAsString();
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002480 S += '>';
2481 }
2482 S += '"';
2483 }
2484 return;
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002485 }
2486 else if (const PointerType *PT = T->getAsPointerType()) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002487 QualType PointeeTy = PT->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002488 bool isReadOnly = false;
2489 // For historical/compatibility reasons, the read-only qualifier of the
2490 // pointee gets emitted _before_ the '^'. The read-only qualifier of
2491 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
2492 // Also, do not emit the 'r' for anything but the outermost type!
2493 if (dyn_cast<TypedefType>(T.getTypePtr())) {
2494 if (OutermostType && T.isConstQualified()) {
2495 isReadOnly = true;
2496 S += 'r';
2497 }
2498 }
2499 else if (OutermostType) {
2500 QualType P = PointeeTy;
2501 while (P->getAsPointerType())
2502 P = P->getAsPointerType()->getPointeeType();
2503 if (P.isConstQualified()) {
2504 isReadOnly = true;
2505 S += 'r';
2506 }
2507 }
2508 if (isReadOnly) {
2509 // Another legacy compatibility encoding. Some ObjC qualifier and type
2510 // combinations need to be rearranged.
2511 // Rewrite "in const" from "nr" to "rn"
2512 const char * s = S.c_str();
2513 int len = S.length();
2514 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
2515 std::string replace = "rn";
2516 S.replace(S.end()-2, S.end(), replace);
2517 }
2518 }
Steve Naroff389bf462009-02-12 17:52:19 +00002519 if (isObjCIdStructType(PointeeTy)) {
Fariborz Jahanianc2939bc2007-10-30 17:06:23 +00002520 S += '@';
2521 return;
Fariborz Jahanianc166d732008-12-19 00:14:49 +00002522 }
2523 else if (PointeeTy->isObjCInterfaceType()) {
Fariborz Jahanianbb99bde2009-02-16 21:41:04 +00002524 if (!EncodingProperty &&
Fariborz Jahanian225dfd72009-02-16 22:09:26 +00002525 isa<TypedefType>(PointeeTy.getTypePtr())) {
Fariborz Jahanian3e1b16c2008-12-23 21:30:15 +00002526 // Another historical/compatibility reason.
2527 // We encode the underlying type which comes out as
2528 // {...};
2529 S += '^';
2530 getObjCEncodingForTypeImpl(PointeeTy, S,
2531 false, ExpandPointedToStructures,
2532 NULL);
2533 return;
2534 }
Fariborz Jahanianc166d732008-12-19 00:14:49 +00002535 S += '@';
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002536 if (FD || EncodingProperty) {
Fariborz Jahanian86f938b2009-02-21 18:23:24 +00002537 const ObjCInterfaceType *OIT =
2538 PointeeTy.getUnqualifiedType()->getAsObjCInterfaceType();
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002539 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanianadcaf542008-12-20 19:17:01 +00002540 S += '"';
2541 S += OI->getNameAsCString();
Steve Naroff446ee4e2009-05-27 16:21:00 +00002542 for (ObjCInterfaceType::qual_iterator I = OIT->qual_begin(),
2543 E = OIT->qual_end(); I != E; ++I) {
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002544 S += '<';
Steve Naroff446ee4e2009-05-27 16:21:00 +00002545 S += (*I)->getNameAsString();
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002546 S += '>';
2547 }
Fariborz Jahanianadcaf542008-12-20 19:17:01 +00002548 S += '"';
2549 }
Fariborz Jahanianc166d732008-12-19 00:14:49 +00002550 return;
Steve Naroff389bf462009-02-12 17:52:19 +00002551 } else if (isObjCClassStructType(PointeeTy)) {
Anders Carlsson8baaca52007-10-31 02:53:19 +00002552 S += '#';
2553 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002554 } else if (isObjCSelType(PointeeTy)) {
Anders Carlsson8baaca52007-10-31 02:53:19 +00002555 S += ':';
2556 return;
Fariborz Jahanianc2939bc2007-10-30 17:06:23 +00002557 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002558
2559 if (PointeeTy->isCharType()) {
2560 // char pointer types should be encoded as '*' unless it is a
2561 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00002562 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002563 S += '*';
2564 return;
2565 }
2566 }
2567
2568 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002569 getLegacyIntegralTypeEncoding(PointeeTy);
2570
2571 getObjCEncodingForTypeImpl(PointeeTy, S,
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002572 false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002573 NULL);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002574 } else if (const ArrayType *AT =
2575 // Ignore type qualifiers etc.
2576 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00002577 if (isa<IncompleteArrayType>(AT)) {
2578 // Incomplete arrays are encoded as a pointer to the array element.
2579 S += '^';
2580
2581 getObjCEncodingForTypeImpl(AT->getElementType(), S,
2582 false, ExpandStructures, FD);
2583 } else {
2584 S += '[';
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002585
Anders Carlsson559a8332009-02-22 01:38:57 +00002586 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
2587 S += llvm::utostr(CAT->getSize().getZExtValue());
2588 else {
2589 //Variable length arrays are encoded as a regular array with 0 elements.
2590 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
2591 S += '0';
2592 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002593
Anders Carlsson559a8332009-02-22 01:38:57 +00002594 getObjCEncodingForTypeImpl(AT->getElementType(), S,
2595 false, ExpandStructures, FD);
2596 S += ']';
2597 }
Anders Carlssonc0a87b72007-10-30 00:06:20 +00002598 } else if (T->getAsFunctionType()) {
2599 S += '?';
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00002600 } else if (const RecordType *RTy = T->getAsRecordType()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002601 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002602 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00002603 // Anonymous structures print as '?'
2604 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
2605 S += II->getName();
2606 } else {
2607 S += '?';
2608 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002609 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002610 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002611 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
2612 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00002613 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002614 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002615 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00002616 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002617 S += '"';
2618 }
2619
2620 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002621 if (Field->isBitField()) {
2622 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
2623 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002624 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002625 QualType qt = Field->getType();
2626 getLegacyIntegralTypeEncoding(qt);
2627 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002628 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002629 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002630 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00002631 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002632 S += RDecl->isUnion() ? ')' : '}';
Steve Naroff5e711242007-12-12 22:30:11 +00002633 } else if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002634 if (FD && FD->isBitField())
2635 EncodeBitField(this, S, FD);
2636 else
2637 S += 'i';
Steve Naroff485eeff2008-09-24 15:05:44 +00002638 } else if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00002639 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002640 } else if (T->isObjCInterfaceType()) {
2641 // @encode(class_name)
2642 ObjCInterfaceDecl *OI = T->getAsObjCInterfaceType()->getDecl();
2643 S += '{';
2644 const IdentifierInfo *II = OI->getIdentifier();
2645 S += II->getName();
2646 S += '=';
Chris Lattnerf1690852009-03-31 08:48:01 +00002647 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002648 CollectObjCIvars(OI, RecFields);
Chris Lattnerf1690852009-03-31 08:48:01 +00002649 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002650 if (RecFields[i]->isBitField())
2651 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2652 RecFields[i]);
2653 else
2654 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2655 FD);
2656 }
2657 S += '}';
2658 }
2659 else
Steve Narofff69cc5d2008-01-30 19:17:43 +00002660 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002661}
2662
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002663void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002664 std::string& S) const {
2665 if (QT & Decl::OBJC_TQ_In)
2666 S += 'n';
2667 if (QT & Decl::OBJC_TQ_Inout)
2668 S += 'N';
2669 if (QT & Decl::OBJC_TQ_Out)
2670 S += 'o';
2671 if (QT & Decl::OBJC_TQ_Bycopy)
2672 S += 'O';
2673 if (QT & Decl::OBJC_TQ_Byref)
2674 S += 'R';
2675 if (QT & Decl::OBJC_TQ_Oneway)
2676 S += 'V';
2677}
2678
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002679void ASTContext::setBuiltinVaListType(QualType T)
2680{
2681 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
2682
2683 BuiltinVaListType = T;
2684}
2685
Douglas Gregor319ac892009-04-23 22:29:11 +00002686void ASTContext::setObjCIdType(QualType T)
Steve Naroff7e219e42007-10-15 14:41:52 +00002687{
Douglas Gregor319ac892009-04-23 22:29:11 +00002688 ObjCIdType = T;
2689
2690 const TypedefType *TT = T->getAsTypedefType();
2691 if (!TT)
2692 return;
2693
2694 TypedefDecl *TD = TT->getDecl();
Steve Naroff7e219e42007-10-15 14:41:52 +00002695
2696 // typedef struct objc_object *id;
2697 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00002698 // User error - caller will issue diagnostics.
2699 if (!ptr)
2700 return;
Steve Naroff7e219e42007-10-15 14:41:52 +00002701 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00002702 // User error - caller will issue diagnostics.
2703 if (!rec)
2704 return;
Steve Naroff7e219e42007-10-15 14:41:52 +00002705 IdStructType = rec;
2706}
2707
Douglas Gregor319ac892009-04-23 22:29:11 +00002708void ASTContext::setObjCSelType(QualType T)
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002709{
Douglas Gregor319ac892009-04-23 22:29:11 +00002710 ObjCSelType = T;
2711
2712 const TypedefType *TT = T->getAsTypedefType();
2713 if (!TT)
2714 return;
2715 TypedefDecl *TD = TT->getDecl();
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002716
2717 // typedef struct objc_selector *SEL;
2718 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00002719 if (!ptr)
2720 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002721 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00002722 if (!rec)
2723 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002724 SelStructType = rec;
2725}
2726
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002727void ASTContext::setObjCProtoType(QualType QT)
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00002728{
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002729 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00002730}
2731
Douglas Gregor319ac892009-04-23 22:29:11 +00002732void ASTContext::setObjCClassType(QualType T)
Anders Carlsson8baaca52007-10-31 02:53:19 +00002733{
Douglas Gregor319ac892009-04-23 22:29:11 +00002734 ObjCClassType = T;
2735
2736 const TypedefType *TT = T->getAsTypedefType();
2737 if (!TT)
2738 return;
2739 TypedefDecl *TD = TT->getDecl();
Anders Carlsson8baaca52007-10-31 02:53:19 +00002740
2741 // typedef struct objc_class *Class;
2742 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
2743 assert(ptr && "'Class' incorrectly typed");
2744 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
2745 assert(rec && "'Class' incorrectly typed");
2746 ClassStructType = rec;
2747}
2748
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002749void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
2750 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00002751 "'NSConstantString' type already set!");
2752
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002753 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00002754}
2755
Douglas Gregor7532dc62009-03-30 22:58:21 +00002756/// \brief Retrieve the template name that represents a qualified
2757/// template name such as \c std::vector.
2758TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
2759 bool TemplateKeyword,
2760 TemplateDecl *Template) {
2761 llvm::FoldingSetNodeID ID;
2762 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
2763
2764 void *InsertPos = 0;
2765 QualifiedTemplateName *QTN =
2766 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
2767 if (!QTN) {
2768 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
2769 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
2770 }
2771
2772 return TemplateName(QTN);
2773}
2774
2775/// \brief Retrieve the template name that represents a dependent
2776/// template name such as \c MetaFun::template apply.
2777TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
2778 const IdentifierInfo *Name) {
2779 assert(NNS->isDependent() && "Nested name specifier must be dependent");
2780
2781 llvm::FoldingSetNodeID ID;
2782 DependentTemplateName::Profile(ID, NNS, Name);
2783
2784 void *InsertPos = 0;
2785 DependentTemplateName *QTN =
2786 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
2787
2788 if (QTN)
2789 return TemplateName(QTN);
2790
2791 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2792 if (CanonNNS == NNS) {
2793 QTN = new (*this,4) DependentTemplateName(NNS, Name);
2794 } else {
2795 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
2796 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
2797 }
2798
2799 DependentTemplateNames.InsertNode(QTN, InsertPos);
2800 return TemplateName(QTN);
2801}
2802
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002803/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00002804/// TargetInfo, produce the corresponding type. The unsigned @p Type
2805/// is actually a value of type @c TargetInfo::IntType.
2806QualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002807 switch (Type) {
2808 case TargetInfo::NoInt: return QualType();
2809 case TargetInfo::SignedShort: return ShortTy;
2810 case TargetInfo::UnsignedShort: return UnsignedShortTy;
2811 case TargetInfo::SignedInt: return IntTy;
2812 case TargetInfo::UnsignedInt: return UnsignedIntTy;
2813 case TargetInfo::SignedLong: return LongTy;
2814 case TargetInfo::UnsignedLong: return UnsignedLongTy;
2815 case TargetInfo::SignedLongLong: return LongLongTy;
2816 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
2817 }
2818
2819 assert(false && "Unhandled TargetInfo::IntType value");
Daniel Dunbarb3ac5432008-11-11 01:16:00 +00002820 return QualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002821}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00002822
2823//===----------------------------------------------------------------------===//
2824// Type Predicates.
2825//===----------------------------------------------------------------------===//
2826
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00002827/// isObjCNSObjectType - Return true if this is an NSObject object using
2828/// NSObject attribute on a c-style pointer type.
2829/// FIXME - Make it work directly on types.
2830///
2831bool ASTContext::isObjCNSObjectType(QualType Ty) const {
2832 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
2833 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00002834 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00002835 return true;
2836 }
2837 return false;
2838}
2839
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00002840/// isObjCObjectPointerType - Returns true if type is an Objective-C pointer
2841/// to an object type. This includes "id" and "Class" (two 'special' pointers
2842/// to struct), Interface* (pointer to ObjCInterfaceType) and id<P> (qualified
2843/// ID type).
2844bool ASTContext::isObjCObjectPointerType(QualType Ty) const {
Steve Naroffd4617772009-02-23 18:36:16 +00002845 if (Ty->isObjCQualifiedIdType())
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00002846 return true;
2847
Steve Naroff6ae98502008-10-21 18:24:04 +00002848 // Blocks are objects.
2849 if (Ty->isBlockPointerType())
2850 return true;
2851
2852 // All other object types are pointers.
Chris Lattner16ede0e2009-04-12 23:51:02 +00002853 const PointerType *PT = Ty->getAsPointerType();
2854 if (PT == 0)
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00002855 return false;
2856
Chris Lattner16ede0e2009-04-12 23:51:02 +00002857 // If this a pointer to an interface (e.g. NSString*), it is ok.
2858 if (PT->getPointeeType()->isObjCInterfaceType() ||
2859 // If is has NSObject attribute, OK as well.
2860 isObjCNSObjectType(Ty))
2861 return true;
2862
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00002863 // Check to see if this is 'id' or 'Class', both of which are typedefs for
2864 // pointer types. This looks for the typedef specifically, not for the
Chris Lattner16ede0e2009-04-12 23:51:02 +00002865 // underlying type. Iteratively strip off typedefs so that we can handle
2866 // typedefs of typedefs.
2867 while (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
2868 if (Ty.getUnqualifiedType() == getObjCIdType() ||
2869 Ty.getUnqualifiedType() == getObjCClassType())
2870 return true;
2871
2872 Ty = TDT->getDecl()->getUnderlyingType();
2873 }
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00002874
Chris Lattner16ede0e2009-04-12 23:51:02 +00002875 return false;
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00002876}
2877
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00002878/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
2879/// garbage collection attribute.
2880///
2881QualType::GCAttrTypes ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
Chris Lattnerb7d25532009-02-18 22:53:11 +00002882 QualType::GCAttrTypes GCAttrs = QualType::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00002883 if (getLangOptions().ObjC1 &&
2884 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00002885 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00002886 // Default behavious under objective-c's gc is for objective-c pointers
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00002887 // (or pointers to them) be treated as though they were declared
2888 // as __strong.
2889 if (GCAttrs == QualType::GCNone) {
2890 if (isObjCObjectPointerType(Ty))
2891 GCAttrs = QualType::Strong;
2892 else if (Ty->isPointerType())
2893 return getObjCGCAttrKind(Ty->getAsPointerType()->getPointeeType());
2894 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00002895 // Non-pointers have none gc'able attribute regardless of the attribute
2896 // set on them.
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00002897 else if (!Ty->isPointerType() && !isObjCObjectPointerType(Ty))
Fariborz Jahanianc2112182009-04-11 00:00:54 +00002898 return QualType::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00002899 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00002900 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00002901}
2902
Chris Lattner6ac46a42008-04-07 06:51:04 +00002903//===----------------------------------------------------------------------===//
2904// Type Compatibility Testing
2905//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00002906
Chris Lattner6ac46a42008-04-07 06:51:04 +00002907/// areCompatVectorTypes - Return true if the two specified vector types are
2908/// compatible.
2909static bool areCompatVectorTypes(const VectorType *LHS,
2910 const VectorType *RHS) {
2911 assert(LHS->isCanonical() && RHS->isCanonical());
2912 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00002913 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00002914}
2915
Eli Friedman3d815e72008-08-22 00:56:42 +00002916/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00002917/// compatible for assignment from RHS to LHS. This handles validation of any
2918/// protocol qualifiers on the LHS or RHS.
2919///
Eli Friedman3d815e72008-08-22 00:56:42 +00002920bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
2921 const ObjCInterfaceType *RHS) {
Chris Lattner6ac46a42008-04-07 06:51:04 +00002922 // Verify that the base decls are compatible: the RHS must be a subclass of
2923 // the LHS.
2924 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
2925 return false;
2926
2927 // RHS must have a superset of the protocols in the LHS. If the LHS is not
2928 // protocol qualified at all, then we are good.
2929 if (!isa<ObjCQualifiedInterfaceType>(LHS))
2930 return true;
2931
2932 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
2933 // isn't a superset.
2934 if (!isa<ObjCQualifiedInterfaceType>(RHS))
2935 return true; // FIXME: should return false!
2936
2937 // Finally, we must have two protocol-qualified interfaces.
2938 const ObjCQualifiedInterfaceType *LHSP =cast<ObjCQualifiedInterfaceType>(LHS);
2939 const ObjCQualifiedInterfaceType *RHSP =cast<ObjCQualifiedInterfaceType>(RHS);
Chris Lattner6ac46a42008-04-07 06:51:04 +00002940
Steve Naroff91b0b0c2009-03-01 16:12:44 +00002941 // All LHS protocols must have a presence on the RHS.
2942 assert(LHSP->qual_begin() != LHSP->qual_end() && "Empty LHS protocol list?");
Chris Lattner6ac46a42008-04-07 06:51:04 +00002943
Steve Naroff91b0b0c2009-03-01 16:12:44 +00002944 for (ObjCQualifiedInterfaceType::qual_iterator LHSPI = LHSP->qual_begin(),
2945 LHSPE = LHSP->qual_end();
2946 LHSPI != LHSPE; LHSPI++) {
2947 bool RHSImplementsProtocol = false;
2948
2949 // If the RHS doesn't implement the protocol on the left, the types
2950 // are incompatible.
2951 for (ObjCQualifiedInterfaceType::qual_iterator RHSPI = RHSP->qual_begin(),
2952 RHSPE = RHSP->qual_end();
2953 !RHSImplementsProtocol && (RHSPI != RHSPE); RHSPI++) {
2954 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier()))
2955 RHSImplementsProtocol = true;
2956 }
2957 // FIXME: For better diagnostics, consider passing back the protocol name.
2958 if (!RHSImplementsProtocol)
2959 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00002960 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00002961 // The RHS implements all protocols listed on the LHS.
2962 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00002963}
2964
Steve Naroff389bf462009-02-12 17:52:19 +00002965bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
2966 // get the "pointed to" types
2967 const PointerType *LHSPT = LHS->getAsPointerType();
2968 const PointerType *RHSPT = RHS->getAsPointerType();
2969
2970 if (!LHSPT || !RHSPT)
2971 return false;
2972
2973 QualType lhptee = LHSPT->getPointeeType();
2974 QualType rhptee = RHSPT->getPointeeType();
2975 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2976 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2977 // ID acts sort of like void* for ObjC interfaces
2978 if (LHSIface && isObjCIdStructType(rhptee))
2979 return true;
2980 if (RHSIface && isObjCIdStructType(lhptee))
2981 return true;
2982 if (!LHSIface || !RHSIface)
2983 return false;
2984 return canAssignObjCInterfaces(LHSIface, RHSIface) ||
2985 canAssignObjCInterfaces(RHSIface, LHSIface);
2986}
2987
Steve Naroffec0550f2007-10-15 20:41:53 +00002988/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
2989/// both shall have the identically qualified version of a compatible type.
2990/// C99 6.2.7p1: Two types have compatible types if their types are the
2991/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman3d815e72008-08-22 00:56:42 +00002992bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
2993 return !mergeTypes(LHS, RHS).isNull();
2994}
2995
2996QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
2997 const FunctionType *lbase = lhs->getAsFunctionType();
2998 const FunctionType *rbase = rhs->getAsFunctionType();
Douglas Gregor72564e72009-02-26 23:50:07 +00002999 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
3000 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00003001 bool allLTypes = true;
3002 bool allRTypes = true;
3003
3004 // Check return type
3005 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
3006 if (retType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00003007 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
3008 allLTypes = false;
3009 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
3010 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00003011
3012 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00003013 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
3014 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00003015 unsigned lproto_nargs = lproto->getNumArgs();
3016 unsigned rproto_nargs = rproto->getNumArgs();
3017
3018 // Compatible functions must have the same number of arguments
3019 if (lproto_nargs != rproto_nargs)
3020 return QualType();
3021
3022 // Variadic and non-variadic functions aren't compatible
3023 if (lproto->isVariadic() != rproto->isVariadic())
3024 return QualType();
3025
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003026 if (lproto->getTypeQuals() != rproto->getTypeQuals())
3027 return QualType();
3028
Eli Friedman3d815e72008-08-22 00:56:42 +00003029 // Check argument compatibility
3030 llvm::SmallVector<QualType, 10> types;
3031 for (unsigned i = 0; i < lproto_nargs; i++) {
3032 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
3033 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
3034 QualType argtype = mergeTypes(largtype, rargtype);
3035 if (argtype.isNull()) return QualType();
3036 types.push_back(argtype);
Chris Lattner61710852008-10-05 17:34:18 +00003037 if (getCanonicalType(argtype) != getCanonicalType(largtype))
3038 allLTypes = false;
3039 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
3040 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00003041 }
3042 if (allLTypes) return lhs;
3043 if (allRTypes) return rhs;
3044 return getFunctionType(retType, types.begin(), types.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003045 lproto->isVariadic(), lproto->getTypeQuals());
Eli Friedman3d815e72008-08-22 00:56:42 +00003046 }
3047
3048 if (lproto) allRTypes = false;
3049 if (rproto) allLTypes = false;
3050
Douglas Gregor72564e72009-02-26 23:50:07 +00003051 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00003052 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00003053 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00003054 if (proto->isVariadic()) return QualType();
3055 // Check that the types are compatible with the types that
3056 // would result from default argument promotions (C99 6.7.5.3p15).
3057 // The only types actually affected are promotable integer
3058 // types and floats, which would be passed as a different
3059 // type depending on whether the prototype is visible.
3060 unsigned proto_nargs = proto->getNumArgs();
3061 for (unsigned i = 0; i < proto_nargs; ++i) {
3062 QualType argTy = proto->getArgType(i);
3063 if (argTy->isPromotableIntegerType() ||
3064 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
3065 return QualType();
3066 }
3067
3068 if (allLTypes) return lhs;
3069 if (allRTypes) return rhs;
3070 return getFunctionType(retType, proto->arg_type_begin(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003071 proto->getNumArgs(), lproto->isVariadic(),
3072 lproto->getTypeQuals());
Eli Friedman3d815e72008-08-22 00:56:42 +00003073 }
3074
3075 if (allLTypes) return lhs;
3076 if (allRTypes) return rhs;
Douglas Gregor72564e72009-02-26 23:50:07 +00003077 return getFunctionNoProtoType(retType);
Eli Friedman3d815e72008-08-22 00:56:42 +00003078}
3079
3080QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
Bill Wendling43d69752007-12-03 07:33:35 +00003081 // C++ [expr]: If an expression initially has the type "reference to T", the
3082 // type is adjusted to "T" prior to any further analysis, the expression
3083 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003084 // expression is an lvalue unless the reference is an rvalue reference and
3085 // the expression is a function call (possibly inside parentheses).
Eli Friedman3d815e72008-08-22 00:56:42 +00003086 // FIXME: C++ shouldn't be going through here! The rules are different
3087 // enough that they should be handled separately.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003088 // FIXME: Merging of lvalue and rvalue references is incorrect. C++ *really*
3089 // shouldn't be going through here!
Eli Friedman3d815e72008-08-22 00:56:42 +00003090 if (const ReferenceType *RT = LHS->getAsReferenceType())
Chris Lattnerc4e40592008-04-07 04:07:56 +00003091 LHS = RT->getPointeeType();
Eli Friedman3d815e72008-08-22 00:56:42 +00003092 if (const ReferenceType *RT = RHS->getAsReferenceType())
Chris Lattnerc4e40592008-04-07 04:07:56 +00003093 RHS = RT->getPointeeType();
Chris Lattnerf3692dc2008-04-07 05:37:56 +00003094
Eli Friedman3d815e72008-08-22 00:56:42 +00003095 QualType LHSCan = getCanonicalType(LHS),
3096 RHSCan = getCanonicalType(RHS);
3097
3098 // If two types are identical, they are compatible.
3099 if (LHSCan == RHSCan)
3100 return LHS;
3101
3102 // If the qualifiers are different, the types aren't compatible
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003103 // Note that we handle extended qualifiers later, in the
3104 // case for ExtQualType.
3105 if (LHSCan.getCVRQualifiers() != RHSCan.getCVRQualifiers())
Eli Friedman3d815e72008-08-22 00:56:42 +00003106 return QualType();
3107
Eli Friedman852d63b2009-06-01 01:22:52 +00003108 Type::TypeClass LHSClass = LHSCan->getTypeClass();
3109 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00003110
Chris Lattner1adb8832008-01-14 05:45:46 +00003111 // We want to consider the two function types to be the same for these
3112 // comparisons, just force one to the other.
3113 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
3114 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00003115
Eli Friedman07d25872009-06-02 05:28:56 +00003116 // Strip off objc_gc attributes off the top level so they can be merged.
3117 // This is a complete mess, but the attribute itself doesn't make much sense.
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003118 if (RHSClass == Type::ExtQual) {
Eli Friedman07d25872009-06-02 05:28:56 +00003119 QualType::GCAttrTypes GCAttr = RHSCan.getObjCGCAttr();
3120 if (GCAttr != QualType::GCNone) {
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003121 QualType::GCAttrTypes GCLHSAttr = LHSCan.getObjCGCAttr();
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003122 // __weak attribute must appear on both declarations.
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003123 // __strong attribue is redundant if other decl is an objective-c
3124 // object pointer (or decorated with __strong attribute); otherwise
3125 // issue error.
3126 if ((GCAttr == QualType::Weak && GCLHSAttr != GCAttr) ||
3127 (GCAttr == QualType::Strong && GCLHSAttr != GCAttr &&
3128 LHSCan->isPointerType() && !isObjCObjectPointerType(LHSCan) &&
3129 !isObjCIdStructType(LHSCan->getAsPointerType()->getPointeeType())))
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003130 return QualType();
3131
Eli Friedman07d25872009-06-02 05:28:56 +00003132 RHS = QualType(cast<ExtQualType>(RHS.getDesugaredType())->getBaseType(),
3133 RHS.getCVRQualifiers());
3134 QualType Result = mergeTypes(LHS, RHS);
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003135 if (!Result.isNull()) {
3136 if (Result.getObjCGCAttr() == QualType::GCNone)
3137 Result = getObjCGCQualType(Result, GCAttr);
3138 else if (Result.getObjCGCAttr() != GCAttr)
3139 Result = QualType();
3140 }
Eli Friedman07d25872009-06-02 05:28:56 +00003141 return Result;
3142 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003143 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003144 if (LHSClass == Type::ExtQual) {
Eli Friedman07d25872009-06-02 05:28:56 +00003145 QualType::GCAttrTypes GCAttr = LHSCan.getObjCGCAttr();
3146 if (GCAttr != QualType::GCNone) {
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003147 QualType::GCAttrTypes GCRHSAttr = RHSCan.getObjCGCAttr();
3148 // __weak attribute must appear on both declarations. __strong
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003149 // __strong attribue is redundant if other decl is an objective-c
3150 // object pointer (or decorated with __strong attribute); otherwise
3151 // issue error.
3152 if ((GCAttr == QualType::Weak && GCRHSAttr != GCAttr) ||
3153 (GCAttr == QualType::Strong && GCRHSAttr != GCAttr &&
3154 RHSCan->isPointerType() && !isObjCObjectPointerType(RHSCan) &&
3155 !isObjCIdStructType(RHSCan->getAsPointerType()->getPointeeType())))
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003156 return QualType();
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003157
Eli Friedman07d25872009-06-02 05:28:56 +00003158 LHS = QualType(cast<ExtQualType>(LHS.getDesugaredType())->getBaseType(),
3159 LHS.getCVRQualifiers());
3160 QualType Result = mergeTypes(LHS, RHS);
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003161 if (!Result.isNull()) {
3162 if (Result.getObjCGCAttr() == QualType::GCNone)
3163 Result = getObjCGCQualType(Result, GCAttr);
3164 else if (Result.getObjCGCAttr() != GCAttr)
3165 Result = QualType();
3166 }
Eli Friedman354e53d2009-06-02 07:45:37 +00003167 return Result;
Eli Friedman07d25872009-06-02 05:28:56 +00003168 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003169 }
3170
Eli Friedman4c721d32008-02-12 08:23:06 +00003171 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00003172 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
3173 LHSClass = Type::ConstantArray;
3174 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
3175 RHSClass = Type::ConstantArray;
Steve Naroffec0550f2007-10-15 20:41:53 +00003176
Nate Begeman213541a2008-04-18 23:10:10 +00003177 // Canonicalize ExtVector -> Vector.
3178 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
3179 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Chris Lattnera36a61f2008-04-07 05:43:21 +00003180
Chris Lattnerb0489812008-04-07 06:38:24 +00003181 // Consider qualified interfaces and interfaces the same.
3182 if (LHSClass == Type::ObjCQualifiedInterface) LHSClass = Type::ObjCInterface;
3183 if (RHSClass == Type::ObjCQualifiedInterface) RHSClass = Type::ObjCInterface;
Eli Friedman3d815e72008-08-22 00:56:42 +00003184
Chris Lattnera36a61f2008-04-07 05:43:21 +00003185 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00003186 if (LHSClass != RHSClass) {
Steve Naroff5fd659d2009-02-21 16:18:07 +00003187 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
3188 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
Fariborz Jahanianc8d2e772009-04-15 21:54:48 +00003189
Steve Naroffd824c9c2009-04-14 15:11:46 +00003190 // 'id' and 'Class' act sort of like void* for ObjC interfaces
3191 if (LHSIface && (isObjCIdStructType(RHS) || isObjCClassStructType(RHS)))
Steve Naroff5fd659d2009-02-21 16:18:07 +00003192 return LHS;
Steve Naroffd824c9c2009-04-14 15:11:46 +00003193 if (RHSIface && (isObjCIdStructType(LHS) || isObjCClassStructType(LHS)))
Steve Naroff5fd659d2009-02-21 16:18:07 +00003194 return RHS;
3195
Steve Naroffbc76dd02008-12-10 22:14:21 +00003196 // ID is compatible with all qualified id types.
3197 if (LHS->isObjCQualifiedIdType()) {
3198 if (const PointerType *PT = RHS->getAsPointerType()) {
3199 QualType pType = PT->getPointeeType();
Steve Naroffd824c9c2009-04-14 15:11:46 +00003200 if (isObjCIdStructType(pType) || isObjCClassStructType(pType))
Steve Naroffbc76dd02008-12-10 22:14:21 +00003201 return LHS;
3202 // FIXME: need to use ObjCQualifiedIdTypesAreCompatible(LHS, RHS, true).
3203 // Unfortunately, this API is part of Sema (which we don't have access
3204 // to. Need to refactor. The following check is insufficient, since we
3205 // need to make sure the class implements the protocol.
3206 if (pType->isObjCInterfaceType())
3207 return LHS;
3208 }
3209 }
3210 if (RHS->isObjCQualifiedIdType()) {
3211 if (const PointerType *PT = LHS->getAsPointerType()) {
3212 QualType pType = PT->getPointeeType();
Steve Naroffd824c9c2009-04-14 15:11:46 +00003213 if (isObjCIdStructType(pType) || isObjCClassStructType(pType))
Steve Naroffbc76dd02008-12-10 22:14:21 +00003214 return RHS;
3215 // FIXME: need to use ObjCQualifiedIdTypesAreCompatible(LHS, RHS, true).
3216 // Unfortunately, this API is part of Sema (which we don't have access
3217 // to. Need to refactor. The following check is insufficient, since we
3218 // need to make sure the class implements the protocol.
3219 if (pType->isObjCInterfaceType())
3220 return RHS;
3221 }
3222 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003223 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
3224 // a signed integer type, or an unsigned integer type.
Eli Friedman3d815e72008-08-22 00:56:42 +00003225 if (const EnumType* ETy = LHS->getAsEnumType()) {
3226 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
3227 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00003228 }
Eli Friedman3d815e72008-08-22 00:56:42 +00003229 if (const EnumType* ETy = RHS->getAsEnumType()) {
3230 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
3231 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00003232 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003233
Eli Friedman3d815e72008-08-22 00:56:42 +00003234 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00003235 }
Eli Friedman3d815e72008-08-22 00:56:42 +00003236
Steve Naroff4a746782008-01-09 22:43:08 +00003237 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00003238 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00003239#define TYPE(Class, Base)
3240#define ABSTRACT_TYPE(Class, Base)
3241#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3242#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3243#include "clang/AST/TypeNodes.def"
3244 assert(false && "Non-canonical and dependent types shouldn't get here");
3245 return QualType();
3246
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003247 case Type::LValueReference:
3248 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00003249 case Type::MemberPointer:
3250 assert(false && "C++ should never be in mergeTypes");
3251 return QualType();
3252
3253 case Type::IncompleteArray:
3254 case Type::VariableArray:
3255 case Type::FunctionProto:
3256 case Type::ExtVector:
3257 case Type::ObjCQualifiedInterface:
3258 assert(false && "Types are eliminated above");
3259 return QualType();
3260
Chris Lattner1adb8832008-01-14 05:45:46 +00003261 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00003262 {
3263 // Merge two pointer types, while trying to preserve typedef info
3264 QualType LHSPointee = LHS->getAsPointerType()->getPointeeType();
3265 QualType RHSPointee = RHS->getAsPointerType()->getPointeeType();
3266 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
3267 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00003268 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00003269 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00003270 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00003271 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00003272 return getPointerType(ResultType);
3273 }
Steve Naroffc0febd52008-12-10 17:49:55 +00003274 case Type::BlockPointer:
3275 {
3276 // Merge two block pointer types, while trying to preserve typedef info
3277 QualType LHSPointee = LHS->getAsBlockPointerType()->getPointeeType();
3278 QualType RHSPointee = RHS->getAsBlockPointerType()->getPointeeType();
3279 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
3280 if (ResultType.isNull()) return QualType();
3281 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
3282 return LHS;
3283 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
3284 return RHS;
3285 return getBlockPointerType(ResultType);
3286 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003287 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00003288 {
3289 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
3290 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
3291 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
3292 return QualType();
3293
3294 QualType LHSElem = getAsArrayType(LHS)->getElementType();
3295 QualType RHSElem = getAsArrayType(RHS)->getElementType();
3296 QualType ResultType = mergeTypes(LHSElem, RHSElem);
3297 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00003298 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3299 return LHS;
3300 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3301 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00003302 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
3303 ArrayType::ArraySizeModifier(), 0);
3304 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
3305 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00003306 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
3307 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00003308 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3309 return LHS;
3310 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3311 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00003312 if (LVAT) {
3313 // FIXME: This isn't correct! But tricky to implement because
3314 // the array's size has to be the size of LHS, but the type
3315 // has to be different.
3316 return LHS;
3317 }
3318 if (RVAT) {
3319 // FIXME: This isn't correct! But tricky to implement because
3320 // the array's size has to be the size of RHS, but the type
3321 // has to be different.
3322 return RHS;
3323 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00003324 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
3325 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Chris Lattner61710852008-10-05 17:34:18 +00003326 return getIncompleteArrayType(ResultType, ArrayType::ArraySizeModifier(),0);
Eli Friedman3d815e72008-08-22 00:56:42 +00003327 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003328 case Type::FunctionNoProto:
Eli Friedman3d815e72008-08-22 00:56:42 +00003329 return mergeFunctionTypes(LHS, RHS);
Douglas Gregor72564e72009-02-26 23:50:07 +00003330 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00003331 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00003332 // FIXME: Why are these compatible?
Steve Naroff389bf462009-02-12 17:52:19 +00003333 if (isObjCIdStructType(LHS) && isObjCClassStructType(RHS)) return LHS;
3334 if (isObjCClassStructType(LHS) && isObjCIdStructType(RHS)) return LHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00003335 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00003336 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00003337 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00003338 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00003339 case Type::Complex:
3340 // Distinct complex types are incompatible.
3341 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00003342 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003343 // FIXME: The merged type should be an ExtVector!
Eli Friedman3d815e72008-08-22 00:56:42 +00003344 if (areCompatVectorTypes(LHS->getAsVectorType(), RHS->getAsVectorType()))
3345 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00003346 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00003347 case Type::ObjCInterface: {
Steve Naroff5fd659d2009-02-21 16:18:07 +00003348 // Check if the interfaces are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003349 // FIXME: This should be type compatibility, e.g. whether
3350 // "LHS x; RHS x;" at global scope is legal.
Steve Naroff5fd659d2009-02-21 16:18:07 +00003351 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
3352 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
3353 if (LHSIface && RHSIface &&
3354 canAssignObjCInterfaces(LHSIface, RHSIface))
3355 return LHS;
3356
Eli Friedman3d815e72008-08-22 00:56:42 +00003357 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00003358 }
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003359 case Type::ObjCObjectPointer:
3360 // FIXME: finish
Steve Naroffbc76dd02008-12-10 22:14:21 +00003361 // Distinct qualified id's are not compatible.
3362 return QualType();
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003363 case Type::FixedWidthInt:
3364 // Distinct fixed-width integers are not compatible.
3365 return QualType();
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003366 case Type::ExtQual:
3367 // FIXME: ExtQual types can be compatible even if they're not
3368 // identical!
3369 return QualType();
3370 // First attempt at an implementation, but I'm not really sure it's
3371 // right...
3372#if 0
3373 ExtQualType* LQual = cast<ExtQualType>(LHSCan);
3374 ExtQualType* RQual = cast<ExtQualType>(RHSCan);
3375 if (LQual->getAddressSpace() != RQual->getAddressSpace() ||
3376 LQual->getObjCGCAttr() != RQual->getObjCGCAttr())
3377 return QualType();
3378 QualType LHSBase, RHSBase, ResultType, ResCanUnqual;
3379 LHSBase = QualType(LQual->getBaseType(), 0);
3380 RHSBase = QualType(RQual->getBaseType(), 0);
3381 ResultType = mergeTypes(LHSBase, RHSBase);
3382 if (ResultType.isNull()) return QualType();
3383 ResCanUnqual = getCanonicalType(ResultType).getUnqualifiedType();
3384 if (LHSCan.getUnqualifiedType() == ResCanUnqual)
3385 return LHS;
3386 if (RHSCan.getUnqualifiedType() == ResCanUnqual)
3387 return RHS;
3388 ResultType = getAddrSpaceQualType(ResultType, LQual->getAddressSpace());
3389 ResultType = getObjCGCQualType(ResultType, LQual->getObjCGCAttr());
3390 ResultType.setCVRQualifiers(LHSCan.getCVRQualifiers());
3391 return ResultType;
3392#endif
Douglas Gregor7532dc62009-03-30 22:58:21 +00003393
3394 case Type::TemplateSpecialization:
3395 assert(false && "Dependent types have no size");
3396 break;
Steve Naroffec0550f2007-10-15 20:41:53 +00003397 }
Douglas Gregor72564e72009-02-26 23:50:07 +00003398
3399 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00003400}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00003401
Chris Lattner5426bf62008-04-07 07:01:58 +00003402//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00003403// Integer Predicates
3404//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00003405
Eli Friedmanad74a752008-06-28 06:23:08 +00003406unsigned ASTContext::getIntWidth(QualType T) {
3407 if (T == BoolTy)
3408 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00003409 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T)) {
3410 return FWIT->getWidth();
3411 }
3412 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00003413 return (unsigned)getTypeSize(T);
3414}
3415
3416QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
3417 assert(T->isSignedIntegerType() && "Unexpected type");
3418 if (const EnumType* ETy = T->getAsEnumType())
3419 T = ETy->getDecl()->getIntegerType();
3420 const BuiltinType* BTy = T->getAsBuiltinType();
3421 assert (BTy && "Unexpected signed integer type");
3422 switch (BTy->getKind()) {
3423 case BuiltinType::Char_S:
3424 case BuiltinType::SChar:
3425 return UnsignedCharTy;
3426 case BuiltinType::Short:
3427 return UnsignedShortTy;
3428 case BuiltinType::Int:
3429 return UnsignedIntTy;
3430 case BuiltinType::Long:
3431 return UnsignedLongTy;
3432 case BuiltinType::LongLong:
3433 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00003434 case BuiltinType::Int128:
3435 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00003436 default:
3437 assert(0 && "Unexpected signed integer type");
3438 return QualType();
3439 }
3440}
3441
Douglas Gregor2cf26342009-04-09 22:27:44 +00003442ExternalASTSource::~ExternalASTSource() { }
3443
3444void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00003445
3446
3447//===----------------------------------------------------------------------===//
3448// Builtin Type Computation
3449//===----------------------------------------------------------------------===//
3450
3451/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
3452/// pointer over the consumed characters. This returns the resultant type.
3453static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
3454 ASTContext::GetBuiltinTypeError &Error,
3455 bool AllowTypeModifiers = true) {
3456 // Modifiers.
3457 int HowLong = 0;
3458 bool Signed = false, Unsigned = false;
3459
3460 // Read the modifiers first.
3461 bool Done = false;
3462 while (!Done) {
3463 switch (*Str++) {
3464 default: Done = true; --Str; break;
3465 case 'S':
3466 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
3467 assert(!Signed && "Can't use 'S' modifier multiple times!");
3468 Signed = true;
3469 break;
3470 case 'U':
3471 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
3472 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
3473 Unsigned = true;
3474 break;
3475 case 'L':
3476 assert(HowLong <= 2 && "Can't have LLLL modifier");
3477 ++HowLong;
3478 break;
3479 }
3480 }
3481
3482 QualType Type;
3483
3484 // Read the base type.
3485 switch (*Str++) {
3486 default: assert(0 && "Unknown builtin type letter!");
3487 case 'v':
3488 assert(HowLong == 0 && !Signed && !Unsigned &&
3489 "Bad modifiers used with 'v'!");
3490 Type = Context.VoidTy;
3491 break;
3492 case 'f':
3493 assert(HowLong == 0 && !Signed && !Unsigned &&
3494 "Bad modifiers used with 'f'!");
3495 Type = Context.FloatTy;
3496 break;
3497 case 'd':
3498 assert(HowLong < 2 && !Signed && !Unsigned &&
3499 "Bad modifiers used with 'd'!");
3500 if (HowLong)
3501 Type = Context.LongDoubleTy;
3502 else
3503 Type = Context.DoubleTy;
3504 break;
3505 case 's':
3506 assert(HowLong == 0 && "Bad modifiers used with 's'!");
3507 if (Unsigned)
3508 Type = Context.UnsignedShortTy;
3509 else
3510 Type = Context.ShortTy;
3511 break;
3512 case 'i':
3513 if (HowLong == 3)
3514 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
3515 else if (HowLong == 2)
3516 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
3517 else if (HowLong == 1)
3518 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
3519 else
3520 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
3521 break;
3522 case 'c':
3523 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
3524 if (Signed)
3525 Type = Context.SignedCharTy;
3526 else if (Unsigned)
3527 Type = Context.UnsignedCharTy;
3528 else
3529 Type = Context.CharTy;
3530 break;
3531 case 'b': // boolean
3532 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
3533 Type = Context.BoolTy;
3534 break;
3535 case 'z': // size_t.
3536 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
3537 Type = Context.getSizeType();
3538 break;
3539 case 'F':
3540 Type = Context.getCFConstantStringType();
3541 break;
3542 case 'a':
3543 Type = Context.getBuiltinVaListType();
3544 assert(!Type.isNull() && "builtin va list type not initialized!");
3545 break;
3546 case 'A':
3547 // This is a "reference" to a va_list; however, what exactly
3548 // this means depends on how va_list is defined. There are two
3549 // different kinds of va_list: ones passed by value, and ones
3550 // passed by reference. An example of a by-value va_list is
3551 // x86, where va_list is a char*. An example of by-ref va_list
3552 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
3553 // we want this argument to be a char*&; for x86-64, we want
3554 // it to be a __va_list_tag*.
3555 Type = Context.getBuiltinVaListType();
3556 assert(!Type.isNull() && "builtin va list type not initialized!");
3557 if (Type->isArrayType()) {
3558 Type = Context.getArrayDecayedType(Type);
3559 } else {
3560 Type = Context.getLValueReferenceType(Type);
3561 }
3562 break;
3563 case 'V': {
3564 char *End;
3565
3566 unsigned NumElements = strtoul(Str, &End, 10);
3567 assert(End != Str && "Missing vector size");
3568
3569 Str = End;
3570
3571 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
3572 Type = Context.getVectorType(ElementType, NumElements);
3573 break;
3574 }
3575 case 'P': {
3576 IdentifierInfo *II = &Context.Idents.get("FILE");
3577 DeclContext::lookup_result Lookup
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003578 = Context.getTranslationUnitDecl()->lookup(II);
Chris Lattner86df27b2009-06-14 00:45:47 +00003579 if (Lookup.first != Lookup.second && isa<TypeDecl>(*Lookup.first)) {
3580 Type = Context.getTypeDeclType(cast<TypeDecl>(*Lookup.first));
3581 break;
3582 }
3583 else {
3584 Error = ASTContext::GE_Missing_FILE;
3585 return QualType();
3586 }
3587 }
3588 }
3589
3590 if (!AllowTypeModifiers)
3591 return Type;
3592
3593 Done = false;
3594 while (!Done) {
3595 switch (*Str++) {
3596 default: Done = true; --Str; break;
3597 case '*':
3598 Type = Context.getPointerType(Type);
3599 break;
3600 case '&':
3601 Type = Context.getLValueReferenceType(Type);
3602 break;
3603 // FIXME: There's no way to have a built-in with an rvalue ref arg.
3604 case 'C':
3605 Type = Type.getQualifiedType(QualType::Const);
3606 break;
3607 }
3608 }
3609
3610 return Type;
3611}
3612
3613/// GetBuiltinType - Return the type for the specified builtin.
3614QualType ASTContext::GetBuiltinType(unsigned id,
3615 GetBuiltinTypeError &Error) {
3616 const char *TypeStr = BuiltinInfo.GetTypeString(id);
3617
3618 llvm::SmallVector<QualType, 8> ArgTypes;
3619
3620 Error = GE_None;
3621 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
3622 if (Error != GE_None)
3623 return QualType();
3624 while (TypeStr[0] && TypeStr[0] != '.') {
3625 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
3626 if (Error != GE_None)
3627 return QualType();
3628
3629 // Do array -> pointer decay. The builtin should use the decayed type.
3630 if (Ty->isArrayType())
3631 Ty = getArrayDecayedType(Ty);
3632
3633 ArgTypes.push_back(Ty);
3634 }
3635
3636 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
3637 "'.' should only occur at end of builtin type list!");
3638
3639 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
3640 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
3641 return getFunctionNoProtoType(ResType);
3642 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
3643 TypeStr[0] == '.', 0);
3644}