blob: 12f75ae863a2fa4e698e70e446d5cc3c2d50ae13 [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 Lattner1b63e4f2009-06-14 01:54:56 +000041 BuiltinInfo(builtins), ExternalSource(0) {
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);
Douglas Gregord249e1d1f2009-05-29 20:38:28 +000045 PrintingPolicy.CPlusPlus = LangOpts.CPlusPlus;
Daniel Dunbare91593e2008-08-11 04:54:23 +000046}
47
Reid Spencer5f016e22007-07-11 17:01:13 +000048ASTContext::~ASTContext() {
49 // Deallocate all the types.
50 while (!Types.empty()) {
Ted Kremenek4b05b1d2008-05-21 16:38:54 +000051 Types.back()->Destroy(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +000052 Types.pop_back();
53 }
Eli Friedmanb26153c2008-05-27 03:08:09 +000054
Nuno Lopesb74668e2008-12-17 22:30:25 +000055 {
56 llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
57 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end();
58 while (I != E) {
59 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
60 delete R;
61 }
62 }
63
64 {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +000065 llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>::iterator
66 I = ObjCLayouts.begin(), E = ObjCLayouts.end();
Nuno Lopesb74668e2008-12-17 22:30:25 +000067 while (I != E) {
68 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
69 delete R;
70 }
71 }
72
Douglas Gregorab452ba2009-03-26 23:50:42 +000073 // Destroy nested-name-specifiers.
Douglas Gregor1ae0afa2009-03-27 23:54:10 +000074 for (llvm::FoldingSet<NestedNameSpecifier>::iterator
75 NNS = NestedNameSpecifiers.begin(),
76 NNSEnd = NestedNameSpecifiers.end();
Douglas Gregore7dcd782009-03-27 23:25:45 +000077 NNS != NNSEnd;
Douglas Gregor1ae0afa2009-03-27 23:54:10 +000078 /* Increment in loop */)
79 (*NNS++).Destroy(*this);
Douglas Gregorab452ba2009-03-26 23:50:42 +000080
81 if (GlobalNestedNameSpecifier)
82 GlobalNestedNameSpecifier->Destroy(*this);
83
Eli Friedmanb26153c2008-05-27 03:08:09 +000084 TUDecl->Destroy(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +000085}
86
Douglas Gregor2cf26342009-04-09 22:27:44 +000087void
88ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
89 ExternalSource.reset(Source.take());
90}
91
Reid Spencer5f016e22007-07-11 17:01:13 +000092void ASTContext::PrintStats() const {
93 fprintf(stderr, "*** AST Context Stats:\n");
94 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl7c80bd62009-03-16 23:22:08 +000095
Douglas Gregordbe833d2009-05-26 14:40:08 +000096 unsigned counts[] = {
97#define TYPE(Name, Parent) 0,
98#define ABSTRACT_TYPE(Name, Parent)
99#include "clang/AST/TypeNodes.def"
100 0 // Extra
101 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000102
Reid Spencer5f016e22007-07-11 17:01:13 +0000103 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
104 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000105 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000106 }
107
Douglas Gregordbe833d2009-05-26 14:40:08 +0000108 unsigned Idx = 0;
109 unsigned TotalBytes = 0;
110#define TYPE(Name, Parent) \
111 if (counts[Idx]) \
112 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
113 TotalBytes += counts[Idx] * sizeof(Name##Type); \
114 ++Idx;
115#define ABSTRACT_TYPE(Name, Parent)
116#include "clang/AST/TypeNodes.def"
117
118 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregor2cf26342009-04-09 22:27:44 +0000119
120 if (ExternalSource.get()) {
121 fprintf(stderr, "\n");
122 ExternalSource->PrintStats();
123 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000124}
125
126
127void ASTContext::InitBuiltinType(QualType &R, BuiltinType::Kind K) {
Steve Narofff83820b2009-01-27 22:08:43 +0000128 Types.push_back((R = QualType(new (*this,8) BuiltinType(K),0)).getTypePtr());
Reid Spencer5f016e22007-07-11 17:01:13 +0000129}
130
Reid Spencer5f016e22007-07-11 17:01:13 +0000131void ASTContext::InitBuiltinTypes() {
132 assert(VoidTy.isNull() && "Context reinitialized?");
133
134 // C99 6.2.5p19.
135 InitBuiltinType(VoidTy, BuiltinType::Void);
136
137 // C99 6.2.5p2.
138 InitBuiltinType(BoolTy, BuiltinType::Bool);
139 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000140 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000141 InitBuiltinType(CharTy, BuiltinType::Char_S);
142 else
143 InitBuiltinType(CharTy, BuiltinType::Char_U);
144 // C99 6.2.5p4.
145 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
146 InitBuiltinType(ShortTy, BuiltinType::Short);
147 InitBuiltinType(IntTy, BuiltinType::Int);
148 InitBuiltinType(LongTy, BuiltinType::Long);
149 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
150
151 // C99 6.2.5p6.
152 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
153 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
154 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
155 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
156 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
157
158 // C99 6.2.5p10.
159 InitBuiltinType(FloatTy, BuiltinType::Float);
160 InitBuiltinType(DoubleTy, BuiltinType::Double);
161 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000162
Chris Lattner2df9ced2009-04-30 02:43:43 +0000163 // GNU extension, 128-bit integers.
164 InitBuiltinType(Int128Ty, BuiltinType::Int128);
165 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
166
Chris Lattner3a250322009-02-26 23:43:47 +0000167 if (LangOpts.CPlusPlus) // C++ 3.9.1p5
168 InitBuiltinType(WCharTy, BuiltinType::WChar);
169 else // C99
170 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000171
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000172 // Placeholder type for functions.
Douglas Gregor898574e2008-12-05 23:32:09 +0000173 InitBuiltinType(OverloadTy, BuiltinType::Overload);
174
175 // Placeholder type for type-dependent expressions whose type is
176 // completely unknown. No code should ever check a type against
177 // DependentTy and users should never see it; however, it is here to
178 // help diagnose failures to properly check for type-dependent
179 // expressions.
180 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000181
Anders Carlssone89d1592009-06-26 18:41:36 +0000182 // Placeholder type for C++0x auto declarations whose real type has
183 // not yet been deduced.
184 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
185
Reid Spencer5f016e22007-07-11 17:01:13 +0000186 // C99 6.2.5p11.
187 FloatComplexTy = getComplexType(FloatTy);
188 DoubleComplexTy = getComplexType(DoubleTy);
189 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000190
Steve Naroff7e219e42007-10-15 14:41:52 +0000191 BuiltinVaListType = QualType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000192 ObjCIdType = QualType();
Steve Naroff7e219e42007-10-15 14:41:52 +0000193 IdStructType = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000194 ObjCClassType = QualType();
Anders Carlsson8baaca52007-10-31 02:53:19 +0000195 ClassStructType = 0;
196
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000197 ObjCConstantStringType = QualType();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000198
199 // void * type
200 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000201
202 // nullptr type (C++0x 2.14.7)
203 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000204}
205
Chris Lattner464175b2007-07-18 17:52:12 +0000206//===----------------------------------------------------------------------===//
207// Type Sizing and Analysis
208//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000209
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000210/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
211/// scalar floating point type.
212const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
213 const BuiltinType *BT = T->getAsBuiltinType();
214 assert(BT && "Not a floating point type!");
215 switch (BT->getKind()) {
216 default: assert(0 && "Not a floating point type!");
217 case BuiltinType::Float: return Target.getFloatFormat();
218 case BuiltinType::Double: return Target.getDoubleFormat();
219 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
220 }
221}
222
Chris Lattneraf707ab2009-01-24 21:53:27 +0000223/// getDeclAlign - Return a conservative estimate of the alignment of the
224/// specified decl. Note that bitfields do not have a valid alignment, so
225/// this method will assert on them.
Daniel Dunbarb7d08442009-02-17 22:16:19 +0000226unsigned ASTContext::getDeclAlignInBytes(const Decl *D) {
Eli Friedmandcdafb62009-02-22 02:56:25 +0000227 unsigned Align = Target.getCharWidth();
228
Douglas Gregor68584ed2009-06-18 16:11:24 +0000229 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>(*this))
Eli Friedmandcdafb62009-02-22 02:56:25 +0000230 Align = std::max(Align, AA->getAlignment());
231
Chris Lattneraf707ab2009-01-24 21:53:27 +0000232 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
233 QualType T = VD->getType();
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000234 if (const ReferenceType* RT = T->getAsReferenceType()) {
235 unsigned AS = RT->getPointeeType().getAddressSpace();
Anders Carlssonf0930232009-04-10 04:52:36 +0000236 Align = Target.getPointerAlign(AS);
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000237 } else if (!T->isIncompleteType() && !T->isFunctionType()) {
238 // Incomplete or function types default to 1.
Eli Friedmandcdafb62009-02-22 02:56:25 +0000239 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
240 T = cast<ArrayType>(T)->getElementType();
241
242 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
243 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000244 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000245
246 return Align / Target.getCharWidth();
Chris Lattneraf707ab2009-01-24 21:53:27 +0000247}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000248
Chris Lattnera7674d82007-07-13 22:13:22 +0000249/// getTypeSize - Return the size of the specified type, in bits. This method
250/// does not work on incomplete types.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000251std::pair<uint64_t, unsigned>
Daniel Dunbar1d751182008-11-08 05:48:37 +0000252ASTContext::getTypeInfo(const Type *T) {
Mike Stump5e301002009-02-27 18:32:39 +0000253 uint64_t Width=0;
254 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000255 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000256#define TYPE(Class, Base)
257#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000258#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000259#define DEPENDENT_TYPE(Class, Base) case Type::Class:
260#include "clang/AST/TypeNodes.def"
Douglas Gregor18857642009-04-30 17:32:17 +0000261 assert(false && "Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000262 break;
263
Chris Lattner692233e2007-07-13 22:27:08 +0000264 case Type::FunctionNoProto:
265 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000266 // GCC extension: alignof(function) = 32 bits
267 Width = 0;
268 Align = 32;
269 break;
270
Douglas Gregor72564e72009-02-26 23:50:07 +0000271 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000272 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000273 Width = 0;
274 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
275 break;
276
Steve Narofffb22d962007-08-30 01:06:46 +0000277 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000278 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Steve Narofffb22d962007-08-30 01:06:46 +0000279
Chris Lattner98be4942008-03-05 18:54:05 +0000280 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000281 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000282 Align = EltInfo.second;
283 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000284 }
Nate Begeman213541a2008-04-18 23:10:10 +0000285 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000286 case Type::Vector: {
287 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000288 getTypeInfo(cast<VectorType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000289 Width = EltInfo.first*cast<VectorType>(T)->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000290 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000291 // If the alignment is not a power of 2, round up to the next power of 2.
292 // This happens for non-power-of-2 length vectors.
293 // FIXME: this should probably be a target property.
294 Align = 1 << llvm::Log2_32_Ceil(Align);
Chris Lattner030d8842007-07-19 22:06:24 +0000295 break;
296 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000297
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000298 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000299 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000300 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000301 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000302 // GCC extension: alignof(void) = 8 bits.
303 Width = 0;
304 Align = 8;
305 break;
306
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000307 case BuiltinType::Bool:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000308 Width = Target.getBoolWidth();
309 Align = Target.getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000310 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000311 case BuiltinType::Char_S:
312 case BuiltinType::Char_U:
313 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000314 case BuiltinType::SChar:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000315 Width = Target.getCharWidth();
316 Align = Target.getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000317 break;
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000318 case BuiltinType::WChar:
319 Width = Target.getWCharWidth();
320 Align = Target.getWCharAlign();
321 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000322 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000323 case BuiltinType::Short:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000324 Width = Target.getShortWidth();
325 Align = Target.getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000326 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000327 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000328 case BuiltinType::Int:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000329 Width = Target.getIntWidth();
330 Align = Target.getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000331 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000332 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000333 case BuiltinType::Long:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000334 Width = Target.getLongWidth();
335 Align = Target.getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000336 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000337 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000338 case BuiltinType::LongLong:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000339 Width = Target.getLongLongWidth();
340 Align = Target.getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000341 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000342 case BuiltinType::Int128:
343 case BuiltinType::UInt128:
344 Width = 128;
345 Align = 128; // int128_t is 128-bit aligned on all targets.
346 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000347 case BuiltinType::Float:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000348 Width = Target.getFloatWidth();
349 Align = Target.getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000350 break;
351 case BuiltinType::Double:
Chris Lattner5426bf62008-04-07 07:01:58 +0000352 Width = Target.getDoubleWidth();
353 Align = Target.getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000354 break;
355 case BuiltinType::LongDouble:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000356 Width = Target.getLongDoubleWidth();
357 Align = Target.getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000358 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000359 case BuiltinType::NullPtr:
360 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
361 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000362 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000363 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000364 break;
Eli Friedmanf98aba32009-02-13 02:31:07 +0000365 case Type::FixedWidthInt:
366 // FIXME: This isn't precisely correct; the width/alignment should depend
367 // on the available types for the target
368 Width = cast<FixedWidthIntType>(T)->getWidth();
Chris Lattner736166b2009-02-15 21:20:13 +0000369 Width = std::max(llvm::NextPowerOf2(Width - 1), (uint64_t)8);
Eli Friedmanf98aba32009-02-13 02:31:07 +0000370 Align = Width;
371 break;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000372 case Type::ExtQual:
Chris Lattner98be4942008-03-05 18:54:05 +0000373 // FIXME: Pointers into different addr spaces could have different sizes and
374 // alignment requirements: getPointerInfo should take an AddrSpace.
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000375 return getTypeInfo(QualType(cast<ExtQualType>(T)->getBaseType(), 0));
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000376 case Type::ObjCObjectPointer:
Douglas Gregor72564e72009-02-26 23:50:07 +0000377 case Type::ObjCQualifiedInterface:
Chris Lattner5426bf62008-04-07 07:01:58 +0000378 Width = Target.getPointerWidth(0);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000379 Align = Target.getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000380 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000381 case Type::BlockPointer: {
382 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
383 Width = Target.getPointerWidth(AS);
384 Align = Target.getPointerAlign(AS);
385 break;
386 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000387 case Type::Pointer: {
388 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner5426bf62008-04-07 07:01:58 +0000389 Width = Target.getPointerWidth(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000390 Align = Target.getPointerAlign(AS);
391 break;
392 }
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000393 case Type::LValueReference:
394 case Type::RValueReference:
Chris Lattner7ab2ed82007-07-13 22:16:13 +0000395 // "When applied to a reference or a reference type, the result is the size
Chris Lattner5d2a6302007-07-18 18:26:58 +0000396 // of the referenced type." C++98 5.3.3p2: expr.sizeof.
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000397 // FIXME: This is wrong for struct layout: a reference in a struct has
398 // pointer size.
Chris Lattnerbdcd6372008-04-02 17:35:06 +0000399 return getTypeInfo(cast<ReferenceType>(T)->getPointeeType());
Sebastian Redlf30208a2009-01-24 21:16:55 +0000400 case Type::MemberPointer: {
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000401 // FIXME: This is ABI dependent. We use the Itanium C++ ABI.
402 // http://www.codesourcery.com/public/cxx-abi/abi.html#member-pointers
403 // If we ever want to support other ABIs this needs to be abstracted.
404
Sebastian Redlf30208a2009-01-24 21:16:55 +0000405 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000406 std::pair<uint64_t, unsigned> PtrDiffInfo =
407 getTypeInfo(getPointerDiffType());
408 Width = PtrDiffInfo.first;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000409 if (Pointee->isFunctionType())
410 Width *= 2;
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000411 Align = PtrDiffInfo.second;
412 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000413 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000414 case Type::Complex: {
415 // Complex types have the same alignment as their elements, but twice the
416 // size.
417 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000418 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000419 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000420 Align = EltInfo.second;
421 break;
422 }
Devang Patel44a3dde2008-06-04 21:54:36 +0000423 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000424 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000425 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
426 Width = Layout.getSize();
427 Align = Layout.getAlignment();
428 break;
429 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000430 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000431 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000432 const TagType *TT = cast<TagType>(T);
433
434 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner8389eab2008-08-09 21:35:13 +0000435 Width = 1;
436 Align = 1;
437 break;
438 }
439
Daniel Dunbar1d751182008-11-08 05:48:37 +0000440 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000441 return getTypeInfo(ET->getDecl()->getIntegerType());
442
Daniel Dunbar1d751182008-11-08 05:48:37 +0000443 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000444 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
445 Width = Layout.getSize();
446 Align = Layout.getAlignment();
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000447 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000448 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000449
Douglas Gregor18857642009-04-30 17:32:17 +0000450 case Type::Typedef: {
451 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregor68584ed2009-06-18 16:11:24 +0000452 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>(*this)) {
Douglas Gregor18857642009-04-30 17:32:17 +0000453 Align = Aligned->getAlignment();
454 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
455 } else
456 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregor7532dc62009-03-30 22:58:21 +0000457 break;
Chris Lattner71763312008-04-06 22:05:18 +0000458 }
Douglas Gregor18857642009-04-30 17:32:17 +0000459
460 case Type::TypeOfExpr:
461 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
462 .getTypePtr());
463
464 case Type::TypeOf:
465 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
466
Anders Carlsson395b4752009-06-24 19:06:50 +0000467 case Type::Decltype:
468 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
469 .getTypePtr());
470
Douglas Gregor18857642009-04-30 17:32:17 +0000471 case Type::QualifiedName:
472 return getTypeInfo(cast<QualifiedNameType>(T)->getNamedType().getTypePtr());
473
474 case Type::TemplateSpecialization:
475 assert(getCanonicalType(T) != T &&
476 "Cannot request the size of a dependent type");
477 // FIXME: this is likely to be wrong once we support template
478 // aliases, since a template alias could refer to a typedef that
479 // has an __aligned__ attribute on it.
480 return getTypeInfo(getCanonicalType(T));
481 }
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000482
Chris Lattner464175b2007-07-18 17:52:12 +0000483 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000484 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +0000485}
486
Chris Lattner34ebde42009-01-27 18:08:34 +0000487/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
488/// type for the current target in bits. This can be different than the ABI
489/// alignment in cases where it is beneficial for performance to overalign
490/// a data type.
491unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
492 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +0000493
494 // Double and long long should be naturally aligned if possible.
495 if (const ComplexType* CT = T->getAsComplexType())
496 T = CT->getElementType().getTypePtr();
497 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
498 T->isSpecificBuiltinType(BuiltinType::LongLong))
499 return std::max(ABIAlign, (unsigned)getTypeSize(T));
500
Chris Lattner34ebde42009-01-27 18:08:34 +0000501 return ABIAlign;
502}
503
504
Devang Patel8b277042008-06-04 21:22:16 +0000505/// LayoutField - Field layout.
506void ASTRecordLayout::LayoutField(const FieldDecl *FD, unsigned FieldNo,
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000507 bool IsUnion, unsigned StructPacking,
Devang Patel8b277042008-06-04 21:22:16 +0000508 ASTContext &Context) {
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000509 unsigned FieldPacking = StructPacking;
Devang Patel8b277042008-06-04 21:22:16 +0000510 uint64_t FieldOffset = IsUnion ? 0 : Size;
511 uint64_t FieldSize;
512 unsigned FieldAlign;
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000513
514 // FIXME: Should this override struct packing? Probably we want to
515 // take the minimum?
Douglas Gregor68584ed2009-06-18 16:11:24 +0000516 if (const PackedAttr *PA = FD->getAttr<PackedAttr>(Context))
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000517 FieldPacking = PA->getAlignment();
Devang Patel8b277042008-06-04 21:22:16 +0000518
519 if (const Expr *BitWidthExpr = FD->getBitWidth()) {
520 // TODO: Need to check this algorithm on other targets!
521 // (tested on Linux-X86)
Eli Friedman9a901bb2009-04-26 19:19:15 +0000522 FieldSize = BitWidthExpr->EvaluateAsInt(Context).getZExtValue();
Devang Patel8b277042008-06-04 21:22:16 +0000523
524 std::pair<uint64_t, unsigned> FieldInfo =
525 Context.getTypeInfo(FD->getType());
526 uint64_t TypeSize = FieldInfo.first;
527
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000528 // Determine the alignment of this bitfield. The packing
529 // attributes define a maximum and the alignment attribute defines
530 // a minimum.
531 // FIXME: What is the right behavior when the specified alignment
532 // is smaller than the specified packing?
Devang Patel8b277042008-06-04 21:22:16 +0000533 FieldAlign = FieldInfo.second;
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000534 if (FieldPacking)
535 FieldAlign = std::min(FieldAlign, FieldPacking);
Douglas Gregor68584ed2009-06-18 16:11:24 +0000536 if (const AlignedAttr *AA = FD->getAttr<AlignedAttr>(Context))
Devang Patel8b277042008-06-04 21:22:16 +0000537 FieldAlign = std::max(FieldAlign, AA->getAlignment());
538
539 // Check if we need to add padding to give the field the correct
540 // alignment.
541 if (FieldSize == 0 || (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize)
542 FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1);
543
544 // Padding members don't affect overall alignment
545 if (!FD->getIdentifier())
546 FieldAlign = 1;
547 } else {
Chris Lattner8389eab2008-08-09 21:35:13 +0000548 if (FD->getType()->isIncompleteArrayType()) {
549 // This is a flexible array member; we can't directly
Devang Patel8b277042008-06-04 21:22:16 +0000550 // query getTypeInfo about these, so we figure it out here.
551 // Flexible array members don't have any size, but they
552 // have to be aligned appropriately for their element type.
553 FieldSize = 0;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000554 const ArrayType* ATy = Context.getAsArrayType(FD->getType());
Devang Patel8b277042008-06-04 21:22:16 +0000555 FieldAlign = Context.getTypeAlign(ATy->getElementType());
Anders Carlsson2f1169f2009-04-10 05:31:15 +0000556 } else if (const ReferenceType *RT = FD->getType()->getAsReferenceType()) {
557 unsigned AS = RT->getPointeeType().getAddressSpace();
558 FieldSize = Context.Target.getPointerWidth(AS);
559 FieldAlign = Context.Target.getPointerAlign(AS);
Devang Patel8b277042008-06-04 21:22:16 +0000560 } else {
561 std::pair<uint64_t, unsigned> FieldInfo =
562 Context.getTypeInfo(FD->getType());
563 FieldSize = FieldInfo.first;
564 FieldAlign = FieldInfo.second;
565 }
566
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000567 // Determine the alignment of this bitfield. The packing
568 // attributes define a maximum and the alignment attribute defines
569 // a minimum. Additionally, the packing alignment must be at least
570 // a byte for non-bitfields.
571 //
572 // FIXME: What is the right behavior when the specified alignment
573 // is smaller than the specified packing?
574 if (FieldPacking)
575 FieldAlign = std::min(FieldAlign, std::max(8U, FieldPacking));
Douglas Gregor68584ed2009-06-18 16:11:24 +0000576 if (const AlignedAttr *AA = FD->getAttr<AlignedAttr>(Context))
Devang Patel8b277042008-06-04 21:22:16 +0000577 FieldAlign = std::max(FieldAlign, AA->getAlignment());
578
579 // Round up the current record size to the field's alignment boundary.
580 FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1);
581 }
582
583 // Place this field at the current location.
584 FieldOffsets[FieldNo] = FieldOffset;
585
586 // Reserve space for this field.
587 if (IsUnion) {
588 Size = std::max(Size, FieldSize);
589 } else {
590 Size = FieldOffset + FieldSize;
591 }
592
Daniel Dunbard6884a02009-05-04 05:16:21 +0000593 // Remember the next available offset.
594 NextOffset = Size;
595
Devang Patel8b277042008-06-04 21:22:16 +0000596 // Remember max struct/class alignment.
597 Alignment = std::max(Alignment, FieldAlign);
598}
599
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000600static void CollectLocalObjCIvars(ASTContext *Ctx,
601 const ObjCInterfaceDecl *OI,
602 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000603 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
604 E = OI->ivar_end(); I != E; ++I) {
Chris Lattnerf1690852009-03-31 08:48:01 +0000605 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000606 if (!IVDecl->isInvalidDecl())
607 Fields.push_back(cast<FieldDecl>(IVDecl));
608 }
609}
610
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000611void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
612 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
613 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
614 CollectObjCIvars(SuperClass, Fields);
615 CollectLocalObjCIvars(this, OI, Fields);
616}
617
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000618/// ShallowCollectObjCIvars -
619/// Collect all ivars, including those synthesized, in the current class.
620///
621void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
622 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars,
623 bool CollectSynthesized) {
624 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
625 E = OI->ivar_end(); I != E; ++I) {
626 Ivars.push_back(*I);
627 }
628 if (CollectSynthesized)
629 CollectSynthesizedIvars(OI, Ivars);
630}
631
Fariborz Jahanian98200742009-05-12 18:14:29 +0000632void ASTContext::CollectProtocolSynthesizedIvars(const ObjCProtocolDecl *PD,
633 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
634 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(*this),
635 E = PD->prop_end(*this); I != E; ++I)
636 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
637 Ivars.push_back(Ivar);
638
639 // Also look into nested protocols.
640 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
641 E = PD->protocol_end(); P != E; ++P)
642 CollectProtocolSynthesizedIvars(*P, Ivars);
643}
644
645/// CollectSynthesizedIvars -
646/// This routine collect synthesized ivars for the designated class.
647///
648void ASTContext::CollectSynthesizedIvars(const ObjCInterfaceDecl *OI,
649 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
650 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(*this),
651 E = OI->prop_end(*this); I != E; ++I) {
652 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
653 Ivars.push_back(Ivar);
654 }
655 // Also look into interface's protocol list for properties declared
656 // in the protocol and whose ivars are synthesized.
657 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
658 PE = OI->protocol_end(); P != PE; ++P) {
659 ObjCProtocolDecl *PD = (*P);
660 CollectProtocolSynthesizedIvars(PD, Ivars);
661 }
662}
663
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000664unsigned ASTContext::CountProtocolSynthesizedIvars(const ObjCProtocolDecl *PD) {
665 unsigned count = 0;
666 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(*this),
667 E = PD->prop_end(*this); I != E; ++I)
668 if ((*I)->getPropertyIvarDecl())
669 ++count;
670
671 // Also look into nested protocols.
672 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
673 E = PD->protocol_end(); P != E; ++P)
674 count += CountProtocolSynthesizedIvars(*P);
675 return count;
676}
677
678unsigned ASTContext::CountSynthesizedIvars(const ObjCInterfaceDecl *OI)
679{
680 unsigned count = 0;
681 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(*this),
682 E = OI->prop_end(*this); I != E; ++I) {
683 if ((*I)->getPropertyIvarDecl())
684 ++count;
685 }
686 // Also look into interface's protocol list for properties declared
687 // in the protocol and whose ivars are synthesized.
688 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
689 PE = OI->protocol_end(); P != PE; ++P) {
690 ObjCProtocolDecl *PD = (*P);
691 count += CountProtocolSynthesizedIvars(PD);
692 }
693 return count;
694}
695
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000696/// getInterfaceLayoutImpl - Get or compute information about the
697/// layout of the given interface.
698///
699/// \param Impl - If given, also include the layout of the interface's
700/// implementation. This may differ by including synthesized ivars.
Devang Patel44a3dde2008-06-04 21:54:36 +0000701const ASTRecordLayout &
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000702ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
703 const ObjCImplementationDecl *Impl) {
Daniel Dunbar532d4da2009-05-03 13:15:50 +0000704 assert(!D->isForwardDecl() && "Invalid interface decl!");
705
Devang Patel44a3dde2008-06-04 21:54:36 +0000706 // Look up this layout, if already laid out, return what we have.
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000707 ObjCContainerDecl *Key =
708 Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
709 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
710 return *Entry;
Devang Patel44a3dde2008-06-04 21:54:36 +0000711
Daniel Dunbar453addb2009-05-03 11:16:44 +0000712 unsigned FieldCount = D->ivar_size();
713 // Add in synthesized ivar count if laying out an implementation.
714 if (Impl) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000715 unsigned SynthCount = CountSynthesizedIvars(D);
716 FieldCount += SynthCount;
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000717 // If there aren't any sythesized ivars then reuse the interface
Daniel Dunbar453addb2009-05-03 11:16:44 +0000718 // entry. Note we can't cache this because we simply free all
719 // entries later; however we shouldn't look up implementations
720 // frequently.
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000721 if (SynthCount == 0)
Daniel Dunbar453addb2009-05-03 11:16:44 +0000722 return getObjCLayout(D, 0);
723 }
724
Devang Patel6a5a34c2008-06-06 02:14:01 +0000725 ASTRecordLayout *NewEntry = NULL;
Devang Patel6a5a34c2008-06-06 02:14:01 +0000726 if (ObjCInterfaceDecl *SD = D->getSuperClass()) {
Devang Patel6a5a34c2008-06-06 02:14:01 +0000727 const ASTRecordLayout &SL = getASTObjCInterfaceLayout(SD);
728 unsigned Alignment = SL.getAlignment();
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000729
Daniel Dunbar913af352009-05-07 21:58:26 +0000730 // We start laying out ivars not at the end of the superclass
731 // structure, but at the next byte following the last field.
732 uint64_t Size = llvm::RoundUpToAlignment(SL.NextOffset, 8);
Daniel Dunbard6884a02009-05-04 05:16:21 +0000733
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000734 ObjCLayouts[Key] = NewEntry = new ASTRecordLayout(Size, Alignment);
Devang Patel6a5a34c2008-06-06 02:14:01 +0000735 NewEntry->InitializeLayout(FieldCount);
Devang Patel6a5a34c2008-06-06 02:14:01 +0000736 } else {
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000737 ObjCLayouts[Key] = NewEntry = new ASTRecordLayout();
Devang Patel6a5a34c2008-06-06 02:14:01 +0000738 NewEntry->InitializeLayout(FieldCount);
739 }
Devang Patel44a3dde2008-06-04 21:54:36 +0000740
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000741 unsigned StructPacking = 0;
Douglas Gregor68584ed2009-06-18 16:11:24 +0000742 if (const PackedAttr *PA = D->getAttr<PackedAttr>(*this))
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000743 StructPacking = PA->getAlignment();
Devang Patel44a3dde2008-06-04 21:54:36 +0000744
Douglas Gregor68584ed2009-06-18 16:11:24 +0000745 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>(*this))
Devang Patel44a3dde2008-06-04 21:54:36 +0000746 NewEntry->SetAlignment(std::max(NewEntry->getAlignment(),
747 AA->getAlignment()));
748
749 // Layout each ivar sequentially.
750 unsigned i = 0;
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000751 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
752 ShallowCollectObjCIvars(D, Ivars, Impl);
753 for (unsigned k = 0, e = Ivars.size(); k != e; ++k)
754 NewEntry->LayoutField(Ivars[k], i++, false, StructPacking, *this);
755
Devang Patel44a3dde2008-06-04 21:54:36 +0000756 // Finally, round the size of the total struct up to the alignment of the
757 // struct itself.
758 NewEntry->FinalizeLayout();
759 return *NewEntry;
760}
761
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000762const ASTRecordLayout &
763ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
764 return getObjCLayout(D, 0);
765}
766
767const ASTRecordLayout &
768ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
769 return getObjCLayout(D->getClassInterface(), D);
770}
771
Devang Patel88a981b2007-11-01 19:11:01 +0000772/// getASTRecordLayout - Get or compute information about the layout of the
Chris Lattner464175b2007-07-18 17:52:12 +0000773/// specified record (struct/union/class), which indicates its size and field
774/// position information.
Chris Lattner98be4942008-03-05 18:54:05 +0000775const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +0000776 D = D->getDefinition(*this);
777 assert(D && "Cannot get layout of forward declarations!");
Eli Friedman4bd998b2008-05-30 09:31:38 +0000778
Chris Lattner464175b2007-07-18 17:52:12 +0000779 // Look up this layout, if already laid out, return what we have.
Devang Patel88a981b2007-11-01 19:11:01 +0000780 const ASTRecordLayout *&Entry = ASTRecordLayouts[D];
Chris Lattner464175b2007-07-18 17:52:12 +0000781 if (Entry) return *Entry;
Eli Friedman4bd998b2008-05-30 09:31:38 +0000782
Devang Patel88a981b2007-11-01 19:11:01 +0000783 // Allocate and assign into ASTRecordLayouts here. The "Entry" reference can
784 // be invalidated (dangle) if the ASTRecordLayouts hashtable is inserted into.
785 ASTRecordLayout *NewEntry = new ASTRecordLayout();
Chris Lattner464175b2007-07-18 17:52:12 +0000786 Entry = NewEntry;
Eli Friedman4bd998b2008-05-30 09:31:38 +0000787
Douglas Gregore267ff32008-12-11 20:41:00 +0000788 // FIXME: Avoid linear walk through the fields, if possible.
Douglas Gregor6ab35242009-04-09 21:40:53 +0000789 NewEntry->InitializeLayout(std::distance(D->field_begin(*this),
790 D->field_end(*this)));
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000791 bool IsUnion = D->isUnion();
Chris Lattner464175b2007-07-18 17:52:12 +0000792
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000793 unsigned StructPacking = 0;
Douglas Gregor68584ed2009-06-18 16:11:24 +0000794 if (const PackedAttr *PA = D->getAttr<PackedAttr>(*this))
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000795 StructPacking = PA->getAlignment();
796
Douglas Gregor68584ed2009-06-18 16:11:24 +0000797 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>(*this))
Devang Patel8b277042008-06-04 21:22:16 +0000798 NewEntry->SetAlignment(std::max(NewEntry->getAlignment(),
799 AA->getAlignment()));
Anders Carlsson8af226a2008-02-18 07:13:09 +0000800
Eli Friedman4bd998b2008-05-30 09:31:38 +0000801 // Layout each field, for now, just sequentially, respecting alignment. In
802 // the future, this will need to be tweakable by targets.
Douglas Gregor44b43212008-12-11 16:49:14 +0000803 unsigned FieldIdx = 0;
Douglas Gregor6ab35242009-04-09 21:40:53 +0000804 for (RecordDecl::field_iterator Field = D->field_begin(*this),
805 FieldEnd = D->field_end(*this);
Douglas Gregor44b43212008-12-11 16:49:14 +0000806 Field != FieldEnd; (void)++Field, ++FieldIdx)
807 NewEntry->LayoutField(*Field, FieldIdx, IsUnion, StructPacking, *this);
Eli Friedman4bd998b2008-05-30 09:31:38 +0000808
809 // Finally, round the size of the total struct up to the alignment of the
810 // struct itself.
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000811 NewEntry->FinalizeLayout(getLangOptions().CPlusPlus);
Chris Lattner5d2a6302007-07-18 18:26:58 +0000812 return *NewEntry;
Chris Lattner464175b2007-07-18 17:52:12 +0000813}
814
Chris Lattnera7674d82007-07-13 22:13:22 +0000815//===----------------------------------------------------------------------===//
816// Type creation/memoization methods
817//===----------------------------------------------------------------------===//
818
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000819QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerf52ab252008-04-06 22:59:24 +0000820 QualType CanT = getCanonicalType(T);
821 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +0000822 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +0000823
824 // If we are composing extended qualifiers together, merge together into one
825 // ExtQualType node.
826 unsigned CVRQuals = T.getCVRQualifiers();
827 QualType::GCAttrTypes GCAttr = QualType::GCNone;
828 Type *TypeNode = T.getTypePtr();
Chris Lattnerf46699c2008-02-20 20:55:12 +0000829
Chris Lattnerb7d25532009-02-18 22:53:11 +0000830 if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
831 // If this type already has an address space specified, it cannot get
832 // another one.
833 assert(EQT->getAddressSpace() == 0 &&
834 "Type cannot be in multiple addr spaces!");
835 GCAttr = EQT->getObjCGCAttr();
836 TypeNode = EQT->getBaseType();
837 }
Chris Lattnerf46699c2008-02-20 20:55:12 +0000838
Chris Lattnerb7d25532009-02-18 22:53:11 +0000839 // Check if we've already instantiated this type.
Christopher Lambebb97e92008-02-04 02:31:56 +0000840 llvm::FoldingSetNodeID ID;
Chris Lattnerb7d25532009-02-18 22:53:11 +0000841 ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
Christopher Lambebb97e92008-02-04 02:31:56 +0000842 void *InsertPos = 0;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000843 if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattnerb7d25532009-02-18 22:53:11 +0000844 return QualType(EXTQy, CVRQuals);
845
Christopher Lambebb97e92008-02-04 02:31:56 +0000846 // If the base type isn't canonical, this won't be a canonical type either,
847 // so fill in the canonical type field.
848 QualType Canonical;
Chris Lattnerb7d25532009-02-18 22:53:11 +0000849 if (!TypeNode->isCanonical()) {
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000850 Canonical = getAddrSpaceQualType(CanT, AddressSpace);
Christopher Lambebb97e92008-02-04 02:31:56 +0000851
Chris Lattnerb7d25532009-02-18 22:53:11 +0000852 // Update InsertPos, the previous call could have invalidated it.
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000853 ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +0000854 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Christopher Lambebb97e92008-02-04 02:31:56 +0000855 }
Chris Lattnerb7d25532009-02-18 22:53:11 +0000856 ExtQualType *New =
857 new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000858 ExtQualTypes.InsertNode(New, InsertPos);
Christopher Lambebb97e92008-02-04 02:31:56 +0000859 Types.push_back(New);
Chris Lattnerb7d25532009-02-18 22:53:11 +0000860 return QualType(New, CVRQuals);
Christopher Lambebb97e92008-02-04 02:31:56 +0000861}
862
Chris Lattnerb7d25532009-02-18 22:53:11 +0000863QualType ASTContext::getObjCGCQualType(QualType T,
864 QualType::GCAttrTypes GCAttr) {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000865 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +0000866 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000867 return T;
868
Fariborz Jahanian4027cd12009-06-03 17:15:17 +0000869 if (T->isPointerType()) {
870 QualType Pointee = T->getAsPointerType()->getPointeeType();
871 if (Pointee->isPointerType()) {
872 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
873 return getPointerType(ResultType);
874 }
875 }
Chris Lattnerb7d25532009-02-18 22:53:11 +0000876 // If we are composing extended qualifiers together, merge together into one
877 // ExtQualType node.
878 unsigned CVRQuals = T.getCVRQualifiers();
879 Type *TypeNode = T.getTypePtr();
880 unsigned AddressSpace = 0;
881
882 if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
883 // If this type already has an address space specified, it cannot get
884 // another one.
885 assert(EQT->getObjCGCAttr() == QualType::GCNone &&
886 "Type cannot be in multiple addr spaces!");
887 AddressSpace = EQT->getAddressSpace();
888 TypeNode = EQT->getBaseType();
889 }
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000890
891 // Check if we've already instantiated an gc qual'd type of this type.
892 llvm::FoldingSetNodeID ID;
Chris Lattnerb7d25532009-02-18 22:53:11 +0000893 ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000894 void *InsertPos = 0;
895 if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattnerb7d25532009-02-18 22:53:11 +0000896 return QualType(EXTQy, CVRQuals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000897
898 // If the base type isn't canonical, this won't be a canonical type either,
899 // so fill in the canonical type field.
Eli Friedman5a61f0e2009-02-27 23:04:43 +0000900 // FIXME: Isn't this also not canonical if the base type is a array
901 // or pointer type? I can't find any documentation for objc_gc, though...
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000902 QualType Canonical;
903 if (!T->isCanonical()) {
Chris Lattnerb7d25532009-02-18 22:53:11 +0000904 Canonical = getObjCGCQualType(CanT, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000905
Chris Lattnerb7d25532009-02-18 22:53:11 +0000906 // Update InsertPos, the previous call could have invalidated it.
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000907 ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
908 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
909 }
Chris Lattnerb7d25532009-02-18 22:53:11 +0000910 ExtQualType *New =
911 new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000912 ExtQualTypes.InsertNode(New, InsertPos);
913 Types.push_back(New);
Chris Lattnerb7d25532009-02-18 22:53:11 +0000914 return QualType(New, CVRQuals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000915}
Chris Lattnera7674d82007-07-13 22:13:22 +0000916
Reid Spencer5f016e22007-07-11 17:01:13 +0000917/// getComplexType - Return the uniqued reference to the type for a complex
918/// number with the specified element type.
919QualType ASTContext::getComplexType(QualType T) {
920 // Unique pointers, to guarantee there is only one pointer of a particular
921 // structure.
922 llvm::FoldingSetNodeID ID;
923 ComplexType::Profile(ID, T);
924
925 void *InsertPos = 0;
926 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
927 return QualType(CT, 0);
928
929 // If the pointee type isn't canonical, this won't be a canonical type either,
930 // so fill in the canonical type field.
931 QualType Canonical;
932 if (!T->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +0000933 Canonical = getComplexType(getCanonicalType(T));
Reid Spencer5f016e22007-07-11 17:01:13 +0000934
935 // Get the new insert position for the node we care about.
936 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +0000937 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +0000938 }
Steve Narofff83820b2009-01-27 22:08:43 +0000939 ComplexType *New = new (*this,8) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +0000940 Types.push_back(New);
941 ComplexTypes.InsertNode(New, InsertPos);
942 return QualType(New, 0);
943}
944
Eli Friedmanf98aba32009-02-13 02:31:07 +0000945QualType ASTContext::getFixedWidthIntType(unsigned Width, bool Signed) {
946 llvm::DenseMap<unsigned, FixedWidthIntType*> &Map = Signed ?
947 SignedFixedWidthIntTypes : UnsignedFixedWidthIntTypes;
948 FixedWidthIntType *&Entry = Map[Width];
949 if (!Entry)
950 Entry = new FixedWidthIntType(Width, Signed);
951 return QualType(Entry, 0);
952}
Reid Spencer5f016e22007-07-11 17:01:13 +0000953
954/// getPointerType - Return the uniqued reference to the type for a pointer to
955/// the specified type.
956QualType ASTContext::getPointerType(QualType T) {
957 // Unique pointers, to guarantee there is only one pointer of a particular
958 // structure.
959 llvm::FoldingSetNodeID ID;
960 PointerType::Profile(ID, T);
961
962 void *InsertPos = 0;
963 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
964 return QualType(PT, 0);
965
966 // If the pointee type isn't canonical, this won't be a canonical type either,
967 // so fill in the canonical type field.
968 QualType Canonical;
969 if (!T->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +0000970 Canonical = getPointerType(getCanonicalType(T));
Reid Spencer5f016e22007-07-11 17:01:13 +0000971
972 // Get the new insert position for the node we care about.
973 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +0000974 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +0000975 }
Steve Narofff83820b2009-01-27 22:08:43 +0000976 PointerType *New = new (*this,8) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +0000977 Types.push_back(New);
978 PointerTypes.InsertNode(New, InsertPos);
979 return QualType(New, 0);
980}
981
Steve Naroff5618bd42008-08-27 16:04:49 +0000982/// getBlockPointerType - Return the uniqued reference to the type for
983/// a pointer to the specified block.
984QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff296e8d52008-08-28 19:20:44 +0000985 assert(T->isFunctionType() && "block of function types only");
986 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +0000987 // structure.
988 llvm::FoldingSetNodeID ID;
989 BlockPointerType::Profile(ID, T);
990
991 void *InsertPos = 0;
992 if (BlockPointerType *PT =
993 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
994 return QualType(PT, 0);
995
Steve Naroff296e8d52008-08-28 19:20:44 +0000996 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +0000997 // type either so fill in the canonical type field.
998 QualType Canonical;
999 if (!T->isCanonical()) {
1000 Canonical = getBlockPointerType(getCanonicalType(T));
1001
1002 // Get the new insert position for the node we care about.
1003 BlockPointerType *NewIP =
1004 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001005 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001006 }
Steve Narofff83820b2009-01-27 22:08:43 +00001007 BlockPointerType *New = new (*this,8) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001008 Types.push_back(New);
1009 BlockPointerTypes.InsertNode(New, InsertPos);
1010 return QualType(New, 0);
1011}
1012
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001013/// getLValueReferenceType - Return the uniqued reference to the type for an
1014/// lvalue reference to the specified type.
1015QualType ASTContext::getLValueReferenceType(QualType T) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001016 // Unique pointers, to guarantee there is only one pointer of a particular
1017 // structure.
1018 llvm::FoldingSetNodeID ID;
1019 ReferenceType::Profile(ID, T);
1020
1021 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001022 if (LValueReferenceType *RT =
1023 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001024 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001025
Reid Spencer5f016e22007-07-11 17:01:13 +00001026 // If the referencee type isn't canonical, this won't be a canonical type
1027 // either, so fill in the canonical type field.
1028 QualType Canonical;
1029 if (!T->isCanonical()) {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001030 Canonical = getLValueReferenceType(getCanonicalType(T));
1031
Reid Spencer5f016e22007-07-11 17:01:13 +00001032 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001033 LValueReferenceType *NewIP =
1034 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001035 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001036 }
1037
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001038 LValueReferenceType *New = new (*this,8) LValueReferenceType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001039 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001040 LValueReferenceTypes.InsertNode(New, InsertPos);
1041 return QualType(New, 0);
1042}
1043
1044/// getRValueReferenceType - Return the uniqued reference to the type for an
1045/// rvalue reference to the specified type.
1046QualType ASTContext::getRValueReferenceType(QualType T) {
1047 // Unique pointers, to guarantee there is only one pointer of a particular
1048 // structure.
1049 llvm::FoldingSetNodeID ID;
1050 ReferenceType::Profile(ID, T);
1051
1052 void *InsertPos = 0;
1053 if (RValueReferenceType *RT =
1054 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1055 return QualType(RT, 0);
1056
1057 // If the referencee type isn't canonical, this won't be a canonical type
1058 // either, so fill in the canonical type field.
1059 QualType Canonical;
1060 if (!T->isCanonical()) {
1061 Canonical = getRValueReferenceType(getCanonicalType(T));
1062
1063 // Get the new insert position for the node we care about.
1064 RValueReferenceType *NewIP =
1065 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1066 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1067 }
1068
1069 RValueReferenceType *New = new (*this,8) RValueReferenceType(T, Canonical);
1070 Types.push_back(New);
1071 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001072 return QualType(New, 0);
1073}
1074
Sebastian Redlf30208a2009-01-24 21:16:55 +00001075/// getMemberPointerType - Return the uniqued reference to the type for a
1076/// member pointer to the specified type, in the specified class.
1077QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls)
1078{
1079 // Unique pointers, to guarantee there is only one pointer of a particular
1080 // structure.
1081 llvm::FoldingSetNodeID ID;
1082 MemberPointerType::Profile(ID, T, Cls);
1083
1084 void *InsertPos = 0;
1085 if (MemberPointerType *PT =
1086 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1087 return QualType(PT, 0);
1088
1089 // If the pointee or class type isn't canonical, this won't be a canonical
1090 // type either, so fill in the canonical type field.
1091 QualType Canonical;
1092 if (!T->isCanonical()) {
1093 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1094
1095 // Get the new insert position for the node we care about.
1096 MemberPointerType *NewIP =
1097 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1098 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1099 }
Steve Narofff83820b2009-01-27 22:08:43 +00001100 MemberPointerType *New = new (*this,8) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001101 Types.push_back(New);
1102 MemberPointerTypes.InsertNode(New, InsertPos);
1103 return QualType(New, 0);
1104}
1105
Steve Narofffb22d962007-08-30 01:06:46 +00001106/// getConstantArrayType - Return the unique reference to the type for an
1107/// array of the specified element type.
1108QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001109 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001110 ArrayType::ArraySizeModifier ASM,
1111 unsigned EltTypeQuals) {
Eli Friedman587cbdf2009-05-29 20:17:55 +00001112 assert((EltTy->isDependentType() || EltTy->isConstantSizeType()) &&
1113 "Constant array of VLAs is illegal!");
1114
Chris Lattner38aeec72009-05-13 04:12:56 +00001115 // Convert the array size into a canonical width matching the pointer size for
1116 // the target.
1117 llvm::APInt ArySize(ArySizeIn);
1118 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1119
Reid Spencer5f016e22007-07-11 17:01:13 +00001120 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001121 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001122
1123 void *InsertPos = 0;
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001124 if (ConstantArrayType *ATP =
1125 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001126 return QualType(ATP, 0);
1127
1128 // If the element type isn't canonical, this won't be a canonical type either,
1129 // so fill in the canonical type field.
1130 QualType Canonical;
1131 if (!EltTy->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001132 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroffc9406122007-08-30 18:10:14 +00001133 ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001134 // Get the new insert position for the node we care about.
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001135 ConstantArrayType *NewIP =
1136 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001137 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001138 }
1139
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001140 ConstantArrayType *New =
Steve Narofff83820b2009-01-27 22:08:43 +00001141 new(*this,8)ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001142 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001143 Types.push_back(New);
1144 return QualType(New, 0);
1145}
1146
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001147/// getVariableArrayType - Returns a non-unique reference to the type for a
1148/// variable array of the specified element type.
Steve Naroffc9406122007-08-30 18:10:14 +00001149QualType ASTContext::getVariableArrayType(QualType EltTy, Expr *NumElts,
1150 ArrayType::ArraySizeModifier ASM,
1151 unsigned EltTypeQuals) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001152 // Since we don't unique expressions, it isn't possible to unique VLA's
1153 // that have an expression provided for their size.
1154
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001155 VariableArrayType *New =
Steve Narofff83820b2009-01-27 22:08:43 +00001156 new(*this,8)VariableArrayType(EltTy,QualType(), NumElts, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001157
1158 VariableArrayTypes.push_back(New);
1159 Types.push_back(New);
1160 return QualType(New, 0);
1161}
1162
Douglas Gregor898574e2008-12-05 23:32:09 +00001163/// getDependentSizedArrayType - Returns a non-unique reference to
1164/// the type for a dependently-sized array of the specified element
1165/// type. FIXME: We will need these to be uniqued, or at least
1166/// comparable, at some point.
1167QualType ASTContext::getDependentSizedArrayType(QualType EltTy, Expr *NumElts,
1168 ArrayType::ArraySizeModifier ASM,
1169 unsigned EltTypeQuals) {
1170 assert((NumElts->isTypeDependent() || NumElts->isValueDependent()) &&
1171 "Size must be type- or value-dependent!");
1172
1173 // Since we don't unique expressions, it isn't possible to unique
1174 // dependently-sized array types.
1175
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001176 DependentSizedArrayType *New =
Steve Narofff83820b2009-01-27 22:08:43 +00001177 new (*this,8) DependentSizedArrayType(EltTy, QualType(), NumElts,
1178 ASM, EltTypeQuals);
Douglas Gregor898574e2008-12-05 23:32:09 +00001179
1180 DependentSizedArrayTypes.push_back(New);
1181 Types.push_back(New);
1182 return QualType(New, 0);
1183}
1184
Eli Friedmanc5773c42008-02-15 18:16:39 +00001185QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1186 ArrayType::ArraySizeModifier ASM,
1187 unsigned EltTypeQuals) {
1188 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001189 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001190
1191 void *InsertPos = 0;
1192 if (IncompleteArrayType *ATP =
1193 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1194 return QualType(ATP, 0);
1195
1196 // If the element type isn't canonical, this won't be a canonical type
1197 // either, so fill in the canonical type field.
1198 QualType Canonical;
1199
1200 if (!EltTy->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001201 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001202 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001203
1204 // Get the new insert position for the node we care about.
1205 IncompleteArrayType *NewIP =
1206 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001207 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001208 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001209
Steve Narofff83820b2009-01-27 22:08:43 +00001210 IncompleteArrayType *New = new (*this,8) IncompleteArrayType(EltTy, Canonical,
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001211 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001212
1213 IncompleteArrayTypes.InsertNode(New, InsertPos);
1214 Types.push_back(New);
1215 return QualType(New, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001216}
1217
Steve Naroff73322922007-07-18 18:00:27 +00001218/// getVectorType - Return the unique reference to a vector type of
1219/// the specified element type and size. VectorType must be a built-in type.
1220QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001221 BuiltinType *baseType;
1222
Chris Lattnerf52ab252008-04-06 22:59:24 +00001223 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff73322922007-07-18 18:00:27 +00001224 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Reid Spencer5f016e22007-07-11 17:01:13 +00001225
1226 // Check if we've already instantiated a vector of this type.
1227 llvm::FoldingSetNodeID ID;
Steve Naroff73322922007-07-18 18:00:27 +00001228 VectorType::Profile(ID, vecType, NumElts, Type::Vector);
Reid Spencer5f016e22007-07-11 17:01:13 +00001229 void *InsertPos = 0;
1230 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1231 return QualType(VTP, 0);
1232
1233 // If the element type isn't canonical, this won't be a canonical type either,
1234 // so fill in the canonical type field.
1235 QualType Canonical;
1236 if (!vecType->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001237 Canonical = getVectorType(getCanonicalType(vecType), NumElts);
Reid Spencer5f016e22007-07-11 17:01:13 +00001238
1239 // Get the new insert position for the node we care about.
1240 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001241 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001242 }
Steve Narofff83820b2009-01-27 22:08:43 +00001243 VectorType *New = new (*this,8) VectorType(vecType, NumElts, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001244 VectorTypes.InsertNode(New, InsertPos);
1245 Types.push_back(New);
1246 return QualType(New, 0);
1247}
1248
Nate Begeman213541a2008-04-18 23:10:10 +00001249/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001250/// the specified element type and size. VectorType must be a built-in type.
Nate Begeman213541a2008-04-18 23:10:10 +00001251QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff73322922007-07-18 18:00:27 +00001252 BuiltinType *baseType;
1253
Chris Lattnerf52ab252008-04-06 22:59:24 +00001254 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begeman213541a2008-04-18 23:10:10 +00001255 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Steve Naroff73322922007-07-18 18:00:27 +00001256
1257 // Check if we've already instantiated a vector of this type.
1258 llvm::FoldingSetNodeID ID;
Nate Begeman213541a2008-04-18 23:10:10 +00001259 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector);
Steve Naroff73322922007-07-18 18:00:27 +00001260 void *InsertPos = 0;
1261 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1262 return QualType(VTP, 0);
1263
1264 // If the element type isn't canonical, this won't be a canonical type either,
1265 // so fill in the canonical type field.
1266 QualType Canonical;
1267 if (!vecType->isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001268 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Steve Naroff73322922007-07-18 18:00:27 +00001269
1270 // Get the new insert position for the node we care about.
1271 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001272 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001273 }
Steve Narofff83820b2009-01-27 22:08:43 +00001274 ExtVectorType *New = new (*this,8) ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001275 VectorTypes.InsertNode(New, InsertPos);
1276 Types.push_back(New);
1277 return QualType(New, 0);
1278}
1279
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001280QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
1281 Expr *SizeExpr,
1282 SourceLocation AttrLoc) {
1283 DependentSizedExtVectorType *New =
1284 new (*this,8) DependentSizedExtVectorType(vecType, QualType(),
1285 SizeExpr, AttrLoc);
1286
1287 DependentSizedExtVectorTypes.push_back(New);
1288 Types.push_back(New);
1289 return QualType(New, 0);
1290}
1291
Douglas Gregor72564e72009-02-26 23:50:07 +00001292/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001293///
Douglas Gregor72564e72009-02-26 23:50:07 +00001294QualType ASTContext::getFunctionNoProtoType(QualType ResultTy) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001295 // Unique functions, to guarantee there is only one function of a particular
1296 // structure.
1297 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001298 FunctionNoProtoType::Profile(ID, ResultTy);
Reid Spencer5f016e22007-07-11 17:01:13 +00001299
1300 void *InsertPos = 0;
Douglas Gregor72564e72009-02-26 23:50:07 +00001301 if (FunctionNoProtoType *FT =
1302 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001303 return QualType(FT, 0);
1304
1305 QualType Canonical;
1306 if (!ResultTy->isCanonical()) {
Douglas Gregor72564e72009-02-26 23:50:07 +00001307 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy));
Reid Spencer5f016e22007-07-11 17:01:13 +00001308
1309 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001310 FunctionNoProtoType *NewIP =
1311 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001312 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001313 }
1314
Douglas Gregor72564e72009-02-26 23:50:07 +00001315 FunctionNoProtoType *New =new(*this,8)FunctionNoProtoType(ResultTy,Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001316 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001317 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001318 return QualType(New, 0);
1319}
1320
1321/// getFunctionType - Return a normal function type with a typed argument
1322/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner61710852008-10-05 17:34:18 +00001323QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001324 unsigned NumArgs, bool isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001325 unsigned TypeQuals, bool hasExceptionSpec,
1326 bool hasAnyExceptionSpec, unsigned NumExs,
1327 const QualType *ExArray) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001328 // Unique functions, to guarantee there is only one function of a particular
1329 // structure.
1330 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001331 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001332 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
1333 NumExs, ExArray);
Reid Spencer5f016e22007-07-11 17:01:13 +00001334
1335 void *InsertPos = 0;
Douglas Gregor72564e72009-02-26 23:50:07 +00001336 if (FunctionProtoType *FTP =
1337 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001338 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001339
1340 // Determine whether the type being created is already canonical or not.
Reid Spencer5f016e22007-07-11 17:01:13 +00001341 bool isCanonical = ResultTy->isCanonical();
Sebastian Redl465226e2009-05-27 22:11:52 +00001342 if (hasExceptionSpec)
1343 isCanonical = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001344 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
1345 if (!ArgArray[i]->isCanonical())
1346 isCanonical = false;
1347
1348 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001349 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001350 QualType Canonical;
1351 if (!isCanonical) {
1352 llvm::SmallVector<QualType, 16> CanonicalArgs;
1353 CanonicalArgs.reserve(NumArgs);
1354 for (unsigned i = 0; i != NumArgs; ++i)
Chris Lattnerf52ab252008-04-06 22:59:24 +00001355 CanonicalArgs.push_back(getCanonicalType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001356
Chris Lattnerf52ab252008-04-06 22:59:24 +00001357 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001358 CanonicalArgs.data(), NumArgs,
Sebastian Redlbfa2fcb2009-05-06 23:27:55 +00001359 isVariadic, TypeQuals);
Sebastian Redl465226e2009-05-27 22:11:52 +00001360
Reid Spencer5f016e22007-07-11 17:01:13 +00001361 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001362 FunctionProtoType *NewIP =
1363 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001364 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001365 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001366
Douglas Gregor72564e72009-02-26 23:50:07 +00001367 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001368 // for two variable size arrays (for parameter and exception types) at the
1369 // end of them.
Douglas Gregor72564e72009-02-26 23:50:07 +00001370 FunctionProtoType *FTP =
Sebastian Redl465226e2009-05-27 22:11:52 +00001371 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1372 NumArgs*sizeof(QualType) +
1373 NumExs*sizeof(QualType), 8);
Douglas Gregor72564e72009-02-26 23:50:07 +00001374 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001375 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
1376 ExArray, NumExs, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001377 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001378 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001379 return QualType(FTP, 0);
1380}
1381
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001382/// getTypeDeclType - Return the unique reference to the type for the
1383/// specified type declaration.
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001384QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001385 assert(Decl && "Passed null for Decl param");
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001386 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1387
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001388 if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001389 return getTypedefType(Typedef);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001390 else if (isa<TemplateTypeParmDecl>(Decl)) {
1391 assert(false && "Template type parameter types are always available.");
1392 } else if (ObjCInterfaceDecl *ObjCInterface = dyn_cast<ObjCInterfaceDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001393 return getObjCInterfaceType(ObjCInterface);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001394
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001395 if (RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001396 if (PrevDecl)
1397 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001398 else
1399 Decl->TypeForDecl = new (*this,8) RecordType(Record);
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001400 }
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001401 else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
1402 if (PrevDecl)
1403 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001404 else
1405 Decl->TypeForDecl = new (*this,8) EnumType(Enum);
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001406 }
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001407 else
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001408 assert(false && "TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001409
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001410 if (!PrevDecl) Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001411 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001412}
1413
Reid Spencer5f016e22007-07-11 17:01:13 +00001414/// getTypedefType - Return the unique reference to the type for the
1415/// specified typename decl.
1416QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
1417 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1418
Chris Lattnerf52ab252008-04-06 22:59:24 +00001419 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
Douglas Gregor72564e72009-02-26 23:50:07 +00001420 Decl->TypeForDecl = new(*this,8) TypedefType(Type::Typedef, Decl, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001421 Types.push_back(Decl->TypeForDecl);
1422 return QualType(Decl->TypeForDecl, 0);
1423}
1424
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001425/// getObjCInterfaceType - Return the unique reference to the type for the
Steve Naroff3536b442007-09-06 21:24:23 +00001426/// specified ObjC interface decl.
Daniel Dunbar3b3a4582009-04-22 04:34:53 +00001427QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) {
Steve Naroff3536b442007-09-06 21:24:23 +00001428 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1429
Daniel Dunbar3b3a4582009-04-22 04:34:53 +00001430 ObjCInterfaceDecl *OID = const_cast<ObjCInterfaceDecl*>(Decl);
1431 Decl->TypeForDecl = new(*this,8) ObjCInterfaceType(Type::ObjCInterface, OID);
Steve Naroff3536b442007-09-06 21:24:23 +00001432 Types.push_back(Decl->TypeForDecl);
1433 return QualType(Decl->TypeForDecl, 0);
1434}
1435
Douglas Gregorfab9d672009-02-05 23:33:38 +00001436/// \brief Retrieve the template type parameter type for a template
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001437/// parameter or parameter pack with the given depth, index, and (optionally)
1438/// name.
Douglas Gregorfab9d672009-02-05 23:33:38 +00001439QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001440 bool ParameterPack,
Douglas Gregorfab9d672009-02-05 23:33:38 +00001441 IdentifierInfo *Name) {
1442 llvm::FoldingSetNodeID ID;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001443 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001444 void *InsertPos = 0;
1445 TemplateTypeParmType *TypeParm
1446 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1447
1448 if (TypeParm)
1449 return QualType(TypeParm, 0);
1450
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001451 if (Name) {
1452 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
1453 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, ParameterPack,
1454 Name, Canon);
1455 } else
1456 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001457
1458 Types.push_back(TypeParm);
1459 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1460
1461 return QualType(TypeParm, 0);
1462}
1463
Douglas Gregor55f6b142009-02-09 18:46:07 +00001464QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00001465ASTContext::getTemplateSpecializationType(TemplateName Template,
1466 const TemplateArgument *Args,
1467 unsigned NumArgs,
1468 QualType Canon) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001469 if (!Canon.isNull())
1470 Canon = getCanonicalType(Canon);
Douglas Gregorfc705b82009-02-26 22:19:44 +00001471
Douglas Gregor55f6b142009-02-09 18:46:07 +00001472 llvm::FoldingSetNodeID ID;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001473 TemplateSpecializationType::Profile(ID, Template, Args, NumArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001474
Douglas Gregor55f6b142009-02-09 18:46:07 +00001475 void *InsertPos = 0;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001476 TemplateSpecializationType *Spec
1477 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001478
1479 if (Spec)
1480 return QualType(Spec, 0);
1481
Douglas Gregor7532dc62009-03-30 22:58:21 +00001482 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00001483 sizeof(TemplateArgument) * NumArgs),
1484 8);
Douglas Gregor7532dc62009-03-30 22:58:21 +00001485 Spec = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, Canon);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001486 Types.push_back(Spec);
Douglas Gregor7532dc62009-03-30 22:58:21 +00001487 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001488
1489 return QualType(Spec, 0);
1490}
1491
Douglas Gregore4e5b052009-03-19 00:18:19 +00001492QualType
Douglas Gregorab452ba2009-03-26 23:50:42 +00001493ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
Douglas Gregore4e5b052009-03-19 00:18:19 +00001494 QualType NamedType) {
1495 llvm::FoldingSetNodeID ID;
Douglas Gregorab452ba2009-03-26 23:50:42 +00001496 QualifiedNameType::Profile(ID, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001497
1498 void *InsertPos = 0;
1499 QualifiedNameType *T
1500 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
1501 if (T)
1502 return QualType(T, 0);
1503
Douglas Gregorab452ba2009-03-26 23:50:42 +00001504 T = new (*this) QualifiedNameType(NNS, NamedType,
1505 getCanonicalType(NamedType));
Douglas Gregore4e5b052009-03-19 00:18:19 +00001506 Types.push_back(T);
1507 QualifiedNameTypes.InsertNode(T, InsertPos);
1508 return QualType(T, 0);
1509}
1510
Douglas Gregord57959a2009-03-27 23:10:48 +00001511QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1512 const IdentifierInfo *Name,
1513 QualType Canon) {
1514 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1515
1516 if (Canon.isNull()) {
1517 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1518 if (CanonNNS != NNS)
1519 Canon = getTypenameType(CanonNNS, Name);
1520 }
1521
1522 llvm::FoldingSetNodeID ID;
1523 TypenameType::Profile(ID, NNS, Name);
1524
1525 void *InsertPos = 0;
1526 TypenameType *T
1527 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1528 if (T)
1529 return QualType(T, 0);
1530
1531 T = new (*this) TypenameType(NNS, Name, Canon);
1532 Types.push_back(T);
1533 TypenameTypes.InsertNode(T, InsertPos);
1534 return QualType(T, 0);
1535}
1536
Douglas Gregor17343172009-04-01 00:28:59 +00001537QualType
1538ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1539 const TemplateSpecializationType *TemplateId,
1540 QualType Canon) {
1541 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1542
1543 if (Canon.isNull()) {
1544 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1545 QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
1546 if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
1547 const TemplateSpecializationType *CanonTemplateId
1548 = CanonType->getAsTemplateSpecializationType();
1549 assert(CanonTemplateId &&
1550 "Canonical type must also be a template specialization type");
1551 Canon = getTypenameType(CanonNNS, CanonTemplateId);
1552 }
1553 }
1554
1555 llvm::FoldingSetNodeID ID;
1556 TypenameType::Profile(ID, NNS, TemplateId);
1557
1558 void *InsertPos = 0;
1559 TypenameType *T
1560 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1561 if (T)
1562 return QualType(T, 0);
1563
1564 T = new (*this) TypenameType(NNS, TemplateId, Canon);
1565 Types.push_back(T);
1566 TypenameTypes.InsertNode(T, InsertPos);
1567 return QualType(T, 0);
1568}
1569
Chris Lattner88cb27a2008-04-07 04:56:42 +00001570/// CmpProtocolNames - Comparison predicate for sorting protocols
1571/// alphabetically.
1572static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
1573 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001574 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00001575}
1576
1577static void SortAndUniqueProtocols(ObjCProtocolDecl **&Protocols,
1578 unsigned &NumProtocols) {
1579 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
1580
1581 // Sort protocols, keyed by name.
1582 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
1583
1584 // Remove duplicates.
1585 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
1586 NumProtocols = ProtocolsEnd-Protocols;
1587}
1588
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001589/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
1590/// the given interface decl and the conforming protocol list.
1591QualType ASTContext::getObjCObjectPointerType(ObjCInterfaceDecl *Decl,
1592 ObjCProtocolDecl **Protocols,
1593 unsigned NumProtocols) {
1594 // Sort the protocol list alphabetically to canonicalize it.
1595 if (NumProtocols)
1596 SortAndUniqueProtocols(Protocols, NumProtocols);
1597
1598 llvm::FoldingSetNodeID ID;
1599 ObjCObjectPointerType::Profile(ID, Decl, Protocols, NumProtocols);
1600
1601 void *InsertPos = 0;
1602 if (ObjCObjectPointerType *QT =
1603 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1604 return QualType(QT, 0);
1605
1606 // No Match;
1607 ObjCObjectPointerType *QType =
1608 new (*this,8) ObjCObjectPointerType(Decl, Protocols, NumProtocols);
1609
1610 Types.push_back(QType);
1611 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
1612 return QualType(QType, 0);
1613}
Chris Lattner88cb27a2008-04-07 04:56:42 +00001614
Chris Lattner065f0d72008-04-07 04:44:08 +00001615/// getObjCQualifiedInterfaceType - Return a ObjCQualifiedInterfaceType type for
1616/// the given interface decl and the conforming protocol list.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001617QualType ASTContext::getObjCQualifiedInterfaceType(ObjCInterfaceDecl *Decl,
1618 ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
Chris Lattner88cb27a2008-04-07 04:56:42 +00001619 // Sort the protocol list alphabetically to canonicalize it.
1620 SortAndUniqueProtocols(Protocols, NumProtocols);
1621
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001622 llvm::FoldingSetNodeID ID;
Chris Lattnerb0489812008-04-07 06:38:24 +00001623 ObjCQualifiedInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001624
1625 void *InsertPos = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001626 if (ObjCQualifiedInterfaceType *QT =
1627 ObjCQualifiedInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001628 return QualType(QT, 0);
1629
1630 // No Match;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001631 ObjCQualifiedInterfaceType *QType =
Steve Narofff83820b2009-01-27 22:08:43 +00001632 new (*this,8) ObjCQualifiedInterfaceType(Decl, Protocols, NumProtocols);
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001633
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001634 Types.push_back(QType);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001635 ObjCQualifiedInterfaceTypes.InsertNode(QType, InsertPos);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001636 return QualType(QType, 0);
1637}
1638
Chris Lattner88cb27a2008-04-07 04:56:42 +00001639/// getObjCQualifiedIdType - Return an ObjCQualifiedIdType for the 'id' decl
1640/// and the conforming protocol list.
Chris Lattner62f5f7f2008-07-26 00:46:50 +00001641QualType ASTContext::getObjCQualifiedIdType(ObjCProtocolDecl **Protocols,
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001642 unsigned NumProtocols) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001643 return getObjCObjectPointerType(0, Protocols, NumProtocols);
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001644}
1645
Douglas Gregor72564e72009-02-26 23:50:07 +00001646/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
1647/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00001648/// multiple declarations that refer to "typeof(x)" all contain different
1649/// DeclRefExpr's. This doesn't effect the type checker, since it operates
1650/// on canonical type's (which are always unique).
Douglas Gregor72564e72009-02-26 23:50:07 +00001651QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001652 QualType Canonical = getCanonicalType(tofExpr->getType());
Douglas Gregor72564e72009-02-26 23:50:07 +00001653 TypeOfExprType *toe = new (*this,8) TypeOfExprType(tofExpr, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00001654 Types.push_back(toe);
1655 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00001656}
1657
Steve Naroff9752f252007-08-01 18:02:17 +00001658/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
1659/// TypeOfType AST's. The only motivation to unique these nodes would be
1660/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
1661/// an issue. This doesn't effect the type checker, since it operates
1662/// on canonical type's (which are always unique).
Steve Naroffd1861fd2007-07-31 12:34:36 +00001663QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001664 QualType Canonical = getCanonicalType(tofType);
Steve Narofff83820b2009-01-27 22:08:43 +00001665 TypeOfType *tot = new (*this,8) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00001666 Types.push_back(tot);
1667 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00001668}
1669
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00001670/// getDecltypeForExpr - Given an expr, will return the decltype for that
1671/// expression, according to the rules in C++0x [dcl.type.simple]p4
1672static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00001673 if (e->isTypeDependent())
1674 return Context.DependentTy;
1675
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00001676 // If e is an id expression or a class member access, decltype(e) is defined
1677 // as the type of the entity named by e.
1678 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
1679 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
1680 return VD->getType();
1681 }
1682 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
1683 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
1684 return FD->getType();
1685 }
1686 // If e is a function call or an invocation of an overloaded operator,
1687 // (parentheses around e are ignored), decltype(e) is defined as the
1688 // return type of that function.
1689 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
1690 return CE->getCallReturnType();
1691
1692 QualType T = e->getType();
1693
1694 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
1695 // defined as T&, otherwise decltype(e) is defined as T.
1696 if (e->isLvalue(Context) == Expr::LV_Valid)
1697 T = Context.getLValueReferenceType(T);
1698
1699 return T;
1700}
1701
Anders Carlsson395b4752009-06-24 19:06:50 +00001702/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
1703/// DecltypeType AST's. The only motivation to unique these nodes would be
1704/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
1705/// an issue. This doesn't effect the type checker, since it operates
1706/// on canonical type's (which are always unique).
1707QualType ASTContext::getDecltypeType(Expr *e) {
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00001708 QualType T = getDecltypeForExpr(e, *this);
1709 DecltypeType *dt = new (*this, 8) DecltypeType(e, getCanonicalType(T));
Anders Carlsson395b4752009-06-24 19:06:50 +00001710 Types.push_back(dt);
1711 return QualType(dt, 0);
1712}
1713
Reid Spencer5f016e22007-07-11 17:01:13 +00001714/// getTagDeclType - Return the unique reference to the type for the
1715/// specified TagDecl (struct/union/class/enum) decl.
1716QualType ASTContext::getTagDeclType(TagDecl *Decl) {
Ted Kremenekd778f882007-11-26 21:16:01 +00001717 assert (Decl);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001718 return getTypeDeclType(Decl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001719}
1720
1721/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
1722/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
1723/// needs to agree with the definition in <stddef.h>.
1724QualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00001725 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00001726}
1727
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00001728/// getSignedWCharType - Return the type of "signed wchar_t".
1729/// Used when in C++, as a GCC extension.
1730QualType ASTContext::getSignedWCharType() const {
1731 // FIXME: derive from "Target" ?
1732 return WCharTy;
1733}
1734
1735/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
1736/// Used when in C++, as a GCC extension.
1737QualType ASTContext::getUnsignedWCharType() const {
1738 // FIXME: derive from "Target" ?
1739 return UnsignedIntTy;
1740}
1741
Chris Lattner8b9023b2007-07-13 03:05:23 +00001742/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
1743/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
1744QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00001745 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00001746}
1747
Chris Lattnere6327742008-04-02 05:18:44 +00001748//===----------------------------------------------------------------------===//
1749// Type Operators
1750//===----------------------------------------------------------------------===//
1751
Chris Lattner77c96472008-04-06 22:41:35 +00001752/// getCanonicalType - Return the canonical (structural) type corresponding to
1753/// the specified potentially non-canonical type. The non-canonical version
1754/// of a type may have many "decorated" versions of types. Decorators can
1755/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
1756/// to be free of any of these, allowing two canonical types to be compared
1757/// for exact equality with a simple pointer comparison.
1758QualType ASTContext::getCanonicalType(QualType T) {
1759 QualType CanType = T.getTypePtr()->getCanonicalTypeInternal();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001760
1761 // If the result has type qualifiers, make sure to canonicalize them as well.
1762 unsigned TypeQuals = T.getCVRQualifiers() | CanType.getCVRQualifiers();
1763 if (TypeQuals == 0) return CanType;
1764
1765 // If the type qualifiers are on an array type, get the canonical type of the
1766 // array with the qualifiers applied to the element type.
1767 ArrayType *AT = dyn_cast<ArrayType>(CanType);
1768 if (!AT)
1769 return CanType.getQualifiedType(TypeQuals);
1770
1771 // Get the canonical version of the element with the extra qualifiers on it.
1772 // This can recursively sink qualifiers through multiple levels of arrays.
1773 QualType NewEltTy=AT->getElementType().getWithAdditionalQualifiers(TypeQuals);
1774 NewEltTy = getCanonicalType(NewEltTy);
1775
1776 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
1777 return getConstantArrayType(NewEltTy, CAT->getSize(),CAT->getSizeModifier(),
1778 CAT->getIndexTypeQualifier());
1779 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
1780 return getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
1781 IAT->getIndexTypeQualifier());
1782
Douglas Gregor898574e2008-12-05 23:32:09 +00001783 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
1784 return getDependentSizedArrayType(NewEltTy, DSAT->getSizeExpr(),
1785 DSAT->getSizeModifier(),
1786 DSAT->getIndexTypeQualifier());
1787
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001788 VariableArrayType *VAT = cast<VariableArrayType>(AT);
1789 return getVariableArrayType(NewEltTy, VAT->getSizeExpr(),
1790 VAT->getSizeModifier(),
1791 VAT->getIndexTypeQualifier());
1792}
1793
Douglas Gregor7da97d02009-05-10 22:57:19 +00001794Decl *ASTContext::getCanonicalDecl(Decl *D) {
Douglas Gregorc4ccf012009-05-10 22:59:12 +00001795 if (!D)
1796 return 0;
1797
Douglas Gregor7da97d02009-05-10 22:57:19 +00001798 if (TagDecl *Tag = dyn_cast<TagDecl>(D)) {
1799 QualType T = getTagDeclType(Tag);
1800 return cast<TagDecl>(cast<TagType>(T.getTypePtr()->CanonicalType)
1801 ->getDecl());
1802 }
1803
1804 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(D)) {
1805 while (Template->getPreviousDeclaration())
1806 Template = Template->getPreviousDeclaration();
1807 return Template;
1808 }
1809
1810 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
1811 while (Function->getPreviousDeclaration())
1812 Function = Function->getPreviousDeclaration();
1813 return const_cast<FunctionDecl *>(Function);
1814 }
1815
1816 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
1817 while (Var->getPreviousDeclaration())
1818 Var = Var->getPreviousDeclaration();
1819 return const_cast<VarDecl *>(Var);
1820 }
1821
1822 return D;
1823}
1824
Douglas Gregor25a3ef72009-05-07 06:41:52 +00001825TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
1826 // If this template name refers to a template, the canonical
1827 // template name merely stores the template itself.
1828 if (TemplateDecl *Template = Name.getAsTemplateDecl())
Douglas Gregor7da97d02009-05-10 22:57:19 +00001829 return TemplateName(cast<TemplateDecl>(getCanonicalDecl(Template)));
Douglas Gregor25a3ef72009-05-07 06:41:52 +00001830
1831 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
1832 assert(DTN && "Non-dependent template names must refer to template decls.");
1833 return DTN->CanonicalTemplateName;
1834}
1835
Douglas Gregord57959a2009-03-27 23:10:48 +00001836NestedNameSpecifier *
1837ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
1838 if (!NNS)
1839 return 0;
1840
1841 switch (NNS->getKind()) {
1842 case NestedNameSpecifier::Identifier:
1843 // Canonicalize the prefix but keep the identifier the same.
1844 return NestedNameSpecifier::Create(*this,
1845 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
1846 NNS->getAsIdentifier());
1847
1848 case NestedNameSpecifier::Namespace:
1849 // A namespace is canonical; build a nested-name-specifier with
1850 // this namespace and no prefix.
1851 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
1852
1853 case NestedNameSpecifier::TypeSpec:
1854 case NestedNameSpecifier::TypeSpecWithTemplate: {
1855 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
1856 NestedNameSpecifier *Prefix = 0;
1857
1858 // FIXME: This isn't the right check!
1859 if (T->isDependentType())
1860 Prefix = getCanonicalNestedNameSpecifier(NNS->getPrefix());
1861
1862 return NestedNameSpecifier::Create(*this, Prefix,
1863 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
1864 T.getTypePtr());
1865 }
1866
1867 case NestedNameSpecifier::Global:
1868 // The global specifier is canonical and unique.
1869 return NNS;
1870 }
1871
1872 // Required to silence a GCC warning
1873 return 0;
1874}
1875
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001876
1877const ArrayType *ASTContext::getAsArrayType(QualType T) {
1878 // Handle the non-qualified case efficiently.
1879 if (T.getCVRQualifiers() == 0) {
1880 // Handle the common positive case fast.
1881 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
1882 return AT;
1883 }
1884
1885 // Handle the common negative case fast, ignoring CVR qualifiers.
1886 QualType CType = T->getCanonicalTypeInternal();
1887
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001888 // Make sure to look through type qualifiers (like ExtQuals) for the negative
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001889 // test.
1890 if (!isa<ArrayType>(CType) &&
1891 !isa<ArrayType>(CType.getUnqualifiedType()))
1892 return 0;
1893
1894 // Apply any CVR qualifiers from the array type to the element type. This
1895 // implements C99 6.7.3p8: "If the specification of an array type includes
1896 // any type qualifiers, the element type is so qualified, not the array type."
1897
1898 // If we get here, we either have type qualifiers on the type, or we have
1899 // sugar such as a typedef in the way. If we have type qualifiers on the type
1900 // we must propagate them down into the elemeng type.
1901 unsigned CVRQuals = T.getCVRQualifiers();
1902 unsigned AddrSpace = 0;
1903 Type *Ty = T.getTypePtr();
1904
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001905 // Rip through ExtQualType's and typedefs to get to a concrete type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001906 while (1) {
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001907 if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(Ty)) {
1908 AddrSpace = EXTQT->getAddressSpace();
1909 Ty = EXTQT->getBaseType();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001910 } else {
1911 T = Ty->getDesugaredType();
1912 if (T.getTypePtr() == Ty && T.getCVRQualifiers() == 0)
1913 break;
1914 CVRQuals |= T.getCVRQualifiers();
1915 Ty = T.getTypePtr();
1916 }
1917 }
1918
1919 // If we have a simple case, just return now.
1920 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
1921 if (ATy == 0 || (AddrSpace == 0 && CVRQuals == 0))
1922 return ATy;
1923
1924 // Otherwise, we have an array and we have qualifiers on it. Push the
1925 // qualifiers into the array element type and return a new array type.
1926 // Get the canonical version of the element with the extra qualifiers on it.
1927 // This can recursively sink qualifiers through multiple levels of arrays.
1928 QualType NewEltTy = ATy->getElementType();
1929 if (AddrSpace)
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001930 NewEltTy = getAddrSpaceQualType(NewEltTy, AddrSpace);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001931 NewEltTy = NewEltTy.getWithAdditionalQualifiers(CVRQuals);
1932
1933 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
1934 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
1935 CAT->getSizeModifier(),
1936 CAT->getIndexTypeQualifier()));
1937 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
1938 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
1939 IAT->getSizeModifier(),
1940 IAT->getIndexTypeQualifier()));
Douglas Gregor898574e2008-12-05 23:32:09 +00001941
Douglas Gregor898574e2008-12-05 23:32:09 +00001942 if (const DependentSizedArrayType *DSAT
1943 = dyn_cast<DependentSizedArrayType>(ATy))
1944 return cast<ArrayType>(
1945 getDependentSizedArrayType(NewEltTy,
1946 DSAT->getSizeExpr(),
1947 DSAT->getSizeModifier(),
1948 DSAT->getIndexTypeQualifier()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001949
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001950 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
1951 return cast<ArrayType>(getVariableArrayType(NewEltTy, VAT->getSizeExpr(),
1952 VAT->getSizeModifier(),
1953 VAT->getIndexTypeQualifier()));
Chris Lattner77c96472008-04-06 22:41:35 +00001954}
1955
1956
Chris Lattnere6327742008-04-02 05:18:44 +00001957/// getArrayDecayedType - Return the properly qualified result of decaying the
1958/// specified array type to a pointer. This operation is non-trivial when
1959/// handling typedefs etc. The canonical type of "T" must be an array type,
1960/// this returns a pointer to a properly qualified element of the array.
1961///
1962/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
1963QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001964 // Get the element type with 'getAsArrayType' so that we don't lose any
1965 // typedefs in the element type of the array. This also handles propagation
1966 // of type qualifiers from the array type into the element type if present
1967 // (C99 6.7.3p8).
1968 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
1969 assert(PrettyArrayType && "Not an array type!");
Chris Lattnere6327742008-04-02 05:18:44 +00001970
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001971 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00001972
1973 // int x[restrict 4] -> int *restrict
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001974 return PtrTy.getQualifiedType(PrettyArrayType->getIndexTypeQualifier());
Chris Lattnere6327742008-04-02 05:18:44 +00001975}
1976
Daniel Dunbard786f6a2009-01-05 22:14:37 +00001977QualType ASTContext::getBaseElementType(const VariableArrayType *VAT) {
Anders Carlsson6183a992008-12-21 03:44:36 +00001978 QualType ElemTy = VAT->getElementType();
1979
1980 if (const VariableArrayType *VAT = getAsVariableArrayType(ElemTy))
1981 return getBaseElementType(VAT);
1982
1983 return ElemTy;
1984}
1985
Reid Spencer5f016e22007-07-11 17:01:13 +00001986/// getFloatingRank - Return a relative rank for floating point types.
1987/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00001988static FloatingRank getFloatingRank(QualType T) {
Christopher Lambebb97e92008-02-04 02:31:56 +00001989 if (const ComplexType *CT = T->getAsComplexType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001990 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00001991
Daniel Dunbard786f6a2009-01-05 22:14:37 +00001992 assert(T->getAsBuiltinType() && "getFloatingRank(): not a floating type");
Christopher Lambebb97e92008-02-04 02:31:56 +00001993 switch (T->getAsBuiltinType()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00001994 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00001995 case BuiltinType::Float: return FloatRank;
1996 case BuiltinType::Double: return DoubleRank;
1997 case BuiltinType::LongDouble: return LongDoubleRank;
1998 }
1999}
2000
Steve Naroff716c7302007-08-27 01:41:48 +00002001/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2002/// point or a complex type (based on typeDomain/typeSize).
2003/// 'typeDomain' is a real floating point or complex type.
2004/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00002005QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2006 QualType Domain) const {
2007 FloatingRank EltRank = getFloatingRank(Size);
2008 if (Domain->isComplexType()) {
2009 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00002010 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00002011 case FloatRank: return FloatComplexTy;
2012 case DoubleRank: return DoubleComplexTy;
2013 case LongDoubleRank: return LongDoubleComplexTy;
2014 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002015 }
Chris Lattner1361b112008-04-06 23:58:54 +00002016
2017 assert(Domain->isRealFloatingType() && "Unknown domain!");
2018 switch (EltRank) {
2019 default: assert(0 && "getFloatingRank(): illegal value for rank");
2020 case FloatRank: return FloatTy;
2021 case DoubleRank: return DoubleTy;
2022 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00002023 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002024}
2025
Chris Lattner7cfeb082008-04-06 23:55:33 +00002026/// getFloatingTypeOrder - Compare the rank of the two specified floating
2027/// point types, ignoring the domain of the type (i.e. 'double' ==
2028/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
2029/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00002030int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2031 FloatingRank LHSR = getFloatingRank(LHS);
2032 FloatingRank RHSR = getFloatingRank(RHS);
2033
2034 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002035 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00002036 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002037 return 1;
2038 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002039}
2040
Chris Lattnerf52ab252008-04-06 22:59:24 +00002041/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2042/// routine will assert if passed a built-in type that isn't an integer or enum,
2043/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00002044unsigned ASTContext::getIntegerRank(Type *T) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002045 assert(T->isCanonical() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00002046 if (EnumType* ET = dyn_cast<EnumType>(T))
2047 T = ET->getDecl()->getIntegerType().getTypePtr();
2048
2049 // There are two things which impact the integer rank: the width, and
2050 // the ordering of builtins. The builtin ordering is encoded in the
2051 // bottom three bits; the width is encoded in the bits above that.
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002052 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T))
Eli Friedmanf98aba32009-02-13 02:31:07 +00002053 return FWIT->getWidth() << 3;
Eli Friedmanf98aba32009-02-13 02:31:07 +00002054
Chris Lattnerf52ab252008-04-06 22:59:24 +00002055 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00002056 default: assert(0 && "getIntegerRank(): not a built-in integer");
2057 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002058 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002059 case BuiltinType::Char_S:
2060 case BuiltinType::Char_U:
2061 case BuiltinType::SChar:
2062 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002063 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002064 case BuiltinType::Short:
2065 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002066 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002067 case BuiltinType::Int:
2068 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002069 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002070 case BuiltinType::Long:
2071 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002072 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002073 case BuiltinType::LongLong:
2074 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002075 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00002076 case BuiltinType::Int128:
2077 case BuiltinType::UInt128:
2078 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00002079 }
2080}
2081
Chris Lattner7cfeb082008-04-06 23:55:33 +00002082/// getIntegerTypeOrder - Returns the highest ranked integer type:
2083/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
2084/// LHS < RHS, return -1.
2085int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002086 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2087 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00002088 if (LHSC == RHSC) return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00002089
Chris Lattnerf52ab252008-04-06 22:59:24 +00002090 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2091 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002092
Chris Lattner7cfeb082008-04-06 23:55:33 +00002093 unsigned LHSRank = getIntegerRank(LHSC);
2094 unsigned RHSRank = getIntegerRank(RHSC);
Reid Spencer5f016e22007-07-11 17:01:13 +00002095
Chris Lattner7cfeb082008-04-06 23:55:33 +00002096 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2097 if (LHSRank == RHSRank) return 0;
2098 return LHSRank > RHSRank ? 1 : -1;
2099 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002100
Chris Lattner7cfeb082008-04-06 23:55:33 +00002101 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2102 if (LHSUnsigned) {
2103 // If the unsigned [LHS] type is larger, return it.
2104 if (LHSRank >= RHSRank)
2105 return 1;
2106
2107 // If the signed type can represent all values of the unsigned type, it
2108 // wins. Because we are dealing with 2's complement and types that are
2109 // powers of two larger than each other, this is always safe.
2110 return -1;
2111 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00002112
Chris Lattner7cfeb082008-04-06 23:55:33 +00002113 // If the unsigned [RHS] type is larger, return it.
2114 if (RHSRank >= LHSRank)
2115 return -1;
2116
2117 // If the signed type can represent all values of the unsigned type, it
2118 // wins. Because we are dealing with 2's complement and types that are
2119 // powers of two larger than each other, this is always safe.
2120 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002121}
Anders Carlsson71993dd2007-08-17 05:31:46 +00002122
2123// getCFConstantStringType - Return the type used for constant CFStrings.
2124QualType ASTContext::getCFConstantStringType() {
2125 if (!CFConstantStringTypeDecl) {
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002126 CFConstantStringTypeDecl =
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002127 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002128 &Idents.get("NSConstantString"));
Anders Carlssonf06273f2007-11-19 00:25:30 +00002129 QualType FieldTypes[4];
Anders Carlsson71993dd2007-08-17 05:31:46 +00002130
2131 // const int *isa;
2132 FieldTypes[0] = getPointerType(IntTy.getQualifiedType(QualType::Const));
Anders Carlssonf06273f2007-11-19 00:25:30 +00002133 // int flags;
2134 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00002135 // const char *str;
Anders Carlssonf06273f2007-11-19 00:25:30 +00002136 FieldTypes[2] = getPointerType(CharTy.getQualifiedType(QualType::Const));
Anders Carlsson71993dd2007-08-17 05:31:46 +00002137 // long length;
Anders Carlssonf06273f2007-11-19 00:25:30 +00002138 FieldTypes[3] = LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002139
Anders Carlsson71993dd2007-08-17 05:31:46 +00002140 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002141 for (unsigned i = 0; i < 4; ++i) {
2142 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
2143 SourceLocation(), 0,
2144 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002145 /*Mutable=*/false);
Douglas Gregor6ab35242009-04-09 21:40:53 +00002146 CFConstantStringTypeDecl->addDecl(*this, Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002147 }
2148
2149 CFConstantStringTypeDecl->completeDefinition(*this);
Anders Carlsson71993dd2007-08-17 05:31:46 +00002150 }
2151
2152 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00002153}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002154
Douglas Gregor319ac892009-04-23 22:29:11 +00002155void ASTContext::setCFConstantStringType(QualType T) {
2156 const RecordType *Rec = T->getAsRecordType();
2157 assert(Rec && "Invalid CFConstantStringType");
2158 CFConstantStringTypeDecl = Rec->getDecl();
2159}
2160
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002161QualType ASTContext::getObjCFastEnumerationStateType()
2162{
2163 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00002164 ObjCFastEnumerationStateTypeDecl =
2165 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2166 &Idents.get("__objcFastEnumerationState"));
2167
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002168 QualType FieldTypes[] = {
2169 UnsignedLongTy,
2170 getPointerType(ObjCIdType),
2171 getPointerType(UnsignedLongTy),
2172 getConstantArrayType(UnsignedLongTy,
2173 llvm::APInt(32, 5), ArrayType::Normal, 0)
2174 };
2175
Douglas Gregor44b43212008-12-11 16:49:14 +00002176 for (size_t i = 0; i < 4; ++i) {
2177 FieldDecl *Field = FieldDecl::Create(*this,
2178 ObjCFastEnumerationStateTypeDecl,
2179 SourceLocation(), 0,
2180 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002181 /*Mutable=*/false);
Douglas Gregor6ab35242009-04-09 21:40:53 +00002182 ObjCFastEnumerationStateTypeDecl->addDecl(*this, Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002183 }
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002184
Douglas Gregor44b43212008-12-11 16:49:14 +00002185 ObjCFastEnumerationStateTypeDecl->completeDefinition(*this);
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002186 }
2187
2188 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2189}
2190
Douglas Gregor319ac892009-04-23 22:29:11 +00002191void ASTContext::setObjCFastEnumerationStateType(QualType T) {
2192 const RecordType *Rec = T->getAsRecordType();
2193 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
2194 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
2195}
2196
Anders Carlssone8c49532007-10-29 06:33:42 +00002197// This returns true if a type has been typedefed to BOOL:
2198// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00002199static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00002200 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00002201 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
2202 return II->isStr("BOOL");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002203
2204 return false;
2205}
2206
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002207/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002208/// purpose.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002209int ASTContext::getObjCEncodingTypeSize(QualType type) {
Chris Lattner98be4942008-03-05 18:54:05 +00002210 uint64_t sz = getTypeSize(type);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002211
2212 // Make all integer and enum types at least as large as an int
2213 if (sz > 0 && type->isIntegralType())
Chris Lattner98be4942008-03-05 18:54:05 +00002214 sz = std::max(sz, getTypeSize(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002215 // Treat arrays as pointers, since that's how they're passed in.
2216 else if (type->isArrayType())
Chris Lattner98be4942008-03-05 18:54:05 +00002217 sz = getTypeSize(VoidPtrTy);
2218 return sz / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002219}
2220
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002221/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002222/// declaration.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002223void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00002224 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002225 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002226 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002227 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002228 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002229 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002230 // Compute size of all parameters.
2231 // Start with computing size of a pointer in number of bytes.
2232 // FIXME: There might(should) be a better way of doing this computation!
2233 SourceLocation Loc;
Chris Lattner98be4942008-03-05 18:54:05 +00002234 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002235 // The first two arguments (self and _cmd) are pointers; account for
2236 // their size.
2237 int ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00002238 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2239 E = Decl->param_end(); PI != E; ++PI) {
2240 QualType PType = (*PI)->getType();
2241 int sz = getObjCEncodingTypeSize(PType);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002242 assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002243 ParmOffset += sz;
2244 }
2245 S += llvm::utostr(ParmOffset);
2246 S += "@0:";
2247 S += llvm::utostr(PtrSize);
2248
2249 // Argument types.
2250 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00002251 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2252 E = Decl->param_end(); PI != E; ++PI) {
2253 ParmVarDecl *PVDecl = *PI;
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00002254 QualType PType = PVDecl->getOriginalType();
2255 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00002256 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
2257 // Use array's original type only if it has known number of
2258 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00002259 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00002260 PType = PVDecl->getType();
2261 } else if (PType->isFunctionType())
2262 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002263 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002264 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00002265 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002266 getObjCEncodingForType(PType, S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002267 S += llvm::utostr(ParmOffset);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002268 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002269 }
2270}
2271
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002272/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00002273/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002274/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
2275/// NULL when getting encodings for protocol properties.
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00002276/// Property attributes are stored as a comma-delimited C string. The simple
2277/// attributes readonly and bycopy are encoded as single characters. The
2278/// parametrized attributes, getter=name, setter=name, and ivar=name, are
2279/// encoded as single characters, followed by an identifier. Property types
2280/// are also encoded as a parametrized attribute. The characters used to encode
2281/// these attributes are defined by the following enumeration:
2282/// @code
2283/// enum PropertyAttributes {
2284/// kPropertyReadOnly = 'R', // property is read-only.
2285/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
2286/// kPropertyByref = '&', // property is a reference to the value last assigned
2287/// kPropertyDynamic = 'D', // property is dynamic
2288/// kPropertyGetter = 'G', // followed by getter selector name
2289/// kPropertySetter = 'S', // followed by setter selector name
2290/// kPropertyInstanceVariable = 'V' // followed by instance variable name
2291/// kPropertyType = 't' // followed by old-style type encoding.
2292/// kPropertyWeak = 'W' // 'weak' property
2293/// kPropertyStrong = 'P' // property GC'able
2294/// kPropertyNonAtomic = 'N' // property non-atomic
2295/// };
2296/// @endcode
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002297void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
2298 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00002299 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002300 // Collect information from the property implementation decl(s).
2301 bool Dynamic = false;
2302 ObjCPropertyImplDecl *SynthesizePID = 0;
2303
2304 // FIXME: Duplicated code due to poor abstraction.
2305 if (Container) {
2306 if (const ObjCCategoryImplDecl *CID =
2307 dyn_cast<ObjCCategoryImplDecl>(Container)) {
2308 for (ObjCCategoryImplDecl::propimpl_iterator
Douglas Gregor653f1b12009-04-23 01:02:12 +00002309 i = CID->propimpl_begin(*this), e = CID->propimpl_end(*this);
2310 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002311 ObjCPropertyImplDecl *PID = *i;
2312 if (PID->getPropertyDecl() == PD) {
2313 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2314 Dynamic = true;
2315 } else {
2316 SynthesizePID = PID;
2317 }
2318 }
2319 }
2320 } else {
Chris Lattner61710852008-10-05 17:34:18 +00002321 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002322 for (ObjCCategoryImplDecl::propimpl_iterator
Douglas Gregor653f1b12009-04-23 01:02:12 +00002323 i = OID->propimpl_begin(*this), e = OID->propimpl_end(*this);
2324 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002325 ObjCPropertyImplDecl *PID = *i;
2326 if (PID->getPropertyDecl() == PD) {
2327 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2328 Dynamic = true;
2329 } else {
2330 SynthesizePID = PID;
2331 }
2332 }
2333 }
2334 }
2335 }
2336
2337 // FIXME: This is not very efficient.
2338 S = "T";
2339
2340 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002341 // GCC has some special rules regarding encoding of properties which
2342 // closely resembles encoding of ivars.
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002343 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002344 true /* outermost type */,
2345 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002346
2347 if (PD->isReadOnly()) {
2348 S += ",R";
2349 } else {
2350 switch (PD->getSetterKind()) {
2351 case ObjCPropertyDecl::Assign: break;
2352 case ObjCPropertyDecl::Copy: S += ",C"; break;
2353 case ObjCPropertyDecl::Retain: S += ",&"; break;
2354 }
2355 }
2356
2357 // It really isn't clear at all what this means, since properties
2358 // are "dynamic by default".
2359 if (Dynamic)
2360 S += ",D";
2361
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002362 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
2363 S += ",N";
2364
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002365 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
2366 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002367 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002368 }
2369
2370 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
2371 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002372 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002373 }
2374
2375 if (SynthesizePID) {
2376 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
2377 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00002378 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002379 }
2380
2381 // FIXME: OBJCGC: weak & strong
2382}
2383
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002384/// getLegacyIntegralTypeEncoding -
2385/// Another legacy compatibility encoding: 32-bit longs are encoded as
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002386/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002387/// 'i' or 'I' instead if encoding a struct field, or a pointer!
2388///
2389void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
2390 if (dyn_cast<TypedefType>(PointeeTy.getTypePtr())) {
2391 if (const BuiltinType *BT = PointeeTy->getAsBuiltinType()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002392 if (BT->getKind() == BuiltinType::ULong &&
2393 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002394 PointeeTy = UnsignedIntTy;
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002395 else
2396 if (BT->getKind() == BuiltinType::Long &&
2397 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002398 PointeeTy = IntTy;
2399 }
2400 }
2401}
2402
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002403void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002404 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002405 // We follow the behavior of gcc, expanding structures which are
2406 // directly pointed to, and expanding embedded structures. Note that
2407 // these rules are sufficient to prevent recursive encoding of the
2408 // same type.
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00002409 getObjCEncodingForTypeImpl(T, S, true, true, Field,
2410 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002411}
2412
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002413static void EncodeBitField(const ASTContext *Context, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002414 const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002415 const Expr *E = FD->getBitWidth();
2416 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
2417 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Eli Friedman9a901bb2009-04-26 19:19:15 +00002418 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002419 S += 'b';
2420 S += llvm::utostr(N);
2421}
2422
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002423void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
2424 bool ExpandPointedToStructures,
2425 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002426 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002427 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002428 bool EncodingProperty) {
Anders Carlssone8c49532007-10-29 06:33:42 +00002429 if (const BuiltinType *BT = T->getAsBuiltinType()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002430 if (FD && FD->isBitField()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002431 EncodeBitField(this, S, FD);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002432 }
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002433 else {
2434 char encoding;
2435 switch (BT->getKind()) {
2436 default: assert(0 && "Unhandled builtin type kind");
2437 case BuiltinType::Void: encoding = 'v'; break;
2438 case BuiltinType::Bool: encoding = 'B'; break;
2439 case BuiltinType::Char_U:
2440 case BuiltinType::UChar: encoding = 'C'; break;
2441 case BuiltinType::UShort: encoding = 'S'; break;
2442 case BuiltinType::UInt: encoding = 'I'; break;
Fariborz Jahanian72696e12009-02-11 22:31:45 +00002443 case BuiltinType::ULong:
2444 encoding =
2445 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
2446 break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002447 case BuiltinType::UInt128: encoding = 'T'; break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002448 case BuiltinType::ULongLong: encoding = 'Q'; break;
2449 case BuiltinType::Char_S:
2450 case BuiltinType::SChar: encoding = 'c'; break;
2451 case BuiltinType::Short: encoding = 's'; break;
2452 case BuiltinType::Int: encoding = 'i'; break;
Fariborz Jahanian72696e12009-02-11 22:31:45 +00002453 case BuiltinType::Long:
2454 encoding =
2455 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
2456 break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002457 case BuiltinType::LongLong: encoding = 'q'; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002458 case BuiltinType::Int128: encoding = 't'; break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002459 case BuiltinType::Float: encoding = 'f'; break;
2460 case BuiltinType::Double: encoding = 'd'; break;
2461 case BuiltinType::LongDouble: encoding = 'd'; break;
2462 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002463
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002464 S += encoding;
2465 }
Anders Carlssonc612f7b2009-04-09 21:55:45 +00002466 } else if (const ComplexType *CT = T->getAsComplexType()) {
2467 S += 'j';
2468 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
2469 false);
2470 } else if (T->isObjCQualifiedIdType()) {
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002471 getObjCEncodingForTypeImpl(getObjCIdType(), S,
2472 ExpandPointedToStructures,
2473 ExpandStructures, FD);
2474 if (FD || EncodingProperty) {
2475 // Note that we do extended encoding of protocol qualifer list
2476 // Only when doing ivar or property encoding.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002477 const ObjCObjectPointerType *QIDT = T->getAsObjCQualifiedIdType();
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002478 S += '"';
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002479 for (ObjCObjectPointerType::qual_iterator I = QIDT->qual_begin(),
Steve Naroff446ee4e2009-05-27 16:21:00 +00002480 E = QIDT->qual_end(); I != E; ++I) {
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002481 S += '<';
Steve Naroff446ee4e2009-05-27 16:21:00 +00002482 S += (*I)->getNameAsString();
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002483 S += '>';
2484 }
2485 S += '"';
2486 }
2487 return;
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002488 }
2489 else if (const PointerType *PT = T->getAsPointerType()) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002490 QualType PointeeTy = PT->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002491 bool isReadOnly = false;
2492 // For historical/compatibility reasons, the read-only qualifier of the
2493 // pointee gets emitted _before_ the '^'. The read-only qualifier of
2494 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
2495 // Also, do not emit the 'r' for anything but the outermost type!
2496 if (dyn_cast<TypedefType>(T.getTypePtr())) {
2497 if (OutermostType && T.isConstQualified()) {
2498 isReadOnly = true;
2499 S += 'r';
2500 }
2501 }
2502 else if (OutermostType) {
2503 QualType P = PointeeTy;
2504 while (P->getAsPointerType())
2505 P = P->getAsPointerType()->getPointeeType();
2506 if (P.isConstQualified()) {
2507 isReadOnly = true;
2508 S += 'r';
2509 }
2510 }
2511 if (isReadOnly) {
2512 // Another legacy compatibility encoding. Some ObjC qualifier and type
2513 // combinations need to be rearranged.
2514 // Rewrite "in const" from "nr" to "rn"
2515 const char * s = S.c_str();
2516 int len = S.length();
2517 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
2518 std::string replace = "rn";
2519 S.replace(S.end()-2, S.end(), replace);
2520 }
2521 }
Steve Naroff389bf462009-02-12 17:52:19 +00002522 if (isObjCIdStructType(PointeeTy)) {
Fariborz Jahanianc2939bc2007-10-30 17:06:23 +00002523 S += '@';
2524 return;
Fariborz Jahanianc166d732008-12-19 00:14:49 +00002525 }
2526 else if (PointeeTy->isObjCInterfaceType()) {
Fariborz Jahanianbb99bde2009-02-16 21:41:04 +00002527 if (!EncodingProperty &&
Fariborz Jahanian225dfd72009-02-16 22:09:26 +00002528 isa<TypedefType>(PointeeTy.getTypePtr())) {
Fariborz Jahanian3e1b16c2008-12-23 21:30:15 +00002529 // Another historical/compatibility reason.
2530 // We encode the underlying type which comes out as
2531 // {...};
2532 S += '^';
2533 getObjCEncodingForTypeImpl(PointeeTy, S,
2534 false, ExpandPointedToStructures,
2535 NULL);
2536 return;
2537 }
Fariborz Jahanianc166d732008-12-19 00:14:49 +00002538 S += '@';
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002539 if (FD || EncodingProperty) {
Fariborz Jahanian86f938b2009-02-21 18:23:24 +00002540 const ObjCInterfaceType *OIT =
2541 PointeeTy.getUnqualifiedType()->getAsObjCInterfaceType();
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002542 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanianadcaf542008-12-20 19:17:01 +00002543 S += '"';
2544 S += OI->getNameAsCString();
Steve Naroff446ee4e2009-05-27 16:21:00 +00002545 for (ObjCInterfaceType::qual_iterator I = OIT->qual_begin(),
2546 E = OIT->qual_end(); I != E; ++I) {
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002547 S += '<';
Steve Naroff446ee4e2009-05-27 16:21:00 +00002548 S += (*I)->getNameAsString();
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002549 S += '>';
2550 }
Fariborz Jahanianadcaf542008-12-20 19:17:01 +00002551 S += '"';
2552 }
Fariborz Jahanianc166d732008-12-19 00:14:49 +00002553 return;
Steve Naroff389bf462009-02-12 17:52:19 +00002554 } else if (isObjCClassStructType(PointeeTy)) {
Anders Carlsson8baaca52007-10-31 02:53:19 +00002555 S += '#';
2556 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002557 } else if (isObjCSelType(PointeeTy)) {
Anders Carlsson8baaca52007-10-31 02:53:19 +00002558 S += ':';
2559 return;
Fariborz Jahanianc2939bc2007-10-30 17:06:23 +00002560 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002561
2562 if (PointeeTy->isCharType()) {
2563 // char pointer types should be encoded as '*' unless it is a
2564 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00002565 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002566 S += '*';
2567 return;
2568 }
2569 }
2570
2571 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002572 getLegacyIntegralTypeEncoding(PointeeTy);
2573
2574 getObjCEncodingForTypeImpl(PointeeTy, S,
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002575 false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002576 NULL);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002577 } else if (const ArrayType *AT =
2578 // Ignore type qualifiers etc.
2579 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00002580 if (isa<IncompleteArrayType>(AT)) {
2581 // Incomplete arrays are encoded as a pointer to the array element.
2582 S += '^';
2583
2584 getObjCEncodingForTypeImpl(AT->getElementType(), S,
2585 false, ExpandStructures, FD);
2586 } else {
2587 S += '[';
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002588
Anders Carlsson559a8332009-02-22 01:38:57 +00002589 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
2590 S += llvm::utostr(CAT->getSize().getZExtValue());
2591 else {
2592 //Variable length arrays are encoded as a regular array with 0 elements.
2593 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
2594 S += '0';
2595 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002596
Anders Carlsson559a8332009-02-22 01:38:57 +00002597 getObjCEncodingForTypeImpl(AT->getElementType(), S,
2598 false, ExpandStructures, FD);
2599 S += ']';
2600 }
Anders Carlssonc0a87b72007-10-30 00:06:20 +00002601 } else if (T->getAsFunctionType()) {
2602 S += '?';
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00002603 } else if (const RecordType *RTy = T->getAsRecordType()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002604 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002605 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00002606 // Anonymous structures print as '?'
2607 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
2608 S += II->getName();
2609 } else {
2610 S += '?';
2611 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002612 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002613 S += '=';
Douglas Gregor6ab35242009-04-09 21:40:53 +00002614 for (RecordDecl::field_iterator Field = RDecl->field_begin(*this),
2615 FieldEnd = RDecl->field_end(*this);
Douglas Gregor44b43212008-12-11 16:49:14 +00002616 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002617 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002618 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00002619 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002620 S += '"';
2621 }
2622
2623 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002624 if (Field->isBitField()) {
2625 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
2626 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002627 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002628 QualType qt = Field->getType();
2629 getLegacyIntegralTypeEncoding(qt);
2630 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002631 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002632 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002633 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00002634 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002635 S += RDecl->isUnion() ? ')' : '}';
Steve Naroff5e711242007-12-12 22:30:11 +00002636 } else if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002637 if (FD && FD->isBitField())
2638 EncodeBitField(this, S, FD);
2639 else
2640 S += 'i';
Steve Naroff485eeff2008-09-24 15:05:44 +00002641 } else if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00002642 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002643 } else if (T->isObjCInterfaceType()) {
2644 // @encode(class_name)
2645 ObjCInterfaceDecl *OI = T->getAsObjCInterfaceType()->getDecl();
2646 S += '{';
2647 const IdentifierInfo *II = OI->getIdentifier();
2648 S += II->getName();
2649 S += '=';
Chris Lattnerf1690852009-03-31 08:48:01 +00002650 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002651 CollectObjCIvars(OI, RecFields);
Chris Lattnerf1690852009-03-31 08:48:01 +00002652 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002653 if (RecFields[i]->isBitField())
2654 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2655 RecFields[i]);
2656 else
2657 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2658 FD);
2659 }
2660 S += '}';
2661 }
2662 else
Steve Narofff69cc5d2008-01-30 19:17:43 +00002663 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002664}
2665
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002666void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002667 std::string& S) const {
2668 if (QT & Decl::OBJC_TQ_In)
2669 S += 'n';
2670 if (QT & Decl::OBJC_TQ_Inout)
2671 S += 'N';
2672 if (QT & Decl::OBJC_TQ_Out)
2673 S += 'o';
2674 if (QT & Decl::OBJC_TQ_Bycopy)
2675 S += 'O';
2676 if (QT & Decl::OBJC_TQ_Byref)
2677 S += 'R';
2678 if (QT & Decl::OBJC_TQ_Oneway)
2679 S += 'V';
2680}
2681
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002682void ASTContext::setBuiltinVaListType(QualType T)
2683{
2684 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
2685
2686 BuiltinVaListType = T;
2687}
2688
Douglas Gregor319ac892009-04-23 22:29:11 +00002689void ASTContext::setObjCIdType(QualType T)
Steve Naroff7e219e42007-10-15 14:41:52 +00002690{
Douglas Gregor319ac892009-04-23 22:29:11 +00002691 ObjCIdType = T;
2692
2693 const TypedefType *TT = T->getAsTypedefType();
2694 if (!TT)
2695 return;
2696
2697 TypedefDecl *TD = TT->getDecl();
Steve Naroff7e219e42007-10-15 14:41:52 +00002698
2699 // typedef struct objc_object *id;
2700 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00002701 // User error - caller will issue diagnostics.
2702 if (!ptr)
2703 return;
Steve Naroff7e219e42007-10-15 14:41:52 +00002704 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00002705 // User error - caller will issue diagnostics.
2706 if (!rec)
2707 return;
Steve Naroff7e219e42007-10-15 14:41:52 +00002708 IdStructType = rec;
2709}
2710
Douglas Gregor319ac892009-04-23 22:29:11 +00002711void ASTContext::setObjCSelType(QualType T)
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002712{
Douglas Gregor319ac892009-04-23 22:29:11 +00002713 ObjCSelType = T;
2714
2715 const TypedefType *TT = T->getAsTypedefType();
2716 if (!TT)
2717 return;
2718 TypedefDecl *TD = TT->getDecl();
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002719
2720 // typedef struct objc_selector *SEL;
2721 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00002722 if (!ptr)
2723 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002724 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00002725 if (!rec)
2726 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002727 SelStructType = rec;
2728}
2729
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002730void ASTContext::setObjCProtoType(QualType QT)
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00002731{
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002732 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00002733}
2734
Douglas Gregor319ac892009-04-23 22:29:11 +00002735void ASTContext::setObjCClassType(QualType T)
Anders Carlsson8baaca52007-10-31 02:53:19 +00002736{
Douglas Gregor319ac892009-04-23 22:29:11 +00002737 ObjCClassType = T;
2738
2739 const TypedefType *TT = T->getAsTypedefType();
2740 if (!TT)
2741 return;
2742 TypedefDecl *TD = TT->getDecl();
Anders Carlsson8baaca52007-10-31 02:53:19 +00002743
2744 // typedef struct objc_class *Class;
2745 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
2746 assert(ptr && "'Class' incorrectly typed");
2747 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
2748 assert(rec && "'Class' incorrectly typed");
2749 ClassStructType = rec;
2750}
2751
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002752void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
2753 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00002754 "'NSConstantString' type already set!");
2755
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002756 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00002757}
2758
Douglas Gregor7532dc62009-03-30 22:58:21 +00002759/// \brief Retrieve the template name that represents a qualified
2760/// template name such as \c std::vector.
2761TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
2762 bool TemplateKeyword,
2763 TemplateDecl *Template) {
2764 llvm::FoldingSetNodeID ID;
2765 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
2766
2767 void *InsertPos = 0;
2768 QualifiedTemplateName *QTN =
2769 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
2770 if (!QTN) {
2771 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
2772 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
2773 }
2774
2775 return TemplateName(QTN);
2776}
2777
2778/// \brief Retrieve the template name that represents a dependent
2779/// template name such as \c MetaFun::template apply.
2780TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
2781 const IdentifierInfo *Name) {
2782 assert(NNS->isDependent() && "Nested name specifier must be dependent");
2783
2784 llvm::FoldingSetNodeID ID;
2785 DependentTemplateName::Profile(ID, NNS, Name);
2786
2787 void *InsertPos = 0;
2788 DependentTemplateName *QTN =
2789 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
2790
2791 if (QTN)
2792 return TemplateName(QTN);
2793
2794 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2795 if (CanonNNS == NNS) {
2796 QTN = new (*this,4) DependentTemplateName(NNS, Name);
2797 } else {
2798 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
2799 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
2800 }
2801
2802 DependentTemplateNames.InsertNode(QTN, InsertPos);
2803 return TemplateName(QTN);
2804}
2805
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002806/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00002807/// TargetInfo, produce the corresponding type. The unsigned @p Type
2808/// is actually a value of type @c TargetInfo::IntType.
2809QualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002810 switch (Type) {
2811 case TargetInfo::NoInt: return QualType();
2812 case TargetInfo::SignedShort: return ShortTy;
2813 case TargetInfo::UnsignedShort: return UnsignedShortTy;
2814 case TargetInfo::SignedInt: return IntTy;
2815 case TargetInfo::UnsignedInt: return UnsignedIntTy;
2816 case TargetInfo::SignedLong: return LongTy;
2817 case TargetInfo::UnsignedLong: return UnsignedLongTy;
2818 case TargetInfo::SignedLongLong: return LongLongTy;
2819 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
2820 }
2821
2822 assert(false && "Unhandled TargetInfo::IntType value");
Daniel Dunbarb3ac5432008-11-11 01:16:00 +00002823 return QualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002824}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00002825
2826//===----------------------------------------------------------------------===//
2827// Type Predicates.
2828//===----------------------------------------------------------------------===//
2829
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00002830/// isObjCNSObjectType - Return true if this is an NSObject object using
2831/// NSObject attribute on a c-style pointer type.
2832/// FIXME - Make it work directly on types.
2833///
2834bool ASTContext::isObjCNSObjectType(QualType Ty) const {
2835 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
2836 if (TypedefDecl *TD = TDT->getDecl())
Douglas Gregor68584ed2009-06-18 16:11:24 +00002837 if (TD->getAttr<ObjCNSObjectAttr>(*const_cast<ASTContext*>(this)))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00002838 return true;
2839 }
2840 return false;
2841}
2842
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00002843/// isObjCObjectPointerType - Returns true if type is an Objective-C pointer
2844/// to an object type. This includes "id" and "Class" (two 'special' pointers
2845/// to struct), Interface* (pointer to ObjCInterfaceType) and id<P> (qualified
2846/// ID type).
2847bool ASTContext::isObjCObjectPointerType(QualType Ty) const {
Steve Naroffd4617772009-02-23 18:36:16 +00002848 if (Ty->isObjCQualifiedIdType())
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00002849 return true;
2850
Steve Naroff6ae98502008-10-21 18:24:04 +00002851 // Blocks are objects.
2852 if (Ty->isBlockPointerType())
2853 return true;
2854
2855 // All other object types are pointers.
Chris Lattner16ede0e2009-04-12 23:51:02 +00002856 const PointerType *PT = Ty->getAsPointerType();
2857 if (PT == 0)
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00002858 return false;
2859
Chris Lattner16ede0e2009-04-12 23:51:02 +00002860 // If this a pointer to an interface (e.g. NSString*), it is ok.
2861 if (PT->getPointeeType()->isObjCInterfaceType() ||
2862 // If is has NSObject attribute, OK as well.
2863 isObjCNSObjectType(Ty))
2864 return true;
2865
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00002866 // Check to see if this is 'id' or 'Class', both of which are typedefs for
2867 // pointer types. This looks for the typedef specifically, not for the
Chris Lattner16ede0e2009-04-12 23:51:02 +00002868 // underlying type. Iteratively strip off typedefs so that we can handle
2869 // typedefs of typedefs.
2870 while (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
2871 if (Ty.getUnqualifiedType() == getObjCIdType() ||
2872 Ty.getUnqualifiedType() == getObjCClassType())
2873 return true;
2874
2875 Ty = TDT->getDecl()->getUnderlyingType();
2876 }
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00002877
Chris Lattner16ede0e2009-04-12 23:51:02 +00002878 return false;
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00002879}
2880
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00002881/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
2882/// garbage collection attribute.
2883///
2884QualType::GCAttrTypes ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
Chris Lattnerb7d25532009-02-18 22:53:11 +00002885 QualType::GCAttrTypes GCAttrs = QualType::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00002886 if (getLangOptions().ObjC1 &&
2887 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00002888 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00002889 // Default behavious under objective-c's gc is for objective-c pointers
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00002890 // (or pointers to them) be treated as though they were declared
2891 // as __strong.
2892 if (GCAttrs == QualType::GCNone) {
2893 if (isObjCObjectPointerType(Ty))
2894 GCAttrs = QualType::Strong;
2895 else if (Ty->isPointerType())
2896 return getObjCGCAttrKind(Ty->getAsPointerType()->getPointeeType());
2897 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00002898 // Non-pointers have none gc'able attribute regardless of the attribute
2899 // set on them.
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00002900 else if (!Ty->isPointerType() && !isObjCObjectPointerType(Ty))
Fariborz Jahanianc2112182009-04-11 00:00:54 +00002901 return QualType::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00002902 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00002903 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00002904}
2905
Chris Lattner6ac46a42008-04-07 06:51:04 +00002906//===----------------------------------------------------------------------===//
2907// Type Compatibility Testing
2908//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00002909
Chris Lattner6ac46a42008-04-07 06:51:04 +00002910/// areCompatVectorTypes - Return true if the two specified vector types are
2911/// compatible.
2912static bool areCompatVectorTypes(const VectorType *LHS,
2913 const VectorType *RHS) {
2914 assert(LHS->isCanonical() && RHS->isCanonical());
2915 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00002916 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00002917}
2918
Eli Friedman3d815e72008-08-22 00:56:42 +00002919/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00002920/// compatible for assignment from RHS to LHS. This handles validation of any
2921/// protocol qualifiers on the LHS or RHS.
2922///
Eli Friedman3d815e72008-08-22 00:56:42 +00002923bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
2924 const ObjCInterfaceType *RHS) {
Chris Lattner6ac46a42008-04-07 06:51:04 +00002925 // Verify that the base decls are compatible: the RHS must be a subclass of
2926 // the LHS.
2927 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
2928 return false;
2929
2930 // RHS must have a superset of the protocols in the LHS. If the LHS is not
2931 // protocol qualified at all, then we are good.
2932 if (!isa<ObjCQualifiedInterfaceType>(LHS))
2933 return true;
2934
2935 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
2936 // isn't a superset.
2937 if (!isa<ObjCQualifiedInterfaceType>(RHS))
2938 return true; // FIXME: should return false!
2939
2940 // Finally, we must have two protocol-qualified interfaces.
2941 const ObjCQualifiedInterfaceType *LHSP =cast<ObjCQualifiedInterfaceType>(LHS);
2942 const ObjCQualifiedInterfaceType *RHSP =cast<ObjCQualifiedInterfaceType>(RHS);
Chris Lattner6ac46a42008-04-07 06:51:04 +00002943
Steve Naroff91b0b0c2009-03-01 16:12:44 +00002944 // All LHS protocols must have a presence on the RHS.
2945 assert(LHSP->qual_begin() != LHSP->qual_end() && "Empty LHS protocol list?");
Chris Lattner6ac46a42008-04-07 06:51:04 +00002946
Steve Naroff91b0b0c2009-03-01 16:12:44 +00002947 for (ObjCQualifiedInterfaceType::qual_iterator LHSPI = LHSP->qual_begin(),
2948 LHSPE = LHSP->qual_end();
2949 LHSPI != LHSPE; LHSPI++) {
2950 bool RHSImplementsProtocol = false;
2951
2952 // If the RHS doesn't implement the protocol on the left, the types
2953 // are incompatible.
2954 for (ObjCQualifiedInterfaceType::qual_iterator RHSPI = RHSP->qual_begin(),
2955 RHSPE = RHSP->qual_end();
2956 !RHSImplementsProtocol && (RHSPI != RHSPE); RHSPI++) {
2957 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier()))
2958 RHSImplementsProtocol = true;
2959 }
2960 // FIXME: For better diagnostics, consider passing back the protocol name.
2961 if (!RHSImplementsProtocol)
2962 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00002963 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00002964 // The RHS implements all protocols listed on the LHS.
2965 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00002966}
2967
Steve Naroff389bf462009-02-12 17:52:19 +00002968bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
2969 // get the "pointed to" types
2970 const PointerType *LHSPT = LHS->getAsPointerType();
2971 const PointerType *RHSPT = RHS->getAsPointerType();
2972
2973 if (!LHSPT || !RHSPT)
2974 return false;
2975
2976 QualType lhptee = LHSPT->getPointeeType();
2977 QualType rhptee = RHSPT->getPointeeType();
2978 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2979 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2980 // ID acts sort of like void* for ObjC interfaces
2981 if (LHSIface && isObjCIdStructType(rhptee))
2982 return true;
2983 if (RHSIface && isObjCIdStructType(lhptee))
2984 return true;
2985 if (!LHSIface || !RHSIface)
2986 return false;
2987 return canAssignObjCInterfaces(LHSIface, RHSIface) ||
2988 canAssignObjCInterfaces(RHSIface, LHSIface);
2989}
2990
Steve Naroffec0550f2007-10-15 20:41:53 +00002991/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
2992/// both shall have the identically qualified version of a compatible type.
2993/// C99 6.2.7p1: Two types have compatible types if their types are the
2994/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman3d815e72008-08-22 00:56:42 +00002995bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
2996 return !mergeTypes(LHS, RHS).isNull();
2997}
2998
2999QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
3000 const FunctionType *lbase = lhs->getAsFunctionType();
3001 const FunctionType *rbase = rhs->getAsFunctionType();
Douglas Gregor72564e72009-02-26 23:50:07 +00003002 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
3003 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00003004 bool allLTypes = true;
3005 bool allRTypes = true;
3006
3007 // Check return type
3008 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
3009 if (retType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00003010 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
3011 allLTypes = false;
3012 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
3013 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00003014
3015 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00003016 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
3017 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00003018 unsigned lproto_nargs = lproto->getNumArgs();
3019 unsigned rproto_nargs = rproto->getNumArgs();
3020
3021 // Compatible functions must have the same number of arguments
3022 if (lproto_nargs != rproto_nargs)
3023 return QualType();
3024
3025 // Variadic and non-variadic functions aren't compatible
3026 if (lproto->isVariadic() != rproto->isVariadic())
3027 return QualType();
3028
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003029 if (lproto->getTypeQuals() != rproto->getTypeQuals())
3030 return QualType();
3031
Eli Friedman3d815e72008-08-22 00:56:42 +00003032 // Check argument compatibility
3033 llvm::SmallVector<QualType, 10> types;
3034 for (unsigned i = 0; i < lproto_nargs; i++) {
3035 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
3036 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
3037 QualType argtype = mergeTypes(largtype, rargtype);
3038 if (argtype.isNull()) return QualType();
3039 types.push_back(argtype);
Chris Lattner61710852008-10-05 17:34:18 +00003040 if (getCanonicalType(argtype) != getCanonicalType(largtype))
3041 allLTypes = false;
3042 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
3043 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00003044 }
3045 if (allLTypes) return lhs;
3046 if (allRTypes) return rhs;
3047 return getFunctionType(retType, types.begin(), types.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003048 lproto->isVariadic(), lproto->getTypeQuals());
Eli Friedman3d815e72008-08-22 00:56:42 +00003049 }
3050
3051 if (lproto) allRTypes = false;
3052 if (rproto) allLTypes = false;
3053
Douglas Gregor72564e72009-02-26 23:50:07 +00003054 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00003055 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00003056 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00003057 if (proto->isVariadic()) return QualType();
3058 // Check that the types are compatible with the types that
3059 // would result from default argument promotions (C99 6.7.5.3p15).
3060 // The only types actually affected are promotable integer
3061 // types and floats, which would be passed as a different
3062 // type depending on whether the prototype is visible.
3063 unsigned proto_nargs = proto->getNumArgs();
3064 for (unsigned i = 0; i < proto_nargs; ++i) {
3065 QualType argTy = proto->getArgType(i);
3066 if (argTy->isPromotableIntegerType() ||
3067 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
3068 return QualType();
3069 }
3070
3071 if (allLTypes) return lhs;
3072 if (allRTypes) return rhs;
3073 return getFunctionType(retType, proto->arg_type_begin(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003074 proto->getNumArgs(), lproto->isVariadic(),
3075 lproto->getTypeQuals());
Eli Friedman3d815e72008-08-22 00:56:42 +00003076 }
3077
3078 if (allLTypes) return lhs;
3079 if (allRTypes) return rhs;
Douglas Gregor72564e72009-02-26 23:50:07 +00003080 return getFunctionNoProtoType(retType);
Eli Friedman3d815e72008-08-22 00:56:42 +00003081}
3082
3083QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
Bill Wendling43d69752007-12-03 07:33:35 +00003084 // C++ [expr]: If an expression initially has the type "reference to T", the
3085 // type is adjusted to "T" prior to any further analysis, the expression
3086 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003087 // expression is an lvalue unless the reference is an rvalue reference and
3088 // the expression is a function call (possibly inside parentheses).
Eli Friedman3d815e72008-08-22 00:56:42 +00003089 // FIXME: C++ shouldn't be going through here! The rules are different
3090 // enough that they should be handled separately.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003091 // FIXME: Merging of lvalue and rvalue references is incorrect. C++ *really*
3092 // shouldn't be going through here!
Eli Friedman3d815e72008-08-22 00:56:42 +00003093 if (const ReferenceType *RT = LHS->getAsReferenceType())
Chris Lattnerc4e40592008-04-07 04:07:56 +00003094 LHS = RT->getPointeeType();
Eli Friedman3d815e72008-08-22 00:56:42 +00003095 if (const ReferenceType *RT = RHS->getAsReferenceType())
Chris Lattnerc4e40592008-04-07 04:07:56 +00003096 RHS = RT->getPointeeType();
Chris Lattnerf3692dc2008-04-07 05:37:56 +00003097
Eli Friedman3d815e72008-08-22 00:56:42 +00003098 QualType LHSCan = getCanonicalType(LHS),
3099 RHSCan = getCanonicalType(RHS);
3100
3101 // If two types are identical, they are compatible.
3102 if (LHSCan == RHSCan)
3103 return LHS;
3104
3105 // If the qualifiers are different, the types aren't compatible
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003106 // Note that we handle extended qualifiers later, in the
3107 // case for ExtQualType.
3108 if (LHSCan.getCVRQualifiers() != RHSCan.getCVRQualifiers())
Eli Friedman3d815e72008-08-22 00:56:42 +00003109 return QualType();
3110
Eli Friedman852d63b2009-06-01 01:22:52 +00003111 Type::TypeClass LHSClass = LHSCan->getTypeClass();
3112 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00003113
Chris Lattner1adb8832008-01-14 05:45:46 +00003114 // We want to consider the two function types to be the same for these
3115 // comparisons, just force one to the other.
3116 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
3117 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00003118
Eli Friedman07d25872009-06-02 05:28:56 +00003119 // Strip off objc_gc attributes off the top level so they can be merged.
3120 // This is a complete mess, but the attribute itself doesn't make much sense.
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003121 if (RHSClass == Type::ExtQual) {
Eli Friedman07d25872009-06-02 05:28:56 +00003122 QualType::GCAttrTypes GCAttr = RHSCan.getObjCGCAttr();
3123 if (GCAttr != QualType::GCNone) {
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003124 QualType::GCAttrTypes GCLHSAttr = LHSCan.getObjCGCAttr();
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003125 // __weak attribute must appear on both declarations.
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003126 // __strong attribue is redundant if other decl is an objective-c
3127 // object pointer (or decorated with __strong attribute); otherwise
3128 // issue error.
3129 if ((GCAttr == QualType::Weak && GCLHSAttr != GCAttr) ||
3130 (GCAttr == QualType::Strong && GCLHSAttr != GCAttr &&
3131 LHSCan->isPointerType() && !isObjCObjectPointerType(LHSCan) &&
3132 !isObjCIdStructType(LHSCan->getAsPointerType()->getPointeeType())))
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003133 return QualType();
3134
Eli Friedman07d25872009-06-02 05:28:56 +00003135 RHS = QualType(cast<ExtQualType>(RHS.getDesugaredType())->getBaseType(),
3136 RHS.getCVRQualifiers());
3137 QualType Result = mergeTypes(LHS, RHS);
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003138 if (!Result.isNull()) {
3139 if (Result.getObjCGCAttr() == QualType::GCNone)
3140 Result = getObjCGCQualType(Result, GCAttr);
3141 else if (Result.getObjCGCAttr() != GCAttr)
3142 Result = QualType();
3143 }
Eli Friedman07d25872009-06-02 05:28:56 +00003144 return Result;
3145 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003146 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003147 if (LHSClass == Type::ExtQual) {
Eli Friedman07d25872009-06-02 05:28:56 +00003148 QualType::GCAttrTypes GCAttr = LHSCan.getObjCGCAttr();
3149 if (GCAttr != QualType::GCNone) {
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003150 QualType::GCAttrTypes GCRHSAttr = RHSCan.getObjCGCAttr();
3151 // __weak attribute must appear on both declarations. __strong
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003152 // __strong attribue is redundant if other decl is an objective-c
3153 // object pointer (or decorated with __strong attribute); otherwise
3154 // issue error.
3155 if ((GCAttr == QualType::Weak && GCRHSAttr != GCAttr) ||
3156 (GCAttr == QualType::Strong && GCRHSAttr != GCAttr &&
3157 RHSCan->isPointerType() && !isObjCObjectPointerType(RHSCan) &&
3158 !isObjCIdStructType(RHSCan->getAsPointerType()->getPointeeType())))
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003159 return QualType();
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003160
Eli Friedman07d25872009-06-02 05:28:56 +00003161 LHS = QualType(cast<ExtQualType>(LHS.getDesugaredType())->getBaseType(),
3162 LHS.getCVRQualifiers());
3163 QualType Result = mergeTypes(LHS, RHS);
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003164 if (!Result.isNull()) {
3165 if (Result.getObjCGCAttr() == QualType::GCNone)
3166 Result = getObjCGCQualType(Result, GCAttr);
3167 else if (Result.getObjCGCAttr() != GCAttr)
3168 Result = QualType();
3169 }
Eli Friedman354e53d2009-06-02 07:45:37 +00003170 return Result;
Eli Friedman07d25872009-06-02 05:28:56 +00003171 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003172 }
3173
Eli Friedman4c721d32008-02-12 08:23:06 +00003174 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00003175 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
3176 LHSClass = Type::ConstantArray;
3177 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
3178 RHSClass = Type::ConstantArray;
Steve Naroffec0550f2007-10-15 20:41:53 +00003179
Nate Begeman213541a2008-04-18 23:10:10 +00003180 // Canonicalize ExtVector -> Vector.
3181 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
3182 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Chris Lattnera36a61f2008-04-07 05:43:21 +00003183
Chris Lattnerb0489812008-04-07 06:38:24 +00003184 // Consider qualified interfaces and interfaces the same.
3185 if (LHSClass == Type::ObjCQualifiedInterface) LHSClass = Type::ObjCInterface;
3186 if (RHSClass == Type::ObjCQualifiedInterface) RHSClass = Type::ObjCInterface;
Eli Friedman3d815e72008-08-22 00:56:42 +00003187
Chris Lattnera36a61f2008-04-07 05:43:21 +00003188 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00003189 if (LHSClass != RHSClass) {
Steve Naroff5fd659d2009-02-21 16:18:07 +00003190 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
3191 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
Fariborz Jahanianc8d2e772009-04-15 21:54:48 +00003192
Steve Naroffd824c9c2009-04-14 15:11:46 +00003193 // 'id' and 'Class' act sort of like void* for ObjC interfaces
3194 if (LHSIface && (isObjCIdStructType(RHS) || isObjCClassStructType(RHS)))
Steve Naroff5fd659d2009-02-21 16:18:07 +00003195 return LHS;
Steve Naroffd824c9c2009-04-14 15:11:46 +00003196 if (RHSIface && (isObjCIdStructType(LHS) || isObjCClassStructType(LHS)))
Steve Naroff5fd659d2009-02-21 16:18:07 +00003197 return RHS;
3198
Steve Naroffbc76dd02008-12-10 22:14:21 +00003199 // ID is compatible with all qualified id types.
3200 if (LHS->isObjCQualifiedIdType()) {
3201 if (const PointerType *PT = RHS->getAsPointerType()) {
3202 QualType pType = PT->getPointeeType();
Steve Naroffd824c9c2009-04-14 15:11:46 +00003203 if (isObjCIdStructType(pType) || isObjCClassStructType(pType))
Steve Naroffbc76dd02008-12-10 22:14:21 +00003204 return LHS;
3205 // FIXME: need to use ObjCQualifiedIdTypesAreCompatible(LHS, RHS, true).
3206 // Unfortunately, this API is part of Sema (which we don't have access
3207 // to. Need to refactor. The following check is insufficient, since we
3208 // need to make sure the class implements the protocol.
3209 if (pType->isObjCInterfaceType())
3210 return LHS;
3211 }
3212 }
3213 if (RHS->isObjCQualifiedIdType()) {
3214 if (const PointerType *PT = LHS->getAsPointerType()) {
3215 QualType pType = PT->getPointeeType();
Steve Naroffd824c9c2009-04-14 15:11:46 +00003216 if (isObjCIdStructType(pType) || isObjCClassStructType(pType))
Steve Naroffbc76dd02008-12-10 22:14:21 +00003217 return RHS;
3218 // FIXME: need to use ObjCQualifiedIdTypesAreCompatible(LHS, RHS, true).
3219 // Unfortunately, this API is part of Sema (which we don't have access
3220 // to. Need to refactor. The following check is insufficient, since we
3221 // need to make sure the class implements the protocol.
3222 if (pType->isObjCInterfaceType())
3223 return RHS;
3224 }
3225 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003226 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
3227 // a signed integer type, or an unsigned integer type.
Eli Friedman3d815e72008-08-22 00:56:42 +00003228 if (const EnumType* ETy = LHS->getAsEnumType()) {
3229 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
3230 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00003231 }
Eli Friedman3d815e72008-08-22 00:56:42 +00003232 if (const EnumType* ETy = RHS->getAsEnumType()) {
3233 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
3234 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00003235 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003236
Eli Friedman3d815e72008-08-22 00:56:42 +00003237 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00003238 }
Eli Friedman3d815e72008-08-22 00:56:42 +00003239
Steve Naroff4a746782008-01-09 22:43:08 +00003240 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00003241 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00003242#define TYPE(Class, Base)
3243#define ABSTRACT_TYPE(Class, Base)
3244#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3245#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3246#include "clang/AST/TypeNodes.def"
3247 assert(false && "Non-canonical and dependent types shouldn't get here");
3248 return QualType();
3249
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003250 case Type::LValueReference:
3251 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00003252 case Type::MemberPointer:
3253 assert(false && "C++ should never be in mergeTypes");
3254 return QualType();
3255
3256 case Type::IncompleteArray:
3257 case Type::VariableArray:
3258 case Type::FunctionProto:
3259 case Type::ExtVector:
3260 case Type::ObjCQualifiedInterface:
3261 assert(false && "Types are eliminated above");
3262 return QualType();
3263
Chris Lattner1adb8832008-01-14 05:45:46 +00003264 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00003265 {
3266 // Merge two pointer types, while trying to preserve typedef info
3267 QualType LHSPointee = LHS->getAsPointerType()->getPointeeType();
3268 QualType RHSPointee = RHS->getAsPointerType()->getPointeeType();
3269 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
3270 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00003271 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00003272 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00003273 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00003274 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00003275 return getPointerType(ResultType);
3276 }
Steve Naroffc0febd52008-12-10 17:49:55 +00003277 case Type::BlockPointer:
3278 {
3279 // Merge two block pointer types, while trying to preserve typedef info
3280 QualType LHSPointee = LHS->getAsBlockPointerType()->getPointeeType();
3281 QualType RHSPointee = RHS->getAsBlockPointerType()->getPointeeType();
3282 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
3283 if (ResultType.isNull()) return QualType();
3284 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
3285 return LHS;
3286 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
3287 return RHS;
3288 return getBlockPointerType(ResultType);
3289 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003290 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00003291 {
3292 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
3293 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
3294 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
3295 return QualType();
3296
3297 QualType LHSElem = getAsArrayType(LHS)->getElementType();
3298 QualType RHSElem = getAsArrayType(RHS)->getElementType();
3299 QualType ResultType = mergeTypes(LHSElem, RHSElem);
3300 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00003301 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3302 return LHS;
3303 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3304 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00003305 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
3306 ArrayType::ArraySizeModifier(), 0);
3307 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
3308 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00003309 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
3310 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00003311 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3312 return LHS;
3313 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3314 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00003315 if (LVAT) {
3316 // FIXME: This isn't correct! But tricky to implement because
3317 // the array's size has to be the size of LHS, but the type
3318 // has to be different.
3319 return LHS;
3320 }
3321 if (RVAT) {
3322 // FIXME: This isn't correct! But tricky to implement because
3323 // the array's size has to be the size of RHS, but the type
3324 // has to be different.
3325 return RHS;
3326 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00003327 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
3328 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Chris Lattner61710852008-10-05 17:34:18 +00003329 return getIncompleteArrayType(ResultType, ArrayType::ArraySizeModifier(),0);
Eli Friedman3d815e72008-08-22 00:56:42 +00003330 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003331 case Type::FunctionNoProto:
Eli Friedman3d815e72008-08-22 00:56:42 +00003332 return mergeFunctionTypes(LHS, RHS);
Douglas Gregor72564e72009-02-26 23:50:07 +00003333 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00003334 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00003335 // FIXME: Why are these compatible?
Steve Naroff389bf462009-02-12 17:52:19 +00003336 if (isObjCIdStructType(LHS) && isObjCClassStructType(RHS)) return LHS;
3337 if (isObjCClassStructType(LHS) && isObjCIdStructType(RHS)) return LHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00003338 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00003339 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00003340 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00003341 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00003342 case Type::Complex:
3343 // Distinct complex types are incompatible.
3344 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00003345 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003346 // FIXME: The merged type should be an ExtVector!
Eli Friedman3d815e72008-08-22 00:56:42 +00003347 if (areCompatVectorTypes(LHS->getAsVectorType(), RHS->getAsVectorType()))
3348 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00003349 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00003350 case Type::ObjCInterface: {
Steve Naroff5fd659d2009-02-21 16:18:07 +00003351 // Check if the interfaces are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003352 // FIXME: This should be type compatibility, e.g. whether
3353 // "LHS x; RHS x;" at global scope is legal.
Steve Naroff5fd659d2009-02-21 16:18:07 +00003354 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
3355 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
3356 if (LHSIface && RHSIface &&
3357 canAssignObjCInterfaces(LHSIface, RHSIface))
3358 return LHS;
3359
Eli Friedman3d815e72008-08-22 00:56:42 +00003360 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00003361 }
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003362 case Type::ObjCObjectPointer:
3363 // FIXME: finish
Steve Naroffbc76dd02008-12-10 22:14:21 +00003364 // Distinct qualified id's are not compatible.
3365 return QualType();
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003366 case Type::FixedWidthInt:
3367 // Distinct fixed-width integers are not compatible.
3368 return QualType();
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003369 case Type::ExtQual:
3370 // FIXME: ExtQual types can be compatible even if they're not
3371 // identical!
3372 return QualType();
3373 // First attempt at an implementation, but I'm not really sure it's
3374 // right...
3375#if 0
3376 ExtQualType* LQual = cast<ExtQualType>(LHSCan);
3377 ExtQualType* RQual = cast<ExtQualType>(RHSCan);
3378 if (LQual->getAddressSpace() != RQual->getAddressSpace() ||
3379 LQual->getObjCGCAttr() != RQual->getObjCGCAttr())
3380 return QualType();
3381 QualType LHSBase, RHSBase, ResultType, ResCanUnqual;
3382 LHSBase = QualType(LQual->getBaseType(), 0);
3383 RHSBase = QualType(RQual->getBaseType(), 0);
3384 ResultType = mergeTypes(LHSBase, RHSBase);
3385 if (ResultType.isNull()) return QualType();
3386 ResCanUnqual = getCanonicalType(ResultType).getUnqualifiedType();
3387 if (LHSCan.getUnqualifiedType() == ResCanUnqual)
3388 return LHS;
3389 if (RHSCan.getUnqualifiedType() == ResCanUnqual)
3390 return RHS;
3391 ResultType = getAddrSpaceQualType(ResultType, LQual->getAddressSpace());
3392 ResultType = getObjCGCQualType(ResultType, LQual->getObjCGCAttr());
3393 ResultType.setCVRQualifiers(LHSCan.getCVRQualifiers());
3394 return ResultType;
3395#endif
Douglas Gregor7532dc62009-03-30 22:58:21 +00003396
3397 case Type::TemplateSpecialization:
3398 assert(false && "Dependent types have no size");
3399 break;
Steve Naroffec0550f2007-10-15 20:41:53 +00003400 }
Douglas Gregor72564e72009-02-26 23:50:07 +00003401
3402 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00003403}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00003404
Chris Lattner5426bf62008-04-07 07:01:58 +00003405//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00003406// Integer Predicates
3407//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00003408
Eli Friedmanad74a752008-06-28 06:23:08 +00003409unsigned ASTContext::getIntWidth(QualType T) {
3410 if (T == BoolTy)
3411 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00003412 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T)) {
3413 return FWIT->getWidth();
3414 }
3415 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00003416 return (unsigned)getTypeSize(T);
3417}
3418
3419QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
3420 assert(T->isSignedIntegerType() && "Unexpected type");
3421 if (const EnumType* ETy = T->getAsEnumType())
3422 T = ETy->getDecl()->getIntegerType();
3423 const BuiltinType* BTy = T->getAsBuiltinType();
3424 assert (BTy && "Unexpected signed integer type");
3425 switch (BTy->getKind()) {
3426 case BuiltinType::Char_S:
3427 case BuiltinType::SChar:
3428 return UnsignedCharTy;
3429 case BuiltinType::Short:
3430 return UnsignedShortTy;
3431 case BuiltinType::Int:
3432 return UnsignedIntTy;
3433 case BuiltinType::Long:
3434 return UnsignedLongTy;
3435 case BuiltinType::LongLong:
3436 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00003437 case BuiltinType::Int128:
3438 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00003439 default:
3440 assert(0 && "Unexpected signed integer type");
3441 return QualType();
3442 }
3443}
3444
Douglas Gregor2cf26342009-04-09 22:27:44 +00003445ExternalASTSource::~ExternalASTSource() { }
3446
3447void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00003448
3449
3450//===----------------------------------------------------------------------===//
3451// Builtin Type Computation
3452//===----------------------------------------------------------------------===//
3453
3454/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
3455/// pointer over the consumed characters. This returns the resultant type.
3456static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
3457 ASTContext::GetBuiltinTypeError &Error,
3458 bool AllowTypeModifiers = true) {
3459 // Modifiers.
3460 int HowLong = 0;
3461 bool Signed = false, Unsigned = false;
3462
3463 // Read the modifiers first.
3464 bool Done = false;
3465 while (!Done) {
3466 switch (*Str++) {
3467 default: Done = true; --Str; break;
3468 case 'S':
3469 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
3470 assert(!Signed && "Can't use 'S' modifier multiple times!");
3471 Signed = true;
3472 break;
3473 case 'U':
3474 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
3475 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
3476 Unsigned = true;
3477 break;
3478 case 'L':
3479 assert(HowLong <= 2 && "Can't have LLLL modifier");
3480 ++HowLong;
3481 break;
3482 }
3483 }
3484
3485 QualType Type;
3486
3487 // Read the base type.
3488 switch (*Str++) {
3489 default: assert(0 && "Unknown builtin type letter!");
3490 case 'v':
3491 assert(HowLong == 0 && !Signed && !Unsigned &&
3492 "Bad modifiers used with 'v'!");
3493 Type = Context.VoidTy;
3494 break;
3495 case 'f':
3496 assert(HowLong == 0 && !Signed && !Unsigned &&
3497 "Bad modifiers used with 'f'!");
3498 Type = Context.FloatTy;
3499 break;
3500 case 'd':
3501 assert(HowLong < 2 && !Signed && !Unsigned &&
3502 "Bad modifiers used with 'd'!");
3503 if (HowLong)
3504 Type = Context.LongDoubleTy;
3505 else
3506 Type = Context.DoubleTy;
3507 break;
3508 case 's':
3509 assert(HowLong == 0 && "Bad modifiers used with 's'!");
3510 if (Unsigned)
3511 Type = Context.UnsignedShortTy;
3512 else
3513 Type = Context.ShortTy;
3514 break;
3515 case 'i':
3516 if (HowLong == 3)
3517 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
3518 else if (HowLong == 2)
3519 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
3520 else if (HowLong == 1)
3521 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
3522 else
3523 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
3524 break;
3525 case 'c':
3526 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
3527 if (Signed)
3528 Type = Context.SignedCharTy;
3529 else if (Unsigned)
3530 Type = Context.UnsignedCharTy;
3531 else
3532 Type = Context.CharTy;
3533 break;
3534 case 'b': // boolean
3535 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
3536 Type = Context.BoolTy;
3537 break;
3538 case 'z': // size_t.
3539 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
3540 Type = Context.getSizeType();
3541 break;
3542 case 'F':
3543 Type = Context.getCFConstantStringType();
3544 break;
3545 case 'a':
3546 Type = Context.getBuiltinVaListType();
3547 assert(!Type.isNull() && "builtin va list type not initialized!");
3548 break;
3549 case 'A':
3550 // This is a "reference" to a va_list; however, what exactly
3551 // this means depends on how va_list is defined. There are two
3552 // different kinds of va_list: ones passed by value, and ones
3553 // passed by reference. An example of a by-value va_list is
3554 // x86, where va_list is a char*. An example of by-ref va_list
3555 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
3556 // we want this argument to be a char*&; for x86-64, we want
3557 // it to be a __va_list_tag*.
3558 Type = Context.getBuiltinVaListType();
3559 assert(!Type.isNull() && "builtin va list type not initialized!");
3560 if (Type->isArrayType()) {
3561 Type = Context.getArrayDecayedType(Type);
3562 } else {
3563 Type = Context.getLValueReferenceType(Type);
3564 }
3565 break;
3566 case 'V': {
3567 char *End;
3568
3569 unsigned NumElements = strtoul(Str, &End, 10);
3570 assert(End != Str && "Missing vector size");
3571
3572 Str = End;
3573
3574 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
3575 Type = Context.getVectorType(ElementType, NumElements);
3576 break;
3577 }
3578 case 'P': {
3579 IdentifierInfo *II = &Context.Idents.get("FILE");
3580 DeclContext::lookup_result Lookup
3581 = Context.getTranslationUnitDecl()->lookup(Context, II);
3582 if (Lookup.first != Lookup.second && isa<TypeDecl>(*Lookup.first)) {
3583 Type = Context.getTypeDeclType(cast<TypeDecl>(*Lookup.first));
3584 break;
3585 }
3586 else {
3587 Error = ASTContext::GE_Missing_FILE;
3588 return QualType();
3589 }
3590 }
3591 }
3592
3593 if (!AllowTypeModifiers)
3594 return Type;
3595
3596 Done = false;
3597 while (!Done) {
3598 switch (*Str++) {
3599 default: Done = true; --Str; break;
3600 case '*':
3601 Type = Context.getPointerType(Type);
3602 break;
3603 case '&':
3604 Type = Context.getLValueReferenceType(Type);
3605 break;
3606 // FIXME: There's no way to have a built-in with an rvalue ref arg.
3607 case 'C':
3608 Type = Type.getQualifiedType(QualType::Const);
3609 break;
3610 }
3611 }
3612
3613 return Type;
3614}
3615
3616/// GetBuiltinType - Return the type for the specified builtin.
3617QualType ASTContext::GetBuiltinType(unsigned id,
3618 GetBuiltinTypeError &Error) {
3619 const char *TypeStr = BuiltinInfo.GetTypeString(id);
3620
3621 llvm::SmallVector<QualType, 8> ArgTypes;
3622
3623 Error = GE_None;
3624 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
3625 if (Error != GE_None)
3626 return QualType();
3627 while (TypeStr[0] && TypeStr[0] != '.') {
3628 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
3629 if (Error != GE_None)
3630 return QualType();
3631
3632 // Do array -> pointer decay. The builtin should use the decayed type.
3633 if (Ty->isArrayType())
3634 Ty = getArrayDecayedType(Ty);
3635
3636 ArgTypes.push_back(Ty);
3637 }
3638
3639 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
3640 "'.' should only occur at end of builtin type list!");
3641
3642 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
3643 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
3644 return getFunctionNoProtoType(ResType);
3645 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
3646 TypeStr[0] == '.', 0);
3647}