blob: 16a62fdd8cddcb5d1b08821d7b177ad47a358cf2 [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
Reid Spencer5f016e22007-07-11 17:01:13 +0000182 // C99 6.2.5p11.
183 FloatComplexTy = getComplexType(FloatTy);
184 DoubleComplexTy = getComplexType(DoubleTy);
185 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000186
Steve Naroff7e219e42007-10-15 14:41:52 +0000187 BuiltinVaListType = QualType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000188 ObjCIdType = QualType();
Steve Naroff7e219e42007-10-15 14:41:52 +0000189 IdStructType = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000190 ObjCClassType = QualType();
Anders Carlsson8baaca52007-10-31 02:53:19 +0000191 ClassStructType = 0;
192
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000193 ObjCConstantStringType = QualType();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000194
195 // void * type
196 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000197
198 // nullptr type (C++0x 2.14.7)
199 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000200}
201
Chris Lattner464175b2007-07-18 17:52:12 +0000202//===----------------------------------------------------------------------===//
203// Type Sizing and Analysis
204//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000205
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000206/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
207/// scalar floating point type.
208const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
209 const BuiltinType *BT = T->getAsBuiltinType();
210 assert(BT && "Not a floating point type!");
211 switch (BT->getKind()) {
212 default: assert(0 && "Not a floating point type!");
213 case BuiltinType::Float: return Target.getFloatFormat();
214 case BuiltinType::Double: return Target.getDoubleFormat();
215 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
216 }
217}
218
Chris Lattneraf707ab2009-01-24 21:53:27 +0000219/// getDeclAlign - Return a conservative estimate of the alignment of the
220/// specified decl. Note that bitfields do not have a valid alignment, so
221/// this method will assert on them.
Daniel Dunbarb7d08442009-02-17 22:16:19 +0000222unsigned ASTContext::getDeclAlignInBytes(const Decl *D) {
Eli Friedmandcdafb62009-02-22 02:56:25 +0000223 unsigned Align = Target.getCharWidth();
224
Douglas Gregor68584ed2009-06-18 16:11:24 +0000225 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>(*this))
Eli Friedmandcdafb62009-02-22 02:56:25 +0000226 Align = std::max(Align, AA->getAlignment());
227
Chris Lattneraf707ab2009-01-24 21:53:27 +0000228 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
229 QualType T = VD->getType();
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000230 if (const ReferenceType* RT = T->getAsReferenceType()) {
231 unsigned AS = RT->getPointeeType().getAddressSpace();
Anders Carlssonf0930232009-04-10 04:52:36 +0000232 Align = Target.getPointerAlign(AS);
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000233 } else if (!T->isIncompleteType() && !T->isFunctionType()) {
234 // Incomplete or function types default to 1.
Eli Friedmandcdafb62009-02-22 02:56:25 +0000235 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
236 T = cast<ArrayType>(T)->getElementType();
237
238 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
239 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000240 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000241
242 return Align / Target.getCharWidth();
Chris Lattneraf707ab2009-01-24 21:53:27 +0000243}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000244
Chris Lattnera7674d82007-07-13 22:13:22 +0000245/// getTypeSize - Return the size of the specified type, in bits. This method
246/// does not work on incomplete types.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000247std::pair<uint64_t, unsigned>
Daniel Dunbar1d751182008-11-08 05:48:37 +0000248ASTContext::getTypeInfo(const Type *T) {
Mike Stump5e301002009-02-27 18:32:39 +0000249 uint64_t Width=0;
250 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000251 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000252#define TYPE(Class, Base)
253#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000254#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000255#define DEPENDENT_TYPE(Class, Base) case Type::Class:
256#include "clang/AST/TypeNodes.def"
Douglas Gregor18857642009-04-30 17:32:17 +0000257 assert(false && "Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000258 break;
259
Chris Lattner692233e2007-07-13 22:27:08 +0000260 case Type::FunctionNoProto:
261 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000262 // GCC extension: alignof(function) = 32 bits
263 Width = 0;
264 Align = 32;
265 break;
266
Douglas Gregor72564e72009-02-26 23:50:07 +0000267 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000268 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000269 Width = 0;
270 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
271 break;
272
Steve Narofffb22d962007-08-30 01:06:46 +0000273 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000274 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Steve Narofffb22d962007-08-30 01:06:46 +0000275
Chris Lattner98be4942008-03-05 18:54:05 +0000276 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000277 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000278 Align = EltInfo.second;
279 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000280 }
Nate Begeman213541a2008-04-18 23:10:10 +0000281 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000282 case Type::Vector: {
283 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000284 getTypeInfo(cast<VectorType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000285 Width = EltInfo.first*cast<VectorType>(T)->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000286 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000287 // If the alignment is not a power of 2, round up to the next power of 2.
288 // This happens for non-power-of-2 length vectors.
289 // FIXME: this should probably be a target property.
290 Align = 1 << llvm::Log2_32_Ceil(Align);
Chris Lattner030d8842007-07-19 22:06:24 +0000291 break;
292 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000293
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000294 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000295 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000296 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000297 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000298 // GCC extension: alignof(void) = 8 bits.
299 Width = 0;
300 Align = 8;
301 break;
302
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000303 case BuiltinType::Bool:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000304 Width = Target.getBoolWidth();
305 Align = Target.getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000306 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000307 case BuiltinType::Char_S:
308 case BuiltinType::Char_U:
309 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000310 case BuiltinType::SChar:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000311 Width = Target.getCharWidth();
312 Align = Target.getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000313 break;
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000314 case BuiltinType::WChar:
315 Width = Target.getWCharWidth();
316 Align = Target.getWCharAlign();
317 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000318 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000319 case BuiltinType::Short:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000320 Width = Target.getShortWidth();
321 Align = Target.getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000322 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000323 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000324 case BuiltinType::Int:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000325 Width = Target.getIntWidth();
326 Align = Target.getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000327 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000328 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000329 case BuiltinType::Long:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000330 Width = Target.getLongWidth();
331 Align = Target.getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000332 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000333 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000334 case BuiltinType::LongLong:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000335 Width = Target.getLongLongWidth();
336 Align = Target.getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000337 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000338 case BuiltinType::Int128:
339 case BuiltinType::UInt128:
340 Width = 128;
341 Align = 128; // int128_t is 128-bit aligned on all targets.
342 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000343 case BuiltinType::Float:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000344 Width = Target.getFloatWidth();
345 Align = Target.getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000346 break;
347 case BuiltinType::Double:
Chris Lattner5426bf62008-04-07 07:01:58 +0000348 Width = Target.getDoubleWidth();
349 Align = Target.getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000350 break;
351 case BuiltinType::LongDouble:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000352 Width = Target.getLongDoubleWidth();
353 Align = Target.getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000354 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000355 case BuiltinType::NullPtr:
356 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
357 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000358 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000359 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000360 break;
Eli Friedmanf98aba32009-02-13 02:31:07 +0000361 case Type::FixedWidthInt:
362 // FIXME: This isn't precisely correct; the width/alignment should depend
363 // on the available types for the target
364 Width = cast<FixedWidthIntType>(T)->getWidth();
Chris Lattner736166b2009-02-15 21:20:13 +0000365 Width = std::max(llvm::NextPowerOf2(Width - 1), (uint64_t)8);
Eli Friedmanf98aba32009-02-13 02:31:07 +0000366 Align = Width;
367 break;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000368 case Type::ExtQual:
Chris Lattner98be4942008-03-05 18:54:05 +0000369 // FIXME: Pointers into different addr spaces could have different sizes and
370 // alignment requirements: getPointerInfo should take an AddrSpace.
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000371 return getTypeInfo(QualType(cast<ExtQualType>(T)->getBaseType(), 0));
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000372 case Type::ObjCObjectPointer:
Douglas Gregor72564e72009-02-26 23:50:07 +0000373 case Type::ObjCQualifiedInterface:
Chris Lattner5426bf62008-04-07 07:01:58 +0000374 Width = Target.getPointerWidth(0);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000375 Align = Target.getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000376 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000377 case Type::BlockPointer: {
378 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
379 Width = Target.getPointerWidth(AS);
380 Align = Target.getPointerAlign(AS);
381 break;
382 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000383 case Type::Pointer: {
384 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner5426bf62008-04-07 07:01:58 +0000385 Width = Target.getPointerWidth(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000386 Align = Target.getPointerAlign(AS);
387 break;
388 }
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000389 case Type::LValueReference:
390 case Type::RValueReference:
Chris Lattner7ab2ed82007-07-13 22:16:13 +0000391 // "When applied to a reference or a reference type, the result is the size
Chris Lattner5d2a6302007-07-18 18:26:58 +0000392 // of the referenced type." C++98 5.3.3p2: expr.sizeof.
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000393 // FIXME: This is wrong for struct layout: a reference in a struct has
394 // pointer size.
Chris Lattnerbdcd6372008-04-02 17:35:06 +0000395 return getTypeInfo(cast<ReferenceType>(T)->getPointeeType());
Sebastian Redlf30208a2009-01-24 21:16:55 +0000396 case Type::MemberPointer: {
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000397 // FIXME: This is ABI dependent. We use the Itanium C++ ABI.
398 // http://www.codesourcery.com/public/cxx-abi/abi.html#member-pointers
399 // If we ever want to support other ABIs this needs to be abstracted.
400
Sebastian Redlf30208a2009-01-24 21:16:55 +0000401 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000402 std::pair<uint64_t, unsigned> PtrDiffInfo =
403 getTypeInfo(getPointerDiffType());
404 Width = PtrDiffInfo.first;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000405 if (Pointee->isFunctionType())
406 Width *= 2;
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000407 Align = PtrDiffInfo.second;
408 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000409 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000410 case Type::Complex: {
411 // Complex types have the same alignment as their elements, but twice the
412 // size.
413 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000414 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000415 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000416 Align = EltInfo.second;
417 break;
418 }
Devang Patel44a3dde2008-06-04 21:54:36 +0000419 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000420 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000421 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
422 Width = Layout.getSize();
423 Align = Layout.getAlignment();
424 break;
425 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000426 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000427 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000428 const TagType *TT = cast<TagType>(T);
429
430 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner8389eab2008-08-09 21:35:13 +0000431 Width = 1;
432 Align = 1;
433 break;
434 }
435
Daniel Dunbar1d751182008-11-08 05:48:37 +0000436 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000437 return getTypeInfo(ET->getDecl()->getIntegerType());
438
Daniel Dunbar1d751182008-11-08 05:48:37 +0000439 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000440 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
441 Width = Layout.getSize();
442 Align = Layout.getAlignment();
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000443 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000444 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000445
Douglas Gregor18857642009-04-30 17:32:17 +0000446 case Type::Typedef: {
447 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregor68584ed2009-06-18 16:11:24 +0000448 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>(*this)) {
Douglas Gregor18857642009-04-30 17:32:17 +0000449 Align = Aligned->getAlignment();
450 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
451 } else
452 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregor7532dc62009-03-30 22:58:21 +0000453 break;
Chris Lattner71763312008-04-06 22:05:18 +0000454 }
Douglas Gregor18857642009-04-30 17:32:17 +0000455
456 case Type::TypeOfExpr:
457 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
458 .getTypePtr());
459
460 case Type::TypeOf:
461 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
462
Anders Carlsson395b4752009-06-24 19:06:50 +0000463 case Type::Decltype:
464 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
465 .getTypePtr());
466
Douglas Gregor18857642009-04-30 17:32:17 +0000467 case Type::QualifiedName:
468 return getTypeInfo(cast<QualifiedNameType>(T)->getNamedType().getTypePtr());
469
470 case Type::TemplateSpecialization:
471 assert(getCanonicalType(T) != T &&
472 "Cannot request the size of a dependent type");
473 // FIXME: this is likely to be wrong once we support template
474 // aliases, since a template alias could refer to a typedef that
475 // has an __aligned__ attribute on it.
476 return getTypeInfo(getCanonicalType(T));
477 }
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000478
Chris Lattner464175b2007-07-18 17:52:12 +0000479 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000480 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +0000481}
482
Chris Lattner34ebde42009-01-27 18:08:34 +0000483/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
484/// type for the current target in bits. This can be different than the ABI
485/// alignment in cases where it is beneficial for performance to overalign
486/// a data type.
487unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
488 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +0000489
490 // Double and long long should be naturally aligned if possible.
491 if (const ComplexType* CT = T->getAsComplexType())
492 T = CT->getElementType().getTypePtr();
493 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
494 T->isSpecificBuiltinType(BuiltinType::LongLong))
495 return std::max(ABIAlign, (unsigned)getTypeSize(T));
496
Chris Lattner34ebde42009-01-27 18:08:34 +0000497 return ABIAlign;
498}
499
500
Devang Patel8b277042008-06-04 21:22:16 +0000501/// LayoutField - Field layout.
502void ASTRecordLayout::LayoutField(const FieldDecl *FD, unsigned FieldNo,
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000503 bool IsUnion, unsigned StructPacking,
Devang Patel8b277042008-06-04 21:22:16 +0000504 ASTContext &Context) {
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000505 unsigned FieldPacking = StructPacking;
Devang Patel8b277042008-06-04 21:22:16 +0000506 uint64_t FieldOffset = IsUnion ? 0 : Size;
507 uint64_t FieldSize;
508 unsigned FieldAlign;
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000509
510 // FIXME: Should this override struct packing? Probably we want to
511 // take the minimum?
Douglas Gregor68584ed2009-06-18 16:11:24 +0000512 if (const PackedAttr *PA = FD->getAttr<PackedAttr>(Context))
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000513 FieldPacking = PA->getAlignment();
Devang Patel8b277042008-06-04 21:22:16 +0000514
515 if (const Expr *BitWidthExpr = FD->getBitWidth()) {
516 // TODO: Need to check this algorithm on other targets!
517 // (tested on Linux-X86)
Eli Friedman9a901bb2009-04-26 19:19:15 +0000518 FieldSize = BitWidthExpr->EvaluateAsInt(Context).getZExtValue();
Devang Patel8b277042008-06-04 21:22:16 +0000519
520 std::pair<uint64_t, unsigned> FieldInfo =
521 Context.getTypeInfo(FD->getType());
522 uint64_t TypeSize = FieldInfo.first;
523
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000524 // Determine the alignment of this bitfield. The packing
525 // attributes define a maximum and the alignment attribute defines
526 // a minimum.
527 // FIXME: What is the right behavior when the specified alignment
528 // is smaller than the specified packing?
Devang Patel8b277042008-06-04 21:22:16 +0000529 FieldAlign = FieldInfo.second;
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000530 if (FieldPacking)
531 FieldAlign = std::min(FieldAlign, FieldPacking);
Douglas Gregor68584ed2009-06-18 16:11:24 +0000532 if (const AlignedAttr *AA = FD->getAttr<AlignedAttr>(Context))
Devang Patel8b277042008-06-04 21:22:16 +0000533 FieldAlign = std::max(FieldAlign, AA->getAlignment());
534
535 // Check if we need to add padding to give the field the correct
536 // alignment.
537 if (FieldSize == 0 || (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize)
538 FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1);
539
540 // Padding members don't affect overall alignment
541 if (!FD->getIdentifier())
542 FieldAlign = 1;
543 } else {
Chris Lattner8389eab2008-08-09 21:35:13 +0000544 if (FD->getType()->isIncompleteArrayType()) {
545 // This is a flexible array member; we can't directly
Devang Patel8b277042008-06-04 21:22:16 +0000546 // query getTypeInfo about these, so we figure it out here.
547 // Flexible array members don't have any size, but they
548 // have to be aligned appropriately for their element type.
549 FieldSize = 0;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000550 const ArrayType* ATy = Context.getAsArrayType(FD->getType());
Devang Patel8b277042008-06-04 21:22:16 +0000551 FieldAlign = Context.getTypeAlign(ATy->getElementType());
Anders Carlsson2f1169f2009-04-10 05:31:15 +0000552 } else if (const ReferenceType *RT = FD->getType()->getAsReferenceType()) {
553 unsigned AS = RT->getPointeeType().getAddressSpace();
554 FieldSize = Context.Target.getPointerWidth(AS);
555 FieldAlign = Context.Target.getPointerAlign(AS);
Devang Patel8b277042008-06-04 21:22:16 +0000556 } else {
557 std::pair<uint64_t, unsigned> FieldInfo =
558 Context.getTypeInfo(FD->getType());
559 FieldSize = FieldInfo.first;
560 FieldAlign = FieldInfo.second;
561 }
562
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000563 // Determine the alignment of this bitfield. The packing
564 // attributes define a maximum and the alignment attribute defines
565 // a minimum. Additionally, the packing alignment must be at least
566 // a byte for non-bitfields.
567 //
568 // FIXME: What is the right behavior when the specified alignment
569 // is smaller than the specified packing?
570 if (FieldPacking)
571 FieldAlign = std::min(FieldAlign, std::max(8U, FieldPacking));
Douglas Gregor68584ed2009-06-18 16:11:24 +0000572 if (const AlignedAttr *AA = FD->getAttr<AlignedAttr>(Context))
Devang Patel8b277042008-06-04 21:22:16 +0000573 FieldAlign = std::max(FieldAlign, AA->getAlignment());
574
575 // Round up the current record size to the field's alignment boundary.
576 FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1);
577 }
578
579 // Place this field at the current location.
580 FieldOffsets[FieldNo] = FieldOffset;
581
582 // Reserve space for this field.
583 if (IsUnion) {
584 Size = std::max(Size, FieldSize);
585 } else {
586 Size = FieldOffset + FieldSize;
587 }
588
Daniel Dunbard6884a02009-05-04 05:16:21 +0000589 // Remember the next available offset.
590 NextOffset = Size;
591
Devang Patel8b277042008-06-04 21:22:16 +0000592 // Remember max struct/class alignment.
593 Alignment = std::max(Alignment, FieldAlign);
594}
595
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000596static void CollectLocalObjCIvars(ASTContext *Ctx,
597 const ObjCInterfaceDecl *OI,
598 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000599 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
600 E = OI->ivar_end(); I != E; ++I) {
Chris Lattnerf1690852009-03-31 08:48:01 +0000601 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000602 if (!IVDecl->isInvalidDecl())
603 Fields.push_back(cast<FieldDecl>(IVDecl));
604 }
605}
606
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000607void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
608 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
609 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
610 CollectObjCIvars(SuperClass, Fields);
611 CollectLocalObjCIvars(this, OI, Fields);
612}
613
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000614/// ShallowCollectObjCIvars -
615/// Collect all ivars, including those synthesized, in the current class.
616///
617void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
618 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars,
619 bool CollectSynthesized) {
620 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
621 E = OI->ivar_end(); I != E; ++I) {
622 Ivars.push_back(*I);
623 }
624 if (CollectSynthesized)
625 CollectSynthesizedIvars(OI, Ivars);
626}
627
Fariborz Jahanian98200742009-05-12 18:14:29 +0000628void ASTContext::CollectProtocolSynthesizedIvars(const ObjCProtocolDecl *PD,
629 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
630 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(*this),
631 E = PD->prop_end(*this); I != E; ++I)
632 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
633 Ivars.push_back(Ivar);
634
635 // Also look into nested protocols.
636 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
637 E = PD->protocol_end(); P != E; ++P)
638 CollectProtocolSynthesizedIvars(*P, Ivars);
639}
640
641/// CollectSynthesizedIvars -
642/// This routine collect synthesized ivars for the designated class.
643///
644void ASTContext::CollectSynthesizedIvars(const ObjCInterfaceDecl *OI,
645 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
646 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(*this),
647 E = OI->prop_end(*this); I != E; ++I) {
648 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
649 Ivars.push_back(Ivar);
650 }
651 // Also look into interface's protocol list for properties declared
652 // in the protocol and whose ivars are synthesized.
653 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
654 PE = OI->protocol_end(); P != PE; ++P) {
655 ObjCProtocolDecl *PD = (*P);
656 CollectProtocolSynthesizedIvars(PD, Ivars);
657 }
658}
659
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000660unsigned ASTContext::CountProtocolSynthesizedIvars(const ObjCProtocolDecl *PD) {
661 unsigned count = 0;
662 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(*this),
663 E = PD->prop_end(*this); I != E; ++I)
664 if ((*I)->getPropertyIvarDecl())
665 ++count;
666
667 // Also look into nested protocols.
668 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
669 E = PD->protocol_end(); P != E; ++P)
670 count += CountProtocolSynthesizedIvars(*P);
671 return count;
672}
673
674unsigned ASTContext::CountSynthesizedIvars(const ObjCInterfaceDecl *OI)
675{
676 unsigned count = 0;
677 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(*this),
678 E = OI->prop_end(*this); I != E; ++I) {
679 if ((*I)->getPropertyIvarDecl())
680 ++count;
681 }
682 // Also look into interface's protocol list for properties declared
683 // in the protocol and whose ivars are synthesized.
684 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
685 PE = OI->protocol_end(); P != PE; ++P) {
686 ObjCProtocolDecl *PD = (*P);
687 count += CountProtocolSynthesizedIvars(PD);
688 }
689 return count;
690}
691
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000692/// getInterfaceLayoutImpl - Get or compute information about the
693/// layout of the given interface.
694///
695/// \param Impl - If given, also include the layout of the interface's
696/// implementation. This may differ by including synthesized ivars.
Devang Patel44a3dde2008-06-04 21:54:36 +0000697const ASTRecordLayout &
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000698ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
699 const ObjCImplementationDecl *Impl) {
Daniel Dunbar532d4da2009-05-03 13:15:50 +0000700 assert(!D->isForwardDecl() && "Invalid interface decl!");
701
Devang Patel44a3dde2008-06-04 21:54:36 +0000702 // Look up this layout, if already laid out, return what we have.
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000703 ObjCContainerDecl *Key =
704 Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
705 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
706 return *Entry;
Devang Patel44a3dde2008-06-04 21:54:36 +0000707
Daniel Dunbar453addb2009-05-03 11:16:44 +0000708 unsigned FieldCount = D->ivar_size();
709 // Add in synthesized ivar count if laying out an implementation.
710 if (Impl) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000711 unsigned SynthCount = CountSynthesizedIvars(D);
712 FieldCount += SynthCount;
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000713 // If there aren't any sythesized ivars then reuse the interface
Daniel Dunbar453addb2009-05-03 11:16:44 +0000714 // entry. Note we can't cache this because we simply free all
715 // entries later; however we shouldn't look up implementations
716 // frequently.
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000717 if (SynthCount == 0)
Daniel Dunbar453addb2009-05-03 11:16:44 +0000718 return getObjCLayout(D, 0);
719 }
720
Devang Patel6a5a34c2008-06-06 02:14:01 +0000721 ASTRecordLayout *NewEntry = NULL;
Devang Patel6a5a34c2008-06-06 02:14:01 +0000722 if (ObjCInterfaceDecl *SD = D->getSuperClass()) {
Devang Patel6a5a34c2008-06-06 02:14:01 +0000723 const ASTRecordLayout &SL = getASTObjCInterfaceLayout(SD);
724 unsigned Alignment = SL.getAlignment();
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000725
Daniel Dunbar913af352009-05-07 21:58:26 +0000726 // We start laying out ivars not at the end of the superclass
727 // structure, but at the next byte following the last field.
728 uint64_t Size = llvm::RoundUpToAlignment(SL.NextOffset, 8);
Daniel Dunbard6884a02009-05-04 05:16:21 +0000729
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000730 ObjCLayouts[Key] = NewEntry = new ASTRecordLayout(Size, Alignment);
Devang Patel6a5a34c2008-06-06 02:14:01 +0000731 NewEntry->InitializeLayout(FieldCount);
Devang Patel6a5a34c2008-06-06 02:14:01 +0000732 } else {
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000733 ObjCLayouts[Key] = NewEntry = new ASTRecordLayout();
Devang Patel6a5a34c2008-06-06 02:14:01 +0000734 NewEntry->InitializeLayout(FieldCount);
735 }
Devang Patel44a3dde2008-06-04 21:54:36 +0000736
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000737 unsigned StructPacking = 0;
Douglas Gregor68584ed2009-06-18 16:11:24 +0000738 if (const PackedAttr *PA = D->getAttr<PackedAttr>(*this))
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000739 StructPacking = PA->getAlignment();
Devang Patel44a3dde2008-06-04 21:54:36 +0000740
Douglas Gregor68584ed2009-06-18 16:11:24 +0000741 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>(*this))
Devang Patel44a3dde2008-06-04 21:54:36 +0000742 NewEntry->SetAlignment(std::max(NewEntry->getAlignment(),
743 AA->getAlignment()));
744
745 // Layout each ivar sequentially.
746 unsigned i = 0;
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000747 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
748 ShallowCollectObjCIvars(D, Ivars, Impl);
749 for (unsigned k = 0, e = Ivars.size(); k != e; ++k)
750 NewEntry->LayoutField(Ivars[k], i++, false, StructPacking, *this);
751
Devang Patel44a3dde2008-06-04 21:54:36 +0000752 // Finally, round the size of the total struct up to the alignment of the
753 // struct itself.
754 NewEntry->FinalizeLayout();
755 return *NewEntry;
756}
757
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000758const ASTRecordLayout &
759ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
760 return getObjCLayout(D, 0);
761}
762
763const ASTRecordLayout &
764ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
765 return getObjCLayout(D->getClassInterface(), D);
766}
767
Devang Patel88a981b2007-11-01 19:11:01 +0000768/// getASTRecordLayout - Get or compute information about the layout of the
Chris Lattner464175b2007-07-18 17:52:12 +0000769/// specified record (struct/union/class), which indicates its size and field
770/// position information.
Chris Lattner98be4942008-03-05 18:54:05 +0000771const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +0000772 D = D->getDefinition(*this);
773 assert(D && "Cannot get layout of forward declarations!");
Eli Friedman4bd998b2008-05-30 09:31:38 +0000774
Chris Lattner464175b2007-07-18 17:52:12 +0000775 // Look up this layout, if already laid out, return what we have.
Devang Patel88a981b2007-11-01 19:11:01 +0000776 const ASTRecordLayout *&Entry = ASTRecordLayouts[D];
Chris Lattner464175b2007-07-18 17:52:12 +0000777 if (Entry) return *Entry;
Eli Friedman4bd998b2008-05-30 09:31:38 +0000778
Devang Patel88a981b2007-11-01 19:11:01 +0000779 // Allocate and assign into ASTRecordLayouts here. The "Entry" reference can
780 // be invalidated (dangle) if the ASTRecordLayouts hashtable is inserted into.
781 ASTRecordLayout *NewEntry = new ASTRecordLayout();
Chris Lattner464175b2007-07-18 17:52:12 +0000782 Entry = NewEntry;
Eli Friedman4bd998b2008-05-30 09:31:38 +0000783
Douglas Gregore267ff32008-12-11 20:41:00 +0000784 // FIXME: Avoid linear walk through the fields, if possible.
Douglas Gregor6ab35242009-04-09 21:40:53 +0000785 NewEntry->InitializeLayout(std::distance(D->field_begin(*this),
786 D->field_end(*this)));
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000787 bool IsUnion = D->isUnion();
Chris Lattner464175b2007-07-18 17:52:12 +0000788
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000789 unsigned StructPacking = 0;
Douglas Gregor68584ed2009-06-18 16:11:24 +0000790 if (const PackedAttr *PA = D->getAttr<PackedAttr>(*this))
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000791 StructPacking = PA->getAlignment();
792
Douglas Gregor68584ed2009-06-18 16:11:24 +0000793 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>(*this))
Devang Patel8b277042008-06-04 21:22:16 +0000794 NewEntry->SetAlignment(std::max(NewEntry->getAlignment(),
795 AA->getAlignment()));
Anders Carlsson8af226a2008-02-18 07:13:09 +0000796
Eli Friedman4bd998b2008-05-30 09:31:38 +0000797 // Layout each field, for now, just sequentially, respecting alignment. In
798 // the future, this will need to be tweakable by targets.
Douglas Gregor44b43212008-12-11 16:49:14 +0000799 unsigned FieldIdx = 0;
Douglas Gregor6ab35242009-04-09 21:40:53 +0000800 for (RecordDecl::field_iterator Field = D->field_begin(*this),
801 FieldEnd = D->field_end(*this);
Douglas Gregor44b43212008-12-11 16:49:14 +0000802 Field != FieldEnd; (void)++Field, ++FieldIdx)
803 NewEntry->LayoutField(*Field, FieldIdx, IsUnion, StructPacking, *this);
Eli Friedman4bd998b2008-05-30 09:31:38 +0000804
805 // Finally, round the size of the total struct up to the alignment of the
806 // struct itself.
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000807 NewEntry->FinalizeLayout(getLangOptions().CPlusPlus);
Chris Lattner5d2a6302007-07-18 18:26:58 +0000808 return *NewEntry;
Chris Lattner464175b2007-07-18 17:52:12 +0000809}
810
Chris Lattnera7674d82007-07-13 22:13:22 +0000811//===----------------------------------------------------------------------===//
812// Type creation/memoization methods
813//===----------------------------------------------------------------------===//
814
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000815QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerf52ab252008-04-06 22:59:24 +0000816 QualType CanT = getCanonicalType(T);
817 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +0000818 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +0000819
820 // If we are composing extended qualifiers together, merge together into one
821 // ExtQualType node.
822 unsigned CVRQuals = T.getCVRQualifiers();
823 QualType::GCAttrTypes GCAttr = QualType::GCNone;
824 Type *TypeNode = T.getTypePtr();
Chris Lattnerf46699c2008-02-20 20:55:12 +0000825
Chris Lattnerb7d25532009-02-18 22:53:11 +0000826 if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
827 // If this type already has an address space specified, it cannot get
828 // another one.
829 assert(EQT->getAddressSpace() == 0 &&
830 "Type cannot be in multiple addr spaces!");
831 GCAttr = EQT->getObjCGCAttr();
832 TypeNode = EQT->getBaseType();
833 }
Chris Lattnerf46699c2008-02-20 20:55:12 +0000834
Chris Lattnerb7d25532009-02-18 22:53:11 +0000835 // Check if we've already instantiated this type.
Christopher Lambebb97e92008-02-04 02:31:56 +0000836 llvm::FoldingSetNodeID ID;
Chris Lattnerb7d25532009-02-18 22:53:11 +0000837 ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
Christopher Lambebb97e92008-02-04 02:31:56 +0000838 void *InsertPos = 0;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000839 if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattnerb7d25532009-02-18 22:53:11 +0000840 return QualType(EXTQy, CVRQuals);
841
Christopher Lambebb97e92008-02-04 02:31:56 +0000842 // If the base type isn't canonical, this won't be a canonical type either,
843 // so fill in the canonical type field.
844 QualType Canonical;
Chris Lattnerb7d25532009-02-18 22:53:11 +0000845 if (!TypeNode->isCanonical()) {
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000846 Canonical = getAddrSpaceQualType(CanT, AddressSpace);
Christopher Lambebb97e92008-02-04 02:31:56 +0000847
Chris Lattnerb7d25532009-02-18 22:53:11 +0000848 // Update InsertPos, the previous call could have invalidated it.
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000849 ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +0000850 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Christopher Lambebb97e92008-02-04 02:31:56 +0000851 }
Chris Lattnerb7d25532009-02-18 22:53:11 +0000852 ExtQualType *New =
853 new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000854 ExtQualTypes.InsertNode(New, InsertPos);
Christopher Lambebb97e92008-02-04 02:31:56 +0000855 Types.push_back(New);
Chris Lattnerb7d25532009-02-18 22:53:11 +0000856 return QualType(New, CVRQuals);
Christopher Lambebb97e92008-02-04 02:31:56 +0000857}
858
Chris Lattnerb7d25532009-02-18 22:53:11 +0000859QualType ASTContext::getObjCGCQualType(QualType T,
860 QualType::GCAttrTypes GCAttr) {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000861 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +0000862 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000863 return T;
864
Fariborz Jahanian4027cd12009-06-03 17:15:17 +0000865 if (T->isPointerType()) {
866 QualType Pointee = T->getAsPointerType()->getPointeeType();
867 if (Pointee->isPointerType()) {
868 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
869 return getPointerType(ResultType);
870 }
871 }
Chris Lattnerb7d25532009-02-18 22:53:11 +0000872 // If we are composing extended qualifiers together, merge together into one
873 // ExtQualType node.
874 unsigned CVRQuals = T.getCVRQualifiers();
875 Type *TypeNode = T.getTypePtr();
876 unsigned AddressSpace = 0;
877
878 if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
879 // If this type already has an address space specified, it cannot get
880 // another one.
881 assert(EQT->getObjCGCAttr() == QualType::GCNone &&
882 "Type cannot be in multiple addr spaces!");
883 AddressSpace = EQT->getAddressSpace();
884 TypeNode = EQT->getBaseType();
885 }
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000886
887 // Check if we've already instantiated an gc qual'd type of this type.
888 llvm::FoldingSetNodeID ID;
Chris Lattnerb7d25532009-02-18 22:53:11 +0000889 ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000890 void *InsertPos = 0;
891 if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattnerb7d25532009-02-18 22:53:11 +0000892 return QualType(EXTQy, CVRQuals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000893
894 // If the base type isn't canonical, this won't be a canonical type either,
895 // so fill in the canonical type field.
Eli Friedman5a61f0e2009-02-27 23:04:43 +0000896 // FIXME: Isn't this also not canonical if the base type is a array
897 // or pointer type? I can't find any documentation for objc_gc, though...
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000898 QualType Canonical;
899 if (!T->isCanonical()) {
Chris Lattnerb7d25532009-02-18 22:53:11 +0000900 Canonical = getObjCGCQualType(CanT, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000901
Chris Lattnerb7d25532009-02-18 22:53:11 +0000902 // Update InsertPos, the previous call could have invalidated it.
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000903 ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
904 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
905 }
Chris Lattnerb7d25532009-02-18 22:53:11 +0000906 ExtQualType *New =
907 new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000908 ExtQualTypes.InsertNode(New, InsertPos);
909 Types.push_back(New);
Chris Lattnerb7d25532009-02-18 22:53:11 +0000910 return QualType(New, CVRQuals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000911}
Chris Lattnera7674d82007-07-13 22:13:22 +0000912
Reid Spencer5f016e22007-07-11 17:01:13 +0000913/// getComplexType - Return the uniqued reference to the type for a complex
914/// number with the specified element type.
915QualType ASTContext::getComplexType(QualType T) {
916 // Unique pointers, to guarantee there is only one pointer of a particular
917 // structure.
918 llvm::FoldingSetNodeID ID;
919 ComplexType::Profile(ID, T);
920
921 void *InsertPos = 0;
922 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
923 return QualType(CT, 0);
924
925 // If the pointee type isn't canonical, this won't be a canonical type either,
926 // so fill in the canonical type field.
927 QualType Canonical;
928 if (!T->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +0000929 Canonical = getComplexType(getCanonicalType(T));
Reid Spencer5f016e22007-07-11 17:01:13 +0000930
931 // Get the new insert position for the node we care about.
932 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +0000933 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +0000934 }
Steve Narofff83820b2009-01-27 22:08:43 +0000935 ComplexType *New = new (*this,8) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +0000936 Types.push_back(New);
937 ComplexTypes.InsertNode(New, InsertPos);
938 return QualType(New, 0);
939}
940
Eli Friedmanf98aba32009-02-13 02:31:07 +0000941QualType ASTContext::getFixedWidthIntType(unsigned Width, bool Signed) {
942 llvm::DenseMap<unsigned, FixedWidthIntType*> &Map = Signed ?
943 SignedFixedWidthIntTypes : UnsignedFixedWidthIntTypes;
944 FixedWidthIntType *&Entry = Map[Width];
945 if (!Entry)
946 Entry = new FixedWidthIntType(Width, Signed);
947 return QualType(Entry, 0);
948}
Reid Spencer5f016e22007-07-11 17:01:13 +0000949
950/// getPointerType - Return the uniqued reference to the type for a pointer to
951/// the specified type.
952QualType ASTContext::getPointerType(QualType T) {
953 // Unique pointers, to guarantee there is only one pointer of a particular
954 // structure.
955 llvm::FoldingSetNodeID ID;
956 PointerType::Profile(ID, T);
957
958 void *InsertPos = 0;
959 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
960 return QualType(PT, 0);
961
962 // If the pointee type isn't canonical, this won't be a canonical type either,
963 // so fill in the canonical type field.
964 QualType Canonical;
965 if (!T->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +0000966 Canonical = getPointerType(getCanonicalType(T));
Reid Spencer5f016e22007-07-11 17:01:13 +0000967
968 // Get the new insert position for the node we care about.
969 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +0000970 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +0000971 }
Steve Narofff83820b2009-01-27 22:08:43 +0000972 PointerType *New = new (*this,8) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +0000973 Types.push_back(New);
974 PointerTypes.InsertNode(New, InsertPos);
975 return QualType(New, 0);
976}
977
Steve Naroff5618bd42008-08-27 16:04:49 +0000978/// getBlockPointerType - Return the uniqued reference to the type for
979/// a pointer to the specified block.
980QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff296e8d52008-08-28 19:20:44 +0000981 assert(T->isFunctionType() && "block of function types only");
982 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +0000983 // structure.
984 llvm::FoldingSetNodeID ID;
985 BlockPointerType::Profile(ID, T);
986
987 void *InsertPos = 0;
988 if (BlockPointerType *PT =
989 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
990 return QualType(PT, 0);
991
Steve Naroff296e8d52008-08-28 19:20:44 +0000992 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +0000993 // type either so fill in the canonical type field.
994 QualType Canonical;
995 if (!T->isCanonical()) {
996 Canonical = getBlockPointerType(getCanonicalType(T));
997
998 // Get the new insert position for the node we care about.
999 BlockPointerType *NewIP =
1000 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001001 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001002 }
Steve Narofff83820b2009-01-27 22:08:43 +00001003 BlockPointerType *New = new (*this,8) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001004 Types.push_back(New);
1005 BlockPointerTypes.InsertNode(New, InsertPos);
1006 return QualType(New, 0);
1007}
1008
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001009/// getLValueReferenceType - Return the uniqued reference to the type for an
1010/// lvalue reference to the specified type.
1011QualType ASTContext::getLValueReferenceType(QualType T) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001012 // Unique pointers, to guarantee there is only one pointer of a particular
1013 // structure.
1014 llvm::FoldingSetNodeID ID;
1015 ReferenceType::Profile(ID, T);
1016
1017 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001018 if (LValueReferenceType *RT =
1019 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001020 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001021
Reid Spencer5f016e22007-07-11 17:01:13 +00001022 // If the referencee type isn't canonical, this won't be a canonical type
1023 // either, so fill in the canonical type field.
1024 QualType Canonical;
1025 if (!T->isCanonical()) {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001026 Canonical = getLValueReferenceType(getCanonicalType(T));
1027
Reid Spencer5f016e22007-07-11 17:01:13 +00001028 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001029 LValueReferenceType *NewIP =
1030 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001031 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001032 }
1033
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001034 LValueReferenceType *New = new (*this,8) LValueReferenceType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001035 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001036 LValueReferenceTypes.InsertNode(New, InsertPos);
1037 return QualType(New, 0);
1038}
1039
1040/// getRValueReferenceType - Return the uniqued reference to the type for an
1041/// rvalue reference to the specified type.
1042QualType ASTContext::getRValueReferenceType(QualType T) {
1043 // Unique pointers, to guarantee there is only one pointer of a particular
1044 // structure.
1045 llvm::FoldingSetNodeID ID;
1046 ReferenceType::Profile(ID, T);
1047
1048 void *InsertPos = 0;
1049 if (RValueReferenceType *RT =
1050 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1051 return QualType(RT, 0);
1052
1053 // If the referencee type isn't canonical, this won't be a canonical type
1054 // either, so fill in the canonical type field.
1055 QualType Canonical;
1056 if (!T->isCanonical()) {
1057 Canonical = getRValueReferenceType(getCanonicalType(T));
1058
1059 // Get the new insert position for the node we care about.
1060 RValueReferenceType *NewIP =
1061 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1062 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1063 }
1064
1065 RValueReferenceType *New = new (*this,8) RValueReferenceType(T, Canonical);
1066 Types.push_back(New);
1067 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001068 return QualType(New, 0);
1069}
1070
Sebastian Redlf30208a2009-01-24 21:16:55 +00001071/// getMemberPointerType - Return the uniqued reference to the type for a
1072/// member pointer to the specified type, in the specified class.
1073QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls)
1074{
1075 // Unique pointers, to guarantee there is only one pointer of a particular
1076 // structure.
1077 llvm::FoldingSetNodeID ID;
1078 MemberPointerType::Profile(ID, T, Cls);
1079
1080 void *InsertPos = 0;
1081 if (MemberPointerType *PT =
1082 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1083 return QualType(PT, 0);
1084
1085 // If the pointee or class type isn't canonical, this won't be a canonical
1086 // type either, so fill in the canonical type field.
1087 QualType Canonical;
1088 if (!T->isCanonical()) {
1089 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1090
1091 // Get the new insert position for the node we care about.
1092 MemberPointerType *NewIP =
1093 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1094 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1095 }
Steve Narofff83820b2009-01-27 22:08:43 +00001096 MemberPointerType *New = new (*this,8) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001097 Types.push_back(New);
1098 MemberPointerTypes.InsertNode(New, InsertPos);
1099 return QualType(New, 0);
1100}
1101
Steve Narofffb22d962007-08-30 01:06:46 +00001102/// getConstantArrayType - Return the unique reference to the type for an
1103/// array of the specified element type.
1104QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001105 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001106 ArrayType::ArraySizeModifier ASM,
1107 unsigned EltTypeQuals) {
Eli Friedman587cbdf2009-05-29 20:17:55 +00001108 assert((EltTy->isDependentType() || EltTy->isConstantSizeType()) &&
1109 "Constant array of VLAs is illegal!");
1110
Chris Lattner38aeec72009-05-13 04:12:56 +00001111 // Convert the array size into a canonical width matching the pointer size for
1112 // the target.
1113 llvm::APInt ArySize(ArySizeIn);
1114 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1115
Reid Spencer5f016e22007-07-11 17:01:13 +00001116 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001117 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001118
1119 void *InsertPos = 0;
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001120 if (ConstantArrayType *ATP =
1121 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001122 return QualType(ATP, 0);
1123
1124 // If the element type isn't canonical, this won't be a canonical type either,
1125 // so fill in the canonical type field.
1126 QualType Canonical;
1127 if (!EltTy->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001128 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroffc9406122007-08-30 18:10:14 +00001129 ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001130 // Get the new insert position for the node we care about.
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001131 ConstantArrayType *NewIP =
1132 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001133 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001134 }
1135
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001136 ConstantArrayType *New =
Steve Narofff83820b2009-01-27 22:08:43 +00001137 new(*this,8)ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001138 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001139 Types.push_back(New);
1140 return QualType(New, 0);
1141}
1142
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001143/// getVariableArrayType - Returns a non-unique reference to the type for a
1144/// variable array of the specified element type.
Steve Naroffc9406122007-08-30 18:10:14 +00001145QualType ASTContext::getVariableArrayType(QualType EltTy, Expr *NumElts,
1146 ArrayType::ArraySizeModifier ASM,
1147 unsigned EltTypeQuals) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001148 // Since we don't unique expressions, it isn't possible to unique VLA's
1149 // that have an expression provided for their size.
1150
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001151 VariableArrayType *New =
Steve Narofff83820b2009-01-27 22:08:43 +00001152 new(*this,8)VariableArrayType(EltTy,QualType(), NumElts, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001153
1154 VariableArrayTypes.push_back(New);
1155 Types.push_back(New);
1156 return QualType(New, 0);
1157}
1158
Douglas Gregor898574e2008-12-05 23:32:09 +00001159/// getDependentSizedArrayType - Returns a non-unique reference to
1160/// the type for a dependently-sized array of the specified element
1161/// type. FIXME: We will need these to be uniqued, or at least
1162/// comparable, at some point.
1163QualType ASTContext::getDependentSizedArrayType(QualType EltTy, Expr *NumElts,
1164 ArrayType::ArraySizeModifier ASM,
1165 unsigned EltTypeQuals) {
1166 assert((NumElts->isTypeDependent() || NumElts->isValueDependent()) &&
1167 "Size must be type- or value-dependent!");
1168
1169 // Since we don't unique expressions, it isn't possible to unique
1170 // dependently-sized array types.
1171
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001172 DependentSizedArrayType *New =
Steve Narofff83820b2009-01-27 22:08:43 +00001173 new (*this,8) DependentSizedArrayType(EltTy, QualType(), NumElts,
1174 ASM, EltTypeQuals);
Douglas Gregor898574e2008-12-05 23:32:09 +00001175
1176 DependentSizedArrayTypes.push_back(New);
1177 Types.push_back(New);
1178 return QualType(New, 0);
1179}
1180
Eli Friedmanc5773c42008-02-15 18:16:39 +00001181QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1182 ArrayType::ArraySizeModifier ASM,
1183 unsigned EltTypeQuals) {
1184 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001185 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001186
1187 void *InsertPos = 0;
1188 if (IncompleteArrayType *ATP =
1189 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1190 return QualType(ATP, 0);
1191
1192 // If the element type isn't canonical, this won't be a canonical type
1193 // either, so fill in the canonical type field.
1194 QualType Canonical;
1195
1196 if (!EltTy->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001197 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001198 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001199
1200 // Get the new insert position for the node we care about.
1201 IncompleteArrayType *NewIP =
1202 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001203 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001204 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001205
Steve Narofff83820b2009-01-27 22:08:43 +00001206 IncompleteArrayType *New = new (*this,8) IncompleteArrayType(EltTy, Canonical,
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001207 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001208
1209 IncompleteArrayTypes.InsertNode(New, InsertPos);
1210 Types.push_back(New);
1211 return QualType(New, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001212}
1213
Steve Naroff73322922007-07-18 18:00:27 +00001214/// getVectorType - Return the unique reference to a vector type of
1215/// the specified element type and size. VectorType must be a built-in type.
1216QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001217 BuiltinType *baseType;
1218
Chris Lattnerf52ab252008-04-06 22:59:24 +00001219 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff73322922007-07-18 18:00:27 +00001220 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Reid Spencer5f016e22007-07-11 17:01:13 +00001221
1222 // Check if we've already instantiated a vector of this type.
1223 llvm::FoldingSetNodeID ID;
Steve Naroff73322922007-07-18 18:00:27 +00001224 VectorType::Profile(ID, vecType, NumElts, Type::Vector);
Reid Spencer5f016e22007-07-11 17:01:13 +00001225 void *InsertPos = 0;
1226 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1227 return QualType(VTP, 0);
1228
1229 // If the element type isn't canonical, this won't be a canonical type either,
1230 // so fill in the canonical type field.
1231 QualType Canonical;
1232 if (!vecType->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001233 Canonical = getVectorType(getCanonicalType(vecType), NumElts);
Reid Spencer5f016e22007-07-11 17:01:13 +00001234
1235 // Get the new insert position for the node we care about.
1236 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001237 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001238 }
Steve Narofff83820b2009-01-27 22:08:43 +00001239 VectorType *New = new (*this,8) VectorType(vecType, NumElts, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001240 VectorTypes.InsertNode(New, InsertPos);
1241 Types.push_back(New);
1242 return QualType(New, 0);
1243}
1244
Nate Begeman213541a2008-04-18 23:10:10 +00001245/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001246/// the specified element type and size. VectorType must be a built-in type.
Nate Begeman213541a2008-04-18 23:10:10 +00001247QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff73322922007-07-18 18:00:27 +00001248 BuiltinType *baseType;
1249
Chris Lattnerf52ab252008-04-06 22:59:24 +00001250 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begeman213541a2008-04-18 23:10:10 +00001251 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Steve Naroff73322922007-07-18 18:00:27 +00001252
1253 // Check if we've already instantiated a vector of this type.
1254 llvm::FoldingSetNodeID ID;
Nate Begeman213541a2008-04-18 23:10:10 +00001255 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector);
Steve Naroff73322922007-07-18 18:00:27 +00001256 void *InsertPos = 0;
1257 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1258 return QualType(VTP, 0);
1259
1260 // If the element type isn't canonical, this won't be a canonical type either,
1261 // so fill in the canonical type field.
1262 QualType Canonical;
1263 if (!vecType->isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001264 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Steve Naroff73322922007-07-18 18:00:27 +00001265
1266 // Get the new insert position for the node we care about.
1267 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001268 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001269 }
Steve Narofff83820b2009-01-27 22:08:43 +00001270 ExtVectorType *New = new (*this,8) ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001271 VectorTypes.InsertNode(New, InsertPos);
1272 Types.push_back(New);
1273 return QualType(New, 0);
1274}
1275
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001276QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
1277 Expr *SizeExpr,
1278 SourceLocation AttrLoc) {
1279 DependentSizedExtVectorType *New =
1280 new (*this,8) DependentSizedExtVectorType(vecType, QualType(),
1281 SizeExpr, AttrLoc);
1282
1283 DependentSizedExtVectorTypes.push_back(New);
1284 Types.push_back(New);
1285 return QualType(New, 0);
1286}
1287
Douglas Gregor72564e72009-02-26 23:50:07 +00001288/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001289///
Douglas Gregor72564e72009-02-26 23:50:07 +00001290QualType ASTContext::getFunctionNoProtoType(QualType ResultTy) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001291 // Unique functions, to guarantee there is only one function of a particular
1292 // structure.
1293 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001294 FunctionNoProtoType::Profile(ID, ResultTy);
Reid Spencer5f016e22007-07-11 17:01:13 +00001295
1296 void *InsertPos = 0;
Douglas Gregor72564e72009-02-26 23:50:07 +00001297 if (FunctionNoProtoType *FT =
1298 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001299 return QualType(FT, 0);
1300
1301 QualType Canonical;
1302 if (!ResultTy->isCanonical()) {
Douglas Gregor72564e72009-02-26 23:50:07 +00001303 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy));
Reid Spencer5f016e22007-07-11 17:01:13 +00001304
1305 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001306 FunctionNoProtoType *NewIP =
1307 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001308 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001309 }
1310
Douglas Gregor72564e72009-02-26 23:50:07 +00001311 FunctionNoProtoType *New =new(*this,8)FunctionNoProtoType(ResultTy,Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001312 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001313 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001314 return QualType(New, 0);
1315}
1316
1317/// getFunctionType - Return a normal function type with a typed argument
1318/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner61710852008-10-05 17:34:18 +00001319QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001320 unsigned NumArgs, bool isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001321 unsigned TypeQuals, bool hasExceptionSpec,
1322 bool hasAnyExceptionSpec, unsigned NumExs,
1323 const QualType *ExArray) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001324 // Unique functions, to guarantee there is only one function of a particular
1325 // structure.
1326 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001327 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001328 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
1329 NumExs, ExArray);
Reid Spencer5f016e22007-07-11 17:01:13 +00001330
1331 void *InsertPos = 0;
Douglas Gregor72564e72009-02-26 23:50:07 +00001332 if (FunctionProtoType *FTP =
1333 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001334 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001335
1336 // Determine whether the type being created is already canonical or not.
Reid Spencer5f016e22007-07-11 17:01:13 +00001337 bool isCanonical = ResultTy->isCanonical();
Sebastian Redl465226e2009-05-27 22:11:52 +00001338 if (hasExceptionSpec)
1339 isCanonical = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001340 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
1341 if (!ArgArray[i]->isCanonical())
1342 isCanonical = false;
1343
1344 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001345 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001346 QualType Canonical;
1347 if (!isCanonical) {
1348 llvm::SmallVector<QualType, 16> CanonicalArgs;
1349 CanonicalArgs.reserve(NumArgs);
1350 for (unsigned i = 0; i != NumArgs; ++i)
Chris Lattnerf52ab252008-04-06 22:59:24 +00001351 CanonicalArgs.push_back(getCanonicalType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001352
Chris Lattnerf52ab252008-04-06 22:59:24 +00001353 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001354 CanonicalArgs.data(), NumArgs,
Sebastian Redlbfa2fcb2009-05-06 23:27:55 +00001355 isVariadic, TypeQuals);
Sebastian Redl465226e2009-05-27 22:11:52 +00001356
Reid Spencer5f016e22007-07-11 17:01:13 +00001357 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001358 FunctionProtoType *NewIP =
1359 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001360 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001361 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001362
Douglas Gregor72564e72009-02-26 23:50:07 +00001363 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001364 // for two variable size arrays (for parameter and exception types) at the
1365 // end of them.
Douglas Gregor72564e72009-02-26 23:50:07 +00001366 FunctionProtoType *FTP =
Sebastian Redl465226e2009-05-27 22:11:52 +00001367 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1368 NumArgs*sizeof(QualType) +
1369 NumExs*sizeof(QualType), 8);
Douglas Gregor72564e72009-02-26 23:50:07 +00001370 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001371 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
1372 ExArray, NumExs, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001373 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001374 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001375 return QualType(FTP, 0);
1376}
1377
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001378/// getTypeDeclType - Return the unique reference to the type for the
1379/// specified type declaration.
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001380QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001381 assert(Decl && "Passed null for Decl param");
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001382 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1383
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001384 if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001385 return getTypedefType(Typedef);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001386 else if (isa<TemplateTypeParmDecl>(Decl)) {
1387 assert(false && "Template type parameter types are always available.");
1388 } else if (ObjCInterfaceDecl *ObjCInterface = dyn_cast<ObjCInterfaceDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001389 return getObjCInterfaceType(ObjCInterface);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001390
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001391 if (RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001392 if (PrevDecl)
1393 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001394 else
1395 Decl->TypeForDecl = new (*this,8) RecordType(Record);
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001396 }
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001397 else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
1398 if (PrevDecl)
1399 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001400 else
1401 Decl->TypeForDecl = new (*this,8) EnumType(Enum);
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001402 }
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001403 else
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001404 assert(false && "TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001405
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001406 if (!PrevDecl) Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001407 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001408}
1409
Reid Spencer5f016e22007-07-11 17:01:13 +00001410/// getTypedefType - Return the unique reference to the type for the
1411/// specified typename decl.
1412QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
1413 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1414
Chris Lattnerf52ab252008-04-06 22:59:24 +00001415 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
Douglas Gregor72564e72009-02-26 23:50:07 +00001416 Decl->TypeForDecl = new(*this,8) TypedefType(Type::Typedef, Decl, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001417 Types.push_back(Decl->TypeForDecl);
1418 return QualType(Decl->TypeForDecl, 0);
1419}
1420
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001421/// getObjCInterfaceType - Return the unique reference to the type for the
Steve Naroff3536b442007-09-06 21:24:23 +00001422/// specified ObjC interface decl.
Daniel Dunbar3b3a4582009-04-22 04:34:53 +00001423QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) {
Steve Naroff3536b442007-09-06 21:24:23 +00001424 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1425
Daniel Dunbar3b3a4582009-04-22 04:34:53 +00001426 ObjCInterfaceDecl *OID = const_cast<ObjCInterfaceDecl*>(Decl);
1427 Decl->TypeForDecl = new(*this,8) ObjCInterfaceType(Type::ObjCInterface, OID);
Steve Naroff3536b442007-09-06 21:24:23 +00001428 Types.push_back(Decl->TypeForDecl);
1429 return QualType(Decl->TypeForDecl, 0);
1430}
1431
Douglas Gregorfab9d672009-02-05 23:33:38 +00001432/// \brief Retrieve the template type parameter type for a template
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001433/// parameter or parameter pack with the given depth, index, and (optionally)
1434/// name.
Douglas Gregorfab9d672009-02-05 23:33:38 +00001435QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001436 bool ParameterPack,
Douglas Gregorfab9d672009-02-05 23:33:38 +00001437 IdentifierInfo *Name) {
1438 llvm::FoldingSetNodeID ID;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001439 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001440 void *InsertPos = 0;
1441 TemplateTypeParmType *TypeParm
1442 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1443
1444 if (TypeParm)
1445 return QualType(TypeParm, 0);
1446
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001447 if (Name) {
1448 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
1449 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, ParameterPack,
1450 Name, Canon);
1451 } else
1452 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001453
1454 Types.push_back(TypeParm);
1455 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1456
1457 return QualType(TypeParm, 0);
1458}
1459
Douglas Gregor55f6b142009-02-09 18:46:07 +00001460QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00001461ASTContext::getTemplateSpecializationType(TemplateName Template,
1462 const TemplateArgument *Args,
1463 unsigned NumArgs,
1464 QualType Canon) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001465 if (!Canon.isNull())
1466 Canon = getCanonicalType(Canon);
Douglas Gregorfc705b82009-02-26 22:19:44 +00001467
Douglas Gregor55f6b142009-02-09 18:46:07 +00001468 llvm::FoldingSetNodeID ID;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001469 TemplateSpecializationType::Profile(ID, Template, Args, NumArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001470
Douglas Gregor55f6b142009-02-09 18:46:07 +00001471 void *InsertPos = 0;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001472 TemplateSpecializationType *Spec
1473 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001474
1475 if (Spec)
1476 return QualType(Spec, 0);
1477
Douglas Gregor7532dc62009-03-30 22:58:21 +00001478 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00001479 sizeof(TemplateArgument) * NumArgs),
1480 8);
Douglas Gregor7532dc62009-03-30 22:58:21 +00001481 Spec = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, Canon);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001482 Types.push_back(Spec);
Douglas Gregor7532dc62009-03-30 22:58:21 +00001483 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001484
1485 return QualType(Spec, 0);
1486}
1487
Douglas Gregore4e5b052009-03-19 00:18:19 +00001488QualType
Douglas Gregorab452ba2009-03-26 23:50:42 +00001489ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
Douglas Gregore4e5b052009-03-19 00:18:19 +00001490 QualType NamedType) {
1491 llvm::FoldingSetNodeID ID;
Douglas Gregorab452ba2009-03-26 23:50:42 +00001492 QualifiedNameType::Profile(ID, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001493
1494 void *InsertPos = 0;
1495 QualifiedNameType *T
1496 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
1497 if (T)
1498 return QualType(T, 0);
1499
Douglas Gregorab452ba2009-03-26 23:50:42 +00001500 T = new (*this) QualifiedNameType(NNS, NamedType,
1501 getCanonicalType(NamedType));
Douglas Gregore4e5b052009-03-19 00:18:19 +00001502 Types.push_back(T);
1503 QualifiedNameTypes.InsertNode(T, InsertPos);
1504 return QualType(T, 0);
1505}
1506
Douglas Gregord57959a2009-03-27 23:10:48 +00001507QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1508 const IdentifierInfo *Name,
1509 QualType Canon) {
1510 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1511
1512 if (Canon.isNull()) {
1513 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1514 if (CanonNNS != NNS)
1515 Canon = getTypenameType(CanonNNS, Name);
1516 }
1517
1518 llvm::FoldingSetNodeID ID;
1519 TypenameType::Profile(ID, NNS, Name);
1520
1521 void *InsertPos = 0;
1522 TypenameType *T
1523 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1524 if (T)
1525 return QualType(T, 0);
1526
1527 T = new (*this) TypenameType(NNS, Name, Canon);
1528 Types.push_back(T);
1529 TypenameTypes.InsertNode(T, InsertPos);
1530 return QualType(T, 0);
1531}
1532
Douglas Gregor17343172009-04-01 00:28:59 +00001533QualType
1534ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1535 const TemplateSpecializationType *TemplateId,
1536 QualType Canon) {
1537 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1538
1539 if (Canon.isNull()) {
1540 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1541 QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
1542 if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
1543 const TemplateSpecializationType *CanonTemplateId
1544 = CanonType->getAsTemplateSpecializationType();
1545 assert(CanonTemplateId &&
1546 "Canonical type must also be a template specialization type");
1547 Canon = getTypenameType(CanonNNS, CanonTemplateId);
1548 }
1549 }
1550
1551 llvm::FoldingSetNodeID ID;
1552 TypenameType::Profile(ID, NNS, TemplateId);
1553
1554 void *InsertPos = 0;
1555 TypenameType *T
1556 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1557 if (T)
1558 return QualType(T, 0);
1559
1560 T = new (*this) TypenameType(NNS, TemplateId, Canon);
1561 Types.push_back(T);
1562 TypenameTypes.InsertNode(T, InsertPos);
1563 return QualType(T, 0);
1564}
1565
Chris Lattner88cb27a2008-04-07 04:56:42 +00001566/// CmpProtocolNames - Comparison predicate for sorting protocols
1567/// alphabetically.
1568static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
1569 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001570 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00001571}
1572
1573static void SortAndUniqueProtocols(ObjCProtocolDecl **&Protocols,
1574 unsigned &NumProtocols) {
1575 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
1576
1577 // Sort protocols, keyed by name.
1578 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
1579
1580 // Remove duplicates.
1581 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
1582 NumProtocols = ProtocolsEnd-Protocols;
1583}
1584
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001585/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
1586/// the given interface decl and the conforming protocol list.
1587QualType ASTContext::getObjCObjectPointerType(ObjCInterfaceDecl *Decl,
1588 ObjCProtocolDecl **Protocols,
1589 unsigned NumProtocols) {
1590 // Sort the protocol list alphabetically to canonicalize it.
1591 if (NumProtocols)
1592 SortAndUniqueProtocols(Protocols, NumProtocols);
1593
1594 llvm::FoldingSetNodeID ID;
1595 ObjCObjectPointerType::Profile(ID, Decl, Protocols, NumProtocols);
1596
1597 void *InsertPos = 0;
1598 if (ObjCObjectPointerType *QT =
1599 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1600 return QualType(QT, 0);
1601
1602 // No Match;
1603 ObjCObjectPointerType *QType =
1604 new (*this,8) ObjCObjectPointerType(Decl, Protocols, NumProtocols);
1605
1606 Types.push_back(QType);
1607 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
1608 return QualType(QType, 0);
1609}
Chris Lattner88cb27a2008-04-07 04:56:42 +00001610
Chris Lattner065f0d72008-04-07 04:44:08 +00001611/// getObjCQualifiedInterfaceType - Return a ObjCQualifiedInterfaceType type for
1612/// the given interface decl and the conforming protocol list.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001613QualType ASTContext::getObjCQualifiedInterfaceType(ObjCInterfaceDecl *Decl,
1614 ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
Chris Lattner88cb27a2008-04-07 04:56:42 +00001615 // Sort the protocol list alphabetically to canonicalize it.
1616 SortAndUniqueProtocols(Protocols, NumProtocols);
1617
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001618 llvm::FoldingSetNodeID ID;
Chris Lattnerb0489812008-04-07 06:38:24 +00001619 ObjCQualifiedInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001620
1621 void *InsertPos = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001622 if (ObjCQualifiedInterfaceType *QT =
1623 ObjCQualifiedInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001624 return QualType(QT, 0);
1625
1626 // No Match;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001627 ObjCQualifiedInterfaceType *QType =
Steve Narofff83820b2009-01-27 22:08:43 +00001628 new (*this,8) ObjCQualifiedInterfaceType(Decl, Protocols, NumProtocols);
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001629
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001630 Types.push_back(QType);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001631 ObjCQualifiedInterfaceTypes.InsertNode(QType, InsertPos);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001632 return QualType(QType, 0);
1633}
1634
Chris Lattner88cb27a2008-04-07 04:56:42 +00001635/// getObjCQualifiedIdType - Return an ObjCQualifiedIdType for the 'id' decl
1636/// and the conforming protocol list.
Chris Lattner62f5f7f2008-07-26 00:46:50 +00001637QualType ASTContext::getObjCQualifiedIdType(ObjCProtocolDecl **Protocols,
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001638 unsigned NumProtocols) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001639 return getObjCObjectPointerType(0, Protocols, NumProtocols);
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001640}
1641
Douglas Gregor72564e72009-02-26 23:50:07 +00001642/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
1643/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00001644/// multiple declarations that refer to "typeof(x)" all contain different
1645/// DeclRefExpr's. This doesn't effect the type checker, since it operates
1646/// on canonical type's (which are always unique).
Douglas Gregor72564e72009-02-26 23:50:07 +00001647QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001648 QualType Canonical = getCanonicalType(tofExpr->getType());
Douglas Gregor72564e72009-02-26 23:50:07 +00001649 TypeOfExprType *toe = new (*this,8) TypeOfExprType(tofExpr, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00001650 Types.push_back(toe);
1651 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00001652}
1653
Steve Naroff9752f252007-08-01 18:02:17 +00001654/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
1655/// TypeOfType AST's. The only motivation to unique these nodes would be
1656/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
1657/// an issue. This doesn't effect the type checker, since it operates
1658/// on canonical type's (which are always unique).
Steve Naroffd1861fd2007-07-31 12:34:36 +00001659QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001660 QualType Canonical = getCanonicalType(tofType);
Steve Narofff83820b2009-01-27 22:08:43 +00001661 TypeOfType *tot = new (*this,8) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00001662 Types.push_back(tot);
1663 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00001664}
1665
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00001666/// getDecltypeForExpr - Given an expr, will return the decltype for that
1667/// expression, according to the rules in C++0x [dcl.type.simple]p4
1668static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00001669 if (e->isTypeDependent())
1670 return Context.DependentTy;
1671
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00001672 // If e is an id expression or a class member access, decltype(e) is defined
1673 // as the type of the entity named by e.
1674 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
1675 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
1676 return VD->getType();
1677 }
1678 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
1679 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
1680 return FD->getType();
1681 }
1682 // If e is a function call or an invocation of an overloaded operator,
1683 // (parentheses around e are ignored), decltype(e) is defined as the
1684 // return type of that function.
1685 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
1686 return CE->getCallReturnType();
1687
1688 QualType T = e->getType();
1689
1690 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
1691 // defined as T&, otherwise decltype(e) is defined as T.
1692 if (e->isLvalue(Context) == Expr::LV_Valid)
1693 T = Context.getLValueReferenceType(T);
1694
1695 return T;
1696}
1697
Anders Carlsson395b4752009-06-24 19:06:50 +00001698/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
1699/// DecltypeType AST's. The only motivation to unique these nodes would be
1700/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
1701/// an issue. This doesn't effect the type checker, since it operates
1702/// on canonical type's (which are always unique).
1703QualType ASTContext::getDecltypeType(Expr *e) {
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00001704 QualType T = getDecltypeForExpr(e, *this);
1705 DecltypeType *dt = new (*this, 8) DecltypeType(e, getCanonicalType(T));
Anders Carlsson395b4752009-06-24 19:06:50 +00001706 Types.push_back(dt);
1707 return QualType(dt, 0);
1708}
1709
Reid Spencer5f016e22007-07-11 17:01:13 +00001710/// getTagDeclType - Return the unique reference to the type for the
1711/// specified TagDecl (struct/union/class/enum) decl.
1712QualType ASTContext::getTagDeclType(TagDecl *Decl) {
Ted Kremenekd778f882007-11-26 21:16:01 +00001713 assert (Decl);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001714 return getTypeDeclType(Decl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001715}
1716
1717/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
1718/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
1719/// needs to agree with the definition in <stddef.h>.
1720QualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00001721 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00001722}
1723
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00001724/// getSignedWCharType - Return the type of "signed wchar_t".
1725/// Used when in C++, as a GCC extension.
1726QualType ASTContext::getSignedWCharType() const {
1727 // FIXME: derive from "Target" ?
1728 return WCharTy;
1729}
1730
1731/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
1732/// Used when in C++, as a GCC extension.
1733QualType ASTContext::getUnsignedWCharType() const {
1734 // FIXME: derive from "Target" ?
1735 return UnsignedIntTy;
1736}
1737
Chris Lattner8b9023b2007-07-13 03:05:23 +00001738/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
1739/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
1740QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00001741 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00001742}
1743
Chris Lattnere6327742008-04-02 05:18:44 +00001744//===----------------------------------------------------------------------===//
1745// Type Operators
1746//===----------------------------------------------------------------------===//
1747
Chris Lattner77c96472008-04-06 22:41:35 +00001748/// getCanonicalType - Return the canonical (structural) type corresponding to
1749/// the specified potentially non-canonical type. The non-canonical version
1750/// of a type may have many "decorated" versions of types. Decorators can
1751/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
1752/// to be free of any of these, allowing two canonical types to be compared
1753/// for exact equality with a simple pointer comparison.
1754QualType ASTContext::getCanonicalType(QualType T) {
1755 QualType CanType = T.getTypePtr()->getCanonicalTypeInternal();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001756
1757 // If the result has type qualifiers, make sure to canonicalize them as well.
1758 unsigned TypeQuals = T.getCVRQualifiers() | CanType.getCVRQualifiers();
1759 if (TypeQuals == 0) return CanType;
1760
1761 // If the type qualifiers are on an array type, get the canonical type of the
1762 // array with the qualifiers applied to the element type.
1763 ArrayType *AT = dyn_cast<ArrayType>(CanType);
1764 if (!AT)
1765 return CanType.getQualifiedType(TypeQuals);
1766
1767 // Get the canonical version of the element with the extra qualifiers on it.
1768 // This can recursively sink qualifiers through multiple levels of arrays.
1769 QualType NewEltTy=AT->getElementType().getWithAdditionalQualifiers(TypeQuals);
1770 NewEltTy = getCanonicalType(NewEltTy);
1771
1772 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
1773 return getConstantArrayType(NewEltTy, CAT->getSize(),CAT->getSizeModifier(),
1774 CAT->getIndexTypeQualifier());
1775 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
1776 return getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
1777 IAT->getIndexTypeQualifier());
1778
Douglas Gregor898574e2008-12-05 23:32:09 +00001779 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
1780 return getDependentSizedArrayType(NewEltTy, DSAT->getSizeExpr(),
1781 DSAT->getSizeModifier(),
1782 DSAT->getIndexTypeQualifier());
1783
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001784 VariableArrayType *VAT = cast<VariableArrayType>(AT);
1785 return getVariableArrayType(NewEltTy, VAT->getSizeExpr(),
1786 VAT->getSizeModifier(),
1787 VAT->getIndexTypeQualifier());
1788}
1789
Douglas Gregor7da97d02009-05-10 22:57:19 +00001790Decl *ASTContext::getCanonicalDecl(Decl *D) {
Douglas Gregorc4ccf012009-05-10 22:59:12 +00001791 if (!D)
1792 return 0;
1793
Douglas Gregor7da97d02009-05-10 22:57:19 +00001794 if (TagDecl *Tag = dyn_cast<TagDecl>(D)) {
1795 QualType T = getTagDeclType(Tag);
1796 return cast<TagDecl>(cast<TagType>(T.getTypePtr()->CanonicalType)
1797 ->getDecl());
1798 }
1799
1800 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(D)) {
1801 while (Template->getPreviousDeclaration())
1802 Template = Template->getPreviousDeclaration();
1803 return Template;
1804 }
1805
1806 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
1807 while (Function->getPreviousDeclaration())
1808 Function = Function->getPreviousDeclaration();
1809 return const_cast<FunctionDecl *>(Function);
1810 }
1811
1812 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
1813 while (Var->getPreviousDeclaration())
1814 Var = Var->getPreviousDeclaration();
1815 return const_cast<VarDecl *>(Var);
1816 }
1817
1818 return D;
1819}
1820
Douglas Gregor25a3ef72009-05-07 06:41:52 +00001821TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
1822 // If this template name refers to a template, the canonical
1823 // template name merely stores the template itself.
1824 if (TemplateDecl *Template = Name.getAsTemplateDecl())
Douglas Gregor7da97d02009-05-10 22:57:19 +00001825 return TemplateName(cast<TemplateDecl>(getCanonicalDecl(Template)));
Douglas Gregor25a3ef72009-05-07 06:41:52 +00001826
1827 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
1828 assert(DTN && "Non-dependent template names must refer to template decls.");
1829 return DTN->CanonicalTemplateName;
1830}
1831
Douglas Gregord57959a2009-03-27 23:10:48 +00001832NestedNameSpecifier *
1833ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
1834 if (!NNS)
1835 return 0;
1836
1837 switch (NNS->getKind()) {
1838 case NestedNameSpecifier::Identifier:
1839 // Canonicalize the prefix but keep the identifier the same.
1840 return NestedNameSpecifier::Create(*this,
1841 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
1842 NNS->getAsIdentifier());
1843
1844 case NestedNameSpecifier::Namespace:
1845 // A namespace is canonical; build a nested-name-specifier with
1846 // this namespace and no prefix.
1847 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
1848
1849 case NestedNameSpecifier::TypeSpec:
1850 case NestedNameSpecifier::TypeSpecWithTemplate: {
1851 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
1852 NestedNameSpecifier *Prefix = 0;
1853
1854 // FIXME: This isn't the right check!
1855 if (T->isDependentType())
1856 Prefix = getCanonicalNestedNameSpecifier(NNS->getPrefix());
1857
1858 return NestedNameSpecifier::Create(*this, Prefix,
1859 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
1860 T.getTypePtr());
1861 }
1862
1863 case NestedNameSpecifier::Global:
1864 // The global specifier is canonical and unique.
1865 return NNS;
1866 }
1867
1868 // Required to silence a GCC warning
1869 return 0;
1870}
1871
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001872
1873const ArrayType *ASTContext::getAsArrayType(QualType T) {
1874 // Handle the non-qualified case efficiently.
1875 if (T.getCVRQualifiers() == 0) {
1876 // Handle the common positive case fast.
1877 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
1878 return AT;
1879 }
1880
1881 // Handle the common negative case fast, ignoring CVR qualifiers.
1882 QualType CType = T->getCanonicalTypeInternal();
1883
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001884 // Make sure to look through type qualifiers (like ExtQuals) for the negative
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001885 // test.
1886 if (!isa<ArrayType>(CType) &&
1887 !isa<ArrayType>(CType.getUnqualifiedType()))
1888 return 0;
1889
1890 // Apply any CVR qualifiers from the array type to the element type. This
1891 // implements C99 6.7.3p8: "If the specification of an array type includes
1892 // any type qualifiers, the element type is so qualified, not the array type."
1893
1894 // If we get here, we either have type qualifiers on the type, or we have
1895 // sugar such as a typedef in the way. If we have type qualifiers on the type
1896 // we must propagate them down into the elemeng type.
1897 unsigned CVRQuals = T.getCVRQualifiers();
1898 unsigned AddrSpace = 0;
1899 Type *Ty = T.getTypePtr();
1900
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001901 // Rip through ExtQualType's and typedefs to get to a concrete type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001902 while (1) {
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001903 if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(Ty)) {
1904 AddrSpace = EXTQT->getAddressSpace();
1905 Ty = EXTQT->getBaseType();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001906 } else {
1907 T = Ty->getDesugaredType();
1908 if (T.getTypePtr() == Ty && T.getCVRQualifiers() == 0)
1909 break;
1910 CVRQuals |= T.getCVRQualifiers();
1911 Ty = T.getTypePtr();
1912 }
1913 }
1914
1915 // If we have a simple case, just return now.
1916 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
1917 if (ATy == 0 || (AddrSpace == 0 && CVRQuals == 0))
1918 return ATy;
1919
1920 // Otherwise, we have an array and we have qualifiers on it. Push the
1921 // qualifiers into the array element type and return a new array type.
1922 // Get the canonical version of the element with the extra qualifiers on it.
1923 // This can recursively sink qualifiers through multiple levels of arrays.
1924 QualType NewEltTy = ATy->getElementType();
1925 if (AddrSpace)
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001926 NewEltTy = getAddrSpaceQualType(NewEltTy, AddrSpace);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001927 NewEltTy = NewEltTy.getWithAdditionalQualifiers(CVRQuals);
1928
1929 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
1930 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
1931 CAT->getSizeModifier(),
1932 CAT->getIndexTypeQualifier()));
1933 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
1934 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
1935 IAT->getSizeModifier(),
1936 IAT->getIndexTypeQualifier()));
Douglas Gregor898574e2008-12-05 23:32:09 +00001937
Douglas Gregor898574e2008-12-05 23:32:09 +00001938 if (const DependentSizedArrayType *DSAT
1939 = dyn_cast<DependentSizedArrayType>(ATy))
1940 return cast<ArrayType>(
1941 getDependentSizedArrayType(NewEltTy,
1942 DSAT->getSizeExpr(),
1943 DSAT->getSizeModifier(),
1944 DSAT->getIndexTypeQualifier()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001945
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001946 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
1947 return cast<ArrayType>(getVariableArrayType(NewEltTy, VAT->getSizeExpr(),
1948 VAT->getSizeModifier(),
1949 VAT->getIndexTypeQualifier()));
Chris Lattner77c96472008-04-06 22:41:35 +00001950}
1951
1952
Chris Lattnere6327742008-04-02 05:18:44 +00001953/// getArrayDecayedType - Return the properly qualified result of decaying the
1954/// specified array type to a pointer. This operation is non-trivial when
1955/// handling typedefs etc. The canonical type of "T" must be an array type,
1956/// this returns a pointer to a properly qualified element of the array.
1957///
1958/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
1959QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001960 // Get the element type with 'getAsArrayType' so that we don't lose any
1961 // typedefs in the element type of the array. This also handles propagation
1962 // of type qualifiers from the array type into the element type if present
1963 // (C99 6.7.3p8).
1964 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
1965 assert(PrettyArrayType && "Not an array type!");
Chris Lattnere6327742008-04-02 05:18:44 +00001966
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001967 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00001968
1969 // int x[restrict 4] -> int *restrict
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001970 return PtrTy.getQualifiedType(PrettyArrayType->getIndexTypeQualifier());
Chris Lattnere6327742008-04-02 05:18:44 +00001971}
1972
Daniel Dunbard786f6a2009-01-05 22:14:37 +00001973QualType ASTContext::getBaseElementType(const VariableArrayType *VAT) {
Anders Carlsson6183a992008-12-21 03:44:36 +00001974 QualType ElemTy = VAT->getElementType();
1975
1976 if (const VariableArrayType *VAT = getAsVariableArrayType(ElemTy))
1977 return getBaseElementType(VAT);
1978
1979 return ElemTy;
1980}
1981
Reid Spencer5f016e22007-07-11 17:01:13 +00001982/// getFloatingRank - Return a relative rank for floating point types.
1983/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00001984static FloatingRank getFloatingRank(QualType T) {
Christopher Lambebb97e92008-02-04 02:31:56 +00001985 if (const ComplexType *CT = T->getAsComplexType())
Reid Spencer5f016e22007-07-11 17:01:13 +00001986 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00001987
Daniel Dunbard786f6a2009-01-05 22:14:37 +00001988 assert(T->getAsBuiltinType() && "getFloatingRank(): not a floating type");
Christopher Lambebb97e92008-02-04 02:31:56 +00001989 switch (T->getAsBuiltinType()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00001990 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00001991 case BuiltinType::Float: return FloatRank;
1992 case BuiltinType::Double: return DoubleRank;
1993 case BuiltinType::LongDouble: return LongDoubleRank;
1994 }
1995}
1996
Steve Naroff716c7302007-08-27 01:41:48 +00001997/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
1998/// point or a complex type (based on typeDomain/typeSize).
1999/// 'typeDomain' is a real floating point or complex type.
2000/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00002001QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2002 QualType Domain) const {
2003 FloatingRank EltRank = getFloatingRank(Size);
2004 if (Domain->isComplexType()) {
2005 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00002006 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00002007 case FloatRank: return FloatComplexTy;
2008 case DoubleRank: return DoubleComplexTy;
2009 case LongDoubleRank: return LongDoubleComplexTy;
2010 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002011 }
Chris Lattner1361b112008-04-06 23:58:54 +00002012
2013 assert(Domain->isRealFloatingType() && "Unknown domain!");
2014 switch (EltRank) {
2015 default: assert(0 && "getFloatingRank(): illegal value for rank");
2016 case FloatRank: return FloatTy;
2017 case DoubleRank: return DoubleTy;
2018 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00002019 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002020}
2021
Chris Lattner7cfeb082008-04-06 23:55:33 +00002022/// getFloatingTypeOrder - Compare the rank of the two specified floating
2023/// point types, ignoring the domain of the type (i.e. 'double' ==
2024/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
2025/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00002026int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2027 FloatingRank LHSR = getFloatingRank(LHS);
2028 FloatingRank RHSR = getFloatingRank(RHS);
2029
2030 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002031 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00002032 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002033 return 1;
2034 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002035}
2036
Chris Lattnerf52ab252008-04-06 22:59:24 +00002037/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2038/// routine will assert if passed a built-in type that isn't an integer or enum,
2039/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00002040unsigned ASTContext::getIntegerRank(Type *T) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002041 assert(T->isCanonical() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00002042 if (EnumType* ET = dyn_cast<EnumType>(T))
2043 T = ET->getDecl()->getIntegerType().getTypePtr();
2044
2045 // There are two things which impact the integer rank: the width, and
2046 // the ordering of builtins. The builtin ordering is encoded in the
2047 // bottom three bits; the width is encoded in the bits above that.
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002048 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T))
Eli Friedmanf98aba32009-02-13 02:31:07 +00002049 return FWIT->getWidth() << 3;
Eli Friedmanf98aba32009-02-13 02:31:07 +00002050
Chris Lattnerf52ab252008-04-06 22:59:24 +00002051 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00002052 default: assert(0 && "getIntegerRank(): not a built-in integer");
2053 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002054 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002055 case BuiltinType::Char_S:
2056 case BuiltinType::Char_U:
2057 case BuiltinType::SChar:
2058 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002059 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002060 case BuiltinType::Short:
2061 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002062 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002063 case BuiltinType::Int:
2064 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002065 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002066 case BuiltinType::Long:
2067 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002068 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002069 case BuiltinType::LongLong:
2070 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002071 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00002072 case BuiltinType::Int128:
2073 case BuiltinType::UInt128:
2074 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00002075 }
2076}
2077
Chris Lattner7cfeb082008-04-06 23:55:33 +00002078/// getIntegerTypeOrder - Returns the highest ranked integer type:
2079/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
2080/// LHS < RHS, return -1.
2081int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002082 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2083 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00002084 if (LHSC == RHSC) return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00002085
Chris Lattnerf52ab252008-04-06 22:59:24 +00002086 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2087 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002088
Chris Lattner7cfeb082008-04-06 23:55:33 +00002089 unsigned LHSRank = getIntegerRank(LHSC);
2090 unsigned RHSRank = getIntegerRank(RHSC);
Reid Spencer5f016e22007-07-11 17:01:13 +00002091
Chris Lattner7cfeb082008-04-06 23:55:33 +00002092 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2093 if (LHSRank == RHSRank) return 0;
2094 return LHSRank > RHSRank ? 1 : -1;
2095 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002096
Chris Lattner7cfeb082008-04-06 23:55:33 +00002097 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2098 if (LHSUnsigned) {
2099 // If the unsigned [LHS] type is larger, return it.
2100 if (LHSRank >= RHSRank)
2101 return 1;
2102
2103 // If the signed type can represent all values of the unsigned type, it
2104 // wins. Because we are dealing with 2's complement and types that are
2105 // powers of two larger than each other, this is always safe.
2106 return -1;
2107 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00002108
Chris Lattner7cfeb082008-04-06 23:55:33 +00002109 // If the unsigned [RHS] type is larger, return it.
2110 if (RHSRank >= LHSRank)
2111 return -1;
2112
2113 // If the signed type can represent all values of the unsigned type, it
2114 // wins. Because we are dealing with 2's complement and types that are
2115 // powers of two larger than each other, this is always safe.
2116 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002117}
Anders Carlsson71993dd2007-08-17 05:31:46 +00002118
2119// getCFConstantStringType - Return the type used for constant CFStrings.
2120QualType ASTContext::getCFConstantStringType() {
2121 if (!CFConstantStringTypeDecl) {
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002122 CFConstantStringTypeDecl =
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002123 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002124 &Idents.get("NSConstantString"));
Anders Carlssonf06273f2007-11-19 00:25:30 +00002125 QualType FieldTypes[4];
Anders Carlsson71993dd2007-08-17 05:31:46 +00002126
2127 // const int *isa;
2128 FieldTypes[0] = getPointerType(IntTy.getQualifiedType(QualType::Const));
Anders Carlssonf06273f2007-11-19 00:25:30 +00002129 // int flags;
2130 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00002131 // const char *str;
Anders Carlssonf06273f2007-11-19 00:25:30 +00002132 FieldTypes[2] = getPointerType(CharTy.getQualifiedType(QualType::Const));
Anders Carlsson71993dd2007-08-17 05:31:46 +00002133 // long length;
Anders Carlssonf06273f2007-11-19 00:25:30 +00002134 FieldTypes[3] = LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002135
Anders Carlsson71993dd2007-08-17 05:31:46 +00002136 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002137 for (unsigned i = 0; i < 4; ++i) {
2138 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
2139 SourceLocation(), 0,
2140 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002141 /*Mutable=*/false);
Douglas Gregor6ab35242009-04-09 21:40:53 +00002142 CFConstantStringTypeDecl->addDecl(*this, Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002143 }
2144
2145 CFConstantStringTypeDecl->completeDefinition(*this);
Anders Carlsson71993dd2007-08-17 05:31:46 +00002146 }
2147
2148 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00002149}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002150
Douglas Gregor319ac892009-04-23 22:29:11 +00002151void ASTContext::setCFConstantStringType(QualType T) {
2152 const RecordType *Rec = T->getAsRecordType();
2153 assert(Rec && "Invalid CFConstantStringType");
2154 CFConstantStringTypeDecl = Rec->getDecl();
2155}
2156
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002157QualType ASTContext::getObjCFastEnumerationStateType()
2158{
2159 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00002160 ObjCFastEnumerationStateTypeDecl =
2161 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2162 &Idents.get("__objcFastEnumerationState"));
2163
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002164 QualType FieldTypes[] = {
2165 UnsignedLongTy,
2166 getPointerType(ObjCIdType),
2167 getPointerType(UnsignedLongTy),
2168 getConstantArrayType(UnsignedLongTy,
2169 llvm::APInt(32, 5), ArrayType::Normal, 0)
2170 };
2171
Douglas Gregor44b43212008-12-11 16:49:14 +00002172 for (size_t i = 0; i < 4; ++i) {
2173 FieldDecl *Field = FieldDecl::Create(*this,
2174 ObjCFastEnumerationStateTypeDecl,
2175 SourceLocation(), 0,
2176 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002177 /*Mutable=*/false);
Douglas Gregor6ab35242009-04-09 21:40:53 +00002178 ObjCFastEnumerationStateTypeDecl->addDecl(*this, Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002179 }
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002180
Douglas Gregor44b43212008-12-11 16:49:14 +00002181 ObjCFastEnumerationStateTypeDecl->completeDefinition(*this);
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002182 }
2183
2184 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2185}
2186
Douglas Gregor319ac892009-04-23 22:29:11 +00002187void ASTContext::setObjCFastEnumerationStateType(QualType T) {
2188 const RecordType *Rec = T->getAsRecordType();
2189 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
2190 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
2191}
2192
Anders Carlssone8c49532007-10-29 06:33:42 +00002193// This returns true if a type has been typedefed to BOOL:
2194// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00002195static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00002196 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00002197 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
2198 return II->isStr("BOOL");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002199
2200 return false;
2201}
2202
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002203/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002204/// purpose.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002205int ASTContext::getObjCEncodingTypeSize(QualType type) {
Chris Lattner98be4942008-03-05 18:54:05 +00002206 uint64_t sz = getTypeSize(type);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002207
2208 // Make all integer and enum types at least as large as an int
2209 if (sz > 0 && type->isIntegralType())
Chris Lattner98be4942008-03-05 18:54:05 +00002210 sz = std::max(sz, getTypeSize(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002211 // Treat arrays as pointers, since that's how they're passed in.
2212 else if (type->isArrayType())
Chris Lattner98be4942008-03-05 18:54:05 +00002213 sz = getTypeSize(VoidPtrTy);
2214 return sz / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002215}
2216
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002217/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002218/// declaration.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002219void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00002220 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002221 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002222 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002223 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002224 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002225 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002226 // Compute size of all parameters.
2227 // Start with computing size of a pointer in number of bytes.
2228 // FIXME: There might(should) be a better way of doing this computation!
2229 SourceLocation Loc;
Chris Lattner98be4942008-03-05 18:54:05 +00002230 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002231 // The first two arguments (self and _cmd) are pointers; account for
2232 // their size.
2233 int ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00002234 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2235 E = Decl->param_end(); PI != E; ++PI) {
2236 QualType PType = (*PI)->getType();
2237 int sz = getObjCEncodingTypeSize(PType);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002238 assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002239 ParmOffset += sz;
2240 }
2241 S += llvm::utostr(ParmOffset);
2242 S += "@0:";
2243 S += llvm::utostr(PtrSize);
2244
2245 // Argument types.
2246 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00002247 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2248 E = Decl->param_end(); PI != E; ++PI) {
2249 ParmVarDecl *PVDecl = *PI;
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00002250 QualType PType = PVDecl->getOriginalType();
2251 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00002252 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
2253 // Use array's original type only if it has known number of
2254 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00002255 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00002256 PType = PVDecl->getType();
2257 } else if (PType->isFunctionType())
2258 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002259 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002260 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00002261 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002262 getObjCEncodingForType(PType, S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002263 S += llvm::utostr(ParmOffset);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002264 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002265 }
2266}
2267
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002268/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00002269/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002270/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
2271/// NULL when getting encodings for protocol properties.
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00002272/// Property attributes are stored as a comma-delimited C string. The simple
2273/// attributes readonly and bycopy are encoded as single characters. The
2274/// parametrized attributes, getter=name, setter=name, and ivar=name, are
2275/// encoded as single characters, followed by an identifier. Property types
2276/// are also encoded as a parametrized attribute. The characters used to encode
2277/// these attributes are defined by the following enumeration:
2278/// @code
2279/// enum PropertyAttributes {
2280/// kPropertyReadOnly = 'R', // property is read-only.
2281/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
2282/// kPropertyByref = '&', // property is a reference to the value last assigned
2283/// kPropertyDynamic = 'D', // property is dynamic
2284/// kPropertyGetter = 'G', // followed by getter selector name
2285/// kPropertySetter = 'S', // followed by setter selector name
2286/// kPropertyInstanceVariable = 'V' // followed by instance variable name
2287/// kPropertyType = 't' // followed by old-style type encoding.
2288/// kPropertyWeak = 'W' // 'weak' property
2289/// kPropertyStrong = 'P' // property GC'able
2290/// kPropertyNonAtomic = 'N' // property non-atomic
2291/// };
2292/// @endcode
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002293void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
2294 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00002295 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002296 // Collect information from the property implementation decl(s).
2297 bool Dynamic = false;
2298 ObjCPropertyImplDecl *SynthesizePID = 0;
2299
2300 // FIXME: Duplicated code due to poor abstraction.
2301 if (Container) {
2302 if (const ObjCCategoryImplDecl *CID =
2303 dyn_cast<ObjCCategoryImplDecl>(Container)) {
2304 for (ObjCCategoryImplDecl::propimpl_iterator
Douglas Gregor653f1b12009-04-23 01:02:12 +00002305 i = CID->propimpl_begin(*this), e = CID->propimpl_end(*this);
2306 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002307 ObjCPropertyImplDecl *PID = *i;
2308 if (PID->getPropertyDecl() == PD) {
2309 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2310 Dynamic = true;
2311 } else {
2312 SynthesizePID = PID;
2313 }
2314 }
2315 }
2316 } else {
Chris Lattner61710852008-10-05 17:34:18 +00002317 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002318 for (ObjCCategoryImplDecl::propimpl_iterator
Douglas Gregor653f1b12009-04-23 01:02:12 +00002319 i = OID->propimpl_begin(*this), e = OID->propimpl_end(*this);
2320 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002321 ObjCPropertyImplDecl *PID = *i;
2322 if (PID->getPropertyDecl() == PD) {
2323 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2324 Dynamic = true;
2325 } else {
2326 SynthesizePID = PID;
2327 }
2328 }
2329 }
2330 }
2331 }
2332
2333 // FIXME: This is not very efficient.
2334 S = "T";
2335
2336 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002337 // GCC has some special rules regarding encoding of properties which
2338 // closely resembles encoding of ivars.
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002339 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002340 true /* outermost type */,
2341 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002342
2343 if (PD->isReadOnly()) {
2344 S += ",R";
2345 } else {
2346 switch (PD->getSetterKind()) {
2347 case ObjCPropertyDecl::Assign: break;
2348 case ObjCPropertyDecl::Copy: S += ",C"; break;
2349 case ObjCPropertyDecl::Retain: S += ",&"; break;
2350 }
2351 }
2352
2353 // It really isn't clear at all what this means, since properties
2354 // are "dynamic by default".
2355 if (Dynamic)
2356 S += ",D";
2357
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002358 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
2359 S += ",N";
2360
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002361 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
2362 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002363 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002364 }
2365
2366 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
2367 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002368 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002369 }
2370
2371 if (SynthesizePID) {
2372 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
2373 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00002374 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002375 }
2376
2377 // FIXME: OBJCGC: weak & strong
2378}
2379
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002380/// getLegacyIntegralTypeEncoding -
2381/// Another legacy compatibility encoding: 32-bit longs are encoded as
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002382/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002383/// 'i' or 'I' instead if encoding a struct field, or a pointer!
2384///
2385void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
2386 if (dyn_cast<TypedefType>(PointeeTy.getTypePtr())) {
2387 if (const BuiltinType *BT = PointeeTy->getAsBuiltinType()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002388 if (BT->getKind() == BuiltinType::ULong &&
2389 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002390 PointeeTy = UnsignedIntTy;
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002391 else
2392 if (BT->getKind() == BuiltinType::Long &&
2393 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002394 PointeeTy = IntTy;
2395 }
2396 }
2397}
2398
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002399void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002400 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002401 // We follow the behavior of gcc, expanding structures which are
2402 // directly pointed to, and expanding embedded structures. Note that
2403 // these rules are sufficient to prevent recursive encoding of the
2404 // same type.
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00002405 getObjCEncodingForTypeImpl(T, S, true, true, Field,
2406 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002407}
2408
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002409static void EncodeBitField(const ASTContext *Context, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002410 const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002411 const Expr *E = FD->getBitWidth();
2412 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
2413 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Eli Friedman9a901bb2009-04-26 19:19:15 +00002414 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002415 S += 'b';
2416 S += llvm::utostr(N);
2417}
2418
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002419void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
2420 bool ExpandPointedToStructures,
2421 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002422 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002423 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002424 bool EncodingProperty) {
Anders Carlssone8c49532007-10-29 06:33:42 +00002425 if (const BuiltinType *BT = T->getAsBuiltinType()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002426 if (FD && FD->isBitField()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002427 EncodeBitField(this, S, FD);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002428 }
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002429 else {
2430 char encoding;
2431 switch (BT->getKind()) {
2432 default: assert(0 && "Unhandled builtin type kind");
2433 case BuiltinType::Void: encoding = 'v'; break;
2434 case BuiltinType::Bool: encoding = 'B'; break;
2435 case BuiltinType::Char_U:
2436 case BuiltinType::UChar: encoding = 'C'; break;
2437 case BuiltinType::UShort: encoding = 'S'; break;
2438 case BuiltinType::UInt: encoding = 'I'; break;
Fariborz Jahanian72696e12009-02-11 22:31:45 +00002439 case BuiltinType::ULong:
2440 encoding =
2441 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
2442 break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002443 case BuiltinType::UInt128: encoding = 'T'; break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002444 case BuiltinType::ULongLong: encoding = 'Q'; break;
2445 case BuiltinType::Char_S:
2446 case BuiltinType::SChar: encoding = 'c'; break;
2447 case BuiltinType::Short: encoding = 's'; break;
2448 case BuiltinType::Int: encoding = 'i'; break;
Fariborz Jahanian72696e12009-02-11 22:31:45 +00002449 case BuiltinType::Long:
2450 encoding =
2451 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
2452 break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002453 case BuiltinType::LongLong: encoding = 'q'; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002454 case BuiltinType::Int128: encoding = 't'; break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002455 case BuiltinType::Float: encoding = 'f'; break;
2456 case BuiltinType::Double: encoding = 'd'; break;
2457 case BuiltinType::LongDouble: encoding = 'd'; break;
2458 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002459
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002460 S += encoding;
2461 }
Anders Carlssonc612f7b2009-04-09 21:55:45 +00002462 } else if (const ComplexType *CT = T->getAsComplexType()) {
2463 S += 'j';
2464 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
2465 false);
2466 } else if (T->isObjCQualifiedIdType()) {
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002467 getObjCEncodingForTypeImpl(getObjCIdType(), S,
2468 ExpandPointedToStructures,
2469 ExpandStructures, FD);
2470 if (FD || EncodingProperty) {
2471 // Note that we do extended encoding of protocol qualifer list
2472 // Only when doing ivar or property encoding.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002473 const ObjCObjectPointerType *QIDT = T->getAsObjCQualifiedIdType();
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002474 S += '"';
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002475 for (ObjCObjectPointerType::qual_iterator I = QIDT->qual_begin(),
Steve Naroff446ee4e2009-05-27 16:21:00 +00002476 E = QIDT->qual_end(); I != E; ++I) {
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002477 S += '<';
Steve Naroff446ee4e2009-05-27 16:21:00 +00002478 S += (*I)->getNameAsString();
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002479 S += '>';
2480 }
2481 S += '"';
2482 }
2483 return;
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002484 }
2485 else if (const PointerType *PT = T->getAsPointerType()) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002486 QualType PointeeTy = PT->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002487 bool isReadOnly = false;
2488 // For historical/compatibility reasons, the read-only qualifier of the
2489 // pointee gets emitted _before_ the '^'. The read-only qualifier of
2490 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
2491 // Also, do not emit the 'r' for anything but the outermost type!
2492 if (dyn_cast<TypedefType>(T.getTypePtr())) {
2493 if (OutermostType && T.isConstQualified()) {
2494 isReadOnly = true;
2495 S += 'r';
2496 }
2497 }
2498 else if (OutermostType) {
2499 QualType P = PointeeTy;
2500 while (P->getAsPointerType())
2501 P = P->getAsPointerType()->getPointeeType();
2502 if (P.isConstQualified()) {
2503 isReadOnly = true;
2504 S += 'r';
2505 }
2506 }
2507 if (isReadOnly) {
2508 // Another legacy compatibility encoding. Some ObjC qualifier and type
2509 // combinations need to be rearranged.
2510 // Rewrite "in const" from "nr" to "rn"
2511 const char * s = S.c_str();
2512 int len = S.length();
2513 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
2514 std::string replace = "rn";
2515 S.replace(S.end()-2, S.end(), replace);
2516 }
2517 }
Steve Naroff389bf462009-02-12 17:52:19 +00002518 if (isObjCIdStructType(PointeeTy)) {
Fariborz Jahanianc2939bc2007-10-30 17:06:23 +00002519 S += '@';
2520 return;
Fariborz Jahanianc166d732008-12-19 00:14:49 +00002521 }
2522 else if (PointeeTy->isObjCInterfaceType()) {
Fariborz Jahanianbb99bde2009-02-16 21:41:04 +00002523 if (!EncodingProperty &&
Fariborz Jahanian225dfd72009-02-16 22:09:26 +00002524 isa<TypedefType>(PointeeTy.getTypePtr())) {
Fariborz Jahanian3e1b16c2008-12-23 21:30:15 +00002525 // Another historical/compatibility reason.
2526 // We encode the underlying type which comes out as
2527 // {...};
2528 S += '^';
2529 getObjCEncodingForTypeImpl(PointeeTy, S,
2530 false, ExpandPointedToStructures,
2531 NULL);
2532 return;
2533 }
Fariborz Jahanianc166d732008-12-19 00:14:49 +00002534 S += '@';
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002535 if (FD || EncodingProperty) {
Fariborz Jahanian86f938b2009-02-21 18:23:24 +00002536 const ObjCInterfaceType *OIT =
2537 PointeeTy.getUnqualifiedType()->getAsObjCInterfaceType();
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002538 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanianadcaf542008-12-20 19:17:01 +00002539 S += '"';
2540 S += OI->getNameAsCString();
Steve Naroff446ee4e2009-05-27 16:21:00 +00002541 for (ObjCInterfaceType::qual_iterator I = OIT->qual_begin(),
2542 E = OIT->qual_end(); I != E; ++I) {
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002543 S += '<';
Steve Naroff446ee4e2009-05-27 16:21:00 +00002544 S += (*I)->getNameAsString();
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002545 S += '>';
2546 }
Fariborz Jahanianadcaf542008-12-20 19:17:01 +00002547 S += '"';
2548 }
Fariborz Jahanianc166d732008-12-19 00:14:49 +00002549 return;
Steve Naroff389bf462009-02-12 17:52:19 +00002550 } else if (isObjCClassStructType(PointeeTy)) {
Anders Carlsson8baaca52007-10-31 02:53:19 +00002551 S += '#';
2552 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002553 } else if (isObjCSelType(PointeeTy)) {
Anders Carlsson8baaca52007-10-31 02:53:19 +00002554 S += ':';
2555 return;
Fariborz Jahanianc2939bc2007-10-30 17:06:23 +00002556 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002557
2558 if (PointeeTy->isCharType()) {
2559 // char pointer types should be encoded as '*' unless it is a
2560 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00002561 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002562 S += '*';
2563 return;
2564 }
2565 }
2566
2567 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002568 getLegacyIntegralTypeEncoding(PointeeTy);
2569
2570 getObjCEncodingForTypeImpl(PointeeTy, S,
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002571 false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002572 NULL);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002573 } else if (const ArrayType *AT =
2574 // Ignore type qualifiers etc.
2575 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00002576 if (isa<IncompleteArrayType>(AT)) {
2577 // Incomplete arrays are encoded as a pointer to the array element.
2578 S += '^';
2579
2580 getObjCEncodingForTypeImpl(AT->getElementType(), S,
2581 false, ExpandStructures, FD);
2582 } else {
2583 S += '[';
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002584
Anders Carlsson559a8332009-02-22 01:38:57 +00002585 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
2586 S += llvm::utostr(CAT->getSize().getZExtValue());
2587 else {
2588 //Variable length arrays are encoded as a regular array with 0 elements.
2589 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
2590 S += '0';
2591 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002592
Anders Carlsson559a8332009-02-22 01:38:57 +00002593 getObjCEncodingForTypeImpl(AT->getElementType(), S,
2594 false, ExpandStructures, FD);
2595 S += ']';
2596 }
Anders Carlssonc0a87b72007-10-30 00:06:20 +00002597 } else if (T->getAsFunctionType()) {
2598 S += '?';
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00002599 } else if (const RecordType *RTy = T->getAsRecordType()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002600 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002601 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00002602 // Anonymous structures print as '?'
2603 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
2604 S += II->getName();
2605 } else {
2606 S += '?';
2607 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002608 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002609 S += '=';
Douglas Gregor6ab35242009-04-09 21:40:53 +00002610 for (RecordDecl::field_iterator Field = RDecl->field_begin(*this),
2611 FieldEnd = RDecl->field_end(*this);
Douglas Gregor44b43212008-12-11 16:49:14 +00002612 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002613 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002614 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00002615 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002616 S += '"';
2617 }
2618
2619 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002620 if (Field->isBitField()) {
2621 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
2622 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002623 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002624 QualType qt = Field->getType();
2625 getLegacyIntegralTypeEncoding(qt);
2626 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002627 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002628 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002629 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00002630 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002631 S += RDecl->isUnion() ? ')' : '}';
Steve Naroff5e711242007-12-12 22:30:11 +00002632 } else if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002633 if (FD && FD->isBitField())
2634 EncodeBitField(this, S, FD);
2635 else
2636 S += 'i';
Steve Naroff485eeff2008-09-24 15:05:44 +00002637 } else if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00002638 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002639 } else if (T->isObjCInterfaceType()) {
2640 // @encode(class_name)
2641 ObjCInterfaceDecl *OI = T->getAsObjCInterfaceType()->getDecl();
2642 S += '{';
2643 const IdentifierInfo *II = OI->getIdentifier();
2644 S += II->getName();
2645 S += '=';
Chris Lattnerf1690852009-03-31 08:48:01 +00002646 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002647 CollectObjCIvars(OI, RecFields);
Chris Lattnerf1690852009-03-31 08:48:01 +00002648 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002649 if (RecFields[i]->isBitField())
2650 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2651 RecFields[i]);
2652 else
2653 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2654 FD);
2655 }
2656 S += '}';
2657 }
2658 else
Steve Narofff69cc5d2008-01-30 19:17:43 +00002659 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002660}
2661
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002662void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002663 std::string& S) const {
2664 if (QT & Decl::OBJC_TQ_In)
2665 S += 'n';
2666 if (QT & Decl::OBJC_TQ_Inout)
2667 S += 'N';
2668 if (QT & Decl::OBJC_TQ_Out)
2669 S += 'o';
2670 if (QT & Decl::OBJC_TQ_Bycopy)
2671 S += 'O';
2672 if (QT & Decl::OBJC_TQ_Byref)
2673 S += 'R';
2674 if (QT & Decl::OBJC_TQ_Oneway)
2675 S += 'V';
2676}
2677
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002678void ASTContext::setBuiltinVaListType(QualType T)
2679{
2680 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
2681
2682 BuiltinVaListType = T;
2683}
2684
Douglas Gregor319ac892009-04-23 22:29:11 +00002685void ASTContext::setObjCIdType(QualType T)
Steve Naroff7e219e42007-10-15 14:41:52 +00002686{
Douglas Gregor319ac892009-04-23 22:29:11 +00002687 ObjCIdType = T;
2688
2689 const TypedefType *TT = T->getAsTypedefType();
2690 if (!TT)
2691 return;
2692
2693 TypedefDecl *TD = TT->getDecl();
Steve Naroff7e219e42007-10-15 14:41:52 +00002694
2695 // typedef struct objc_object *id;
2696 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00002697 // User error - caller will issue diagnostics.
2698 if (!ptr)
2699 return;
Steve Naroff7e219e42007-10-15 14:41:52 +00002700 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00002701 // User error - caller will issue diagnostics.
2702 if (!rec)
2703 return;
Steve Naroff7e219e42007-10-15 14:41:52 +00002704 IdStructType = rec;
2705}
2706
Douglas Gregor319ac892009-04-23 22:29:11 +00002707void ASTContext::setObjCSelType(QualType T)
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002708{
Douglas Gregor319ac892009-04-23 22:29:11 +00002709 ObjCSelType = T;
2710
2711 const TypedefType *TT = T->getAsTypedefType();
2712 if (!TT)
2713 return;
2714 TypedefDecl *TD = TT->getDecl();
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002715
2716 // typedef struct objc_selector *SEL;
2717 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00002718 if (!ptr)
2719 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002720 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00002721 if (!rec)
2722 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002723 SelStructType = rec;
2724}
2725
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002726void ASTContext::setObjCProtoType(QualType QT)
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00002727{
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002728 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00002729}
2730
Douglas Gregor319ac892009-04-23 22:29:11 +00002731void ASTContext::setObjCClassType(QualType T)
Anders Carlsson8baaca52007-10-31 02:53:19 +00002732{
Douglas Gregor319ac892009-04-23 22:29:11 +00002733 ObjCClassType = T;
2734
2735 const TypedefType *TT = T->getAsTypedefType();
2736 if (!TT)
2737 return;
2738 TypedefDecl *TD = TT->getDecl();
Anders Carlsson8baaca52007-10-31 02:53:19 +00002739
2740 // typedef struct objc_class *Class;
2741 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
2742 assert(ptr && "'Class' incorrectly typed");
2743 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
2744 assert(rec && "'Class' incorrectly typed");
2745 ClassStructType = rec;
2746}
2747
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002748void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
2749 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00002750 "'NSConstantString' type already set!");
2751
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002752 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00002753}
2754
Douglas Gregor7532dc62009-03-30 22:58:21 +00002755/// \brief Retrieve the template name that represents a qualified
2756/// template name such as \c std::vector.
2757TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
2758 bool TemplateKeyword,
2759 TemplateDecl *Template) {
2760 llvm::FoldingSetNodeID ID;
2761 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
2762
2763 void *InsertPos = 0;
2764 QualifiedTemplateName *QTN =
2765 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
2766 if (!QTN) {
2767 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
2768 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
2769 }
2770
2771 return TemplateName(QTN);
2772}
2773
2774/// \brief Retrieve the template name that represents a dependent
2775/// template name such as \c MetaFun::template apply.
2776TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
2777 const IdentifierInfo *Name) {
2778 assert(NNS->isDependent() && "Nested name specifier must be dependent");
2779
2780 llvm::FoldingSetNodeID ID;
2781 DependentTemplateName::Profile(ID, NNS, Name);
2782
2783 void *InsertPos = 0;
2784 DependentTemplateName *QTN =
2785 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
2786
2787 if (QTN)
2788 return TemplateName(QTN);
2789
2790 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2791 if (CanonNNS == NNS) {
2792 QTN = new (*this,4) DependentTemplateName(NNS, Name);
2793 } else {
2794 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
2795 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
2796 }
2797
2798 DependentTemplateNames.InsertNode(QTN, InsertPos);
2799 return TemplateName(QTN);
2800}
2801
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002802/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00002803/// TargetInfo, produce the corresponding type. The unsigned @p Type
2804/// is actually a value of type @c TargetInfo::IntType.
2805QualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002806 switch (Type) {
2807 case TargetInfo::NoInt: return QualType();
2808 case TargetInfo::SignedShort: return ShortTy;
2809 case TargetInfo::UnsignedShort: return UnsignedShortTy;
2810 case TargetInfo::SignedInt: return IntTy;
2811 case TargetInfo::UnsignedInt: return UnsignedIntTy;
2812 case TargetInfo::SignedLong: return LongTy;
2813 case TargetInfo::UnsignedLong: return UnsignedLongTy;
2814 case TargetInfo::SignedLongLong: return LongLongTy;
2815 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
2816 }
2817
2818 assert(false && "Unhandled TargetInfo::IntType value");
Daniel Dunbarb3ac5432008-11-11 01:16:00 +00002819 return QualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002820}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00002821
2822//===----------------------------------------------------------------------===//
2823// Type Predicates.
2824//===----------------------------------------------------------------------===//
2825
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00002826/// isObjCNSObjectType - Return true if this is an NSObject object using
2827/// NSObject attribute on a c-style pointer type.
2828/// FIXME - Make it work directly on types.
2829///
2830bool ASTContext::isObjCNSObjectType(QualType Ty) const {
2831 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
2832 if (TypedefDecl *TD = TDT->getDecl())
Douglas Gregor68584ed2009-06-18 16:11:24 +00002833 if (TD->getAttr<ObjCNSObjectAttr>(*const_cast<ASTContext*>(this)))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00002834 return true;
2835 }
2836 return false;
2837}
2838
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00002839/// isObjCObjectPointerType - Returns true if type is an Objective-C pointer
2840/// to an object type. This includes "id" and "Class" (two 'special' pointers
2841/// to struct), Interface* (pointer to ObjCInterfaceType) and id<P> (qualified
2842/// ID type).
2843bool ASTContext::isObjCObjectPointerType(QualType Ty) const {
Steve Naroffd4617772009-02-23 18:36:16 +00002844 if (Ty->isObjCQualifiedIdType())
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00002845 return true;
2846
Steve Naroff6ae98502008-10-21 18:24:04 +00002847 // Blocks are objects.
2848 if (Ty->isBlockPointerType())
2849 return true;
2850
2851 // All other object types are pointers.
Chris Lattner16ede0e2009-04-12 23:51:02 +00002852 const PointerType *PT = Ty->getAsPointerType();
2853 if (PT == 0)
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00002854 return false;
2855
Chris Lattner16ede0e2009-04-12 23:51:02 +00002856 // If this a pointer to an interface (e.g. NSString*), it is ok.
2857 if (PT->getPointeeType()->isObjCInterfaceType() ||
2858 // If is has NSObject attribute, OK as well.
2859 isObjCNSObjectType(Ty))
2860 return true;
2861
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00002862 // Check to see if this is 'id' or 'Class', both of which are typedefs for
2863 // pointer types. This looks for the typedef specifically, not for the
Chris Lattner16ede0e2009-04-12 23:51:02 +00002864 // underlying type. Iteratively strip off typedefs so that we can handle
2865 // typedefs of typedefs.
2866 while (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
2867 if (Ty.getUnqualifiedType() == getObjCIdType() ||
2868 Ty.getUnqualifiedType() == getObjCClassType())
2869 return true;
2870
2871 Ty = TDT->getDecl()->getUnderlyingType();
2872 }
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00002873
Chris Lattner16ede0e2009-04-12 23:51:02 +00002874 return false;
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00002875}
2876
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00002877/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
2878/// garbage collection attribute.
2879///
2880QualType::GCAttrTypes ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
Chris Lattnerb7d25532009-02-18 22:53:11 +00002881 QualType::GCAttrTypes GCAttrs = QualType::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00002882 if (getLangOptions().ObjC1 &&
2883 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00002884 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00002885 // Default behavious under objective-c's gc is for objective-c pointers
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00002886 // (or pointers to them) be treated as though they were declared
2887 // as __strong.
2888 if (GCAttrs == QualType::GCNone) {
2889 if (isObjCObjectPointerType(Ty))
2890 GCAttrs = QualType::Strong;
2891 else if (Ty->isPointerType())
2892 return getObjCGCAttrKind(Ty->getAsPointerType()->getPointeeType());
2893 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00002894 // Non-pointers have none gc'able attribute regardless of the attribute
2895 // set on them.
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00002896 else if (!Ty->isPointerType() && !isObjCObjectPointerType(Ty))
Fariborz Jahanianc2112182009-04-11 00:00:54 +00002897 return QualType::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00002898 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00002899 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00002900}
2901
Chris Lattner6ac46a42008-04-07 06:51:04 +00002902//===----------------------------------------------------------------------===//
2903// Type Compatibility Testing
2904//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00002905
Chris Lattner6ac46a42008-04-07 06:51:04 +00002906/// areCompatVectorTypes - Return true if the two specified vector types are
2907/// compatible.
2908static bool areCompatVectorTypes(const VectorType *LHS,
2909 const VectorType *RHS) {
2910 assert(LHS->isCanonical() && RHS->isCanonical());
2911 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00002912 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00002913}
2914
Eli Friedman3d815e72008-08-22 00:56:42 +00002915/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00002916/// compatible for assignment from RHS to LHS. This handles validation of any
2917/// protocol qualifiers on the LHS or RHS.
2918///
Eli Friedman3d815e72008-08-22 00:56:42 +00002919bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
2920 const ObjCInterfaceType *RHS) {
Chris Lattner6ac46a42008-04-07 06:51:04 +00002921 // Verify that the base decls are compatible: the RHS must be a subclass of
2922 // the LHS.
2923 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
2924 return false;
2925
2926 // RHS must have a superset of the protocols in the LHS. If the LHS is not
2927 // protocol qualified at all, then we are good.
2928 if (!isa<ObjCQualifiedInterfaceType>(LHS))
2929 return true;
2930
2931 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
2932 // isn't a superset.
2933 if (!isa<ObjCQualifiedInterfaceType>(RHS))
2934 return true; // FIXME: should return false!
2935
2936 // Finally, we must have two protocol-qualified interfaces.
2937 const ObjCQualifiedInterfaceType *LHSP =cast<ObjCQualifiedInterfaceType>(LHS);
2938 const ObjCQualifiedInterfaceType *RHSP =cast<ObjCQualifiedInterfaceType>(RHS);
Chris Lattner6ac46a42008-04-07 06:51:04 +00002939
Steve Naroff91b0b0c2009-03-01 16:12:44 +00002940 // All LHS protocols must have a presence on the RHS.
2941 assert(LHSP->qual_begin() != LHSP->qual_end() && "Empty LHS protocol list?");
Chris Lattner6ac46a42008-04-07 06:51:04 +00002942
Steve Naroff91b0b0c2009-03-01 16:12:44 +00002943 for (ObjCQualifiedInterfaceType::qual_iterator LHSPI = LHSP->qual_begin(),
2944 LHSPE = LHSP->qual_end();
2945 LHSPI != LHSPE; LHSPI++) {
2946 bool RHSImplementsProtocol = false;
2947
2948 // If the RHS doesn't implement the protocol on the left, the types
2949 // are incompatible.
2950 for (ObjCQualifiedInterfaceType::qual_iterator RHSPI = RHSP->qual_begin(),
2951 RHSPE = RHSP->qual_end();
2952 !RHSImplementsProtocol && (RHSPI != RHSPE); RHSPI++) {
2953 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier()))
2954 RHSImplementsProtocol = true;
2955 }
2956 // FIXME: For better diagnostics, consider passing back the protocol name.
2957 if (!RHSImplementsProtocol)
2958 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00002959 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00002960 // The RHS implements all protocols listed on the LHS.
2961 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00002962}
2963
Steve Naroff389bf462009-02-12 17:52:19 +00002964bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
2965 // get the "pointed to" types
2966 const PointerType *LHSPT = LHS->getAsPointerType();
2967 const PointerType *RHSPT = RHS->getAsPointerType();
2968
2969 if (!LHSPT || !RHSPT)
2970 return false;
2971
2972 QualType lhptee = LHSPT->getPointeeType();
2973 QualType rhptee = RHSPT->getPointeeType();
2974 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2975 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2976 // ID acts sort of like void* for ObjC interfaces
2977 if (LHSIface && isObjCIdStructType(rhptee))
2978 return true;
2979 if (RHSIface && isObjCIdStructType(lhptee))
2980 return true;
2981 if (!LHSIface || !RHSIface)
2982 return false;
2983 return canAssignObjCInterfaces(LHSIface, RHSIface) ||
2984 canAssignObjCInterfaces(RHSIface, LHSIface);
2985}
2986
Steve Naroffec0550f2007-10-15 20:41:53 +00002987/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
2988/// both shall have the identically qualified version of a compatible type.
2989/// C99 6.2.7p1: Two types have compatible types if their types are the
2990/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman3d815e72008-08-22 00:56:42 +00002991bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
2992 return !mergeTypes(LHS, RHS).isNull();
2993}
2994
2995QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
2996 const FunctionType *lbase = lhs->getAsFunctionType();
2997 const FunctionType *rbase = rhs->getAsFunctionType();
Douglas Gregor72564e72009-02-26 23:50:07 +00002998 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
2999 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00003000 bool allLTypes = true;
3001 bool allRTypes = true;
3002
3003 // Check return type
3004 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
3005 if (retType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00003006 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
3007 allLTypes = false;
3008 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
3009 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00003010
3011 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00003012 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
3013 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00003014 unsigned lproto_nargs = lproto->getNumArgs();
3015 unsigned rproto_nargs = rproto->getNumArgs();
3016
3017 // Compatible functions must have the same number of arguments
3018 if (lproto_nargs != rproto_nargs)
3019 return QualType();
3020
3021 // Variadic and non-variadic functions aren't compatible
3022 if (lproto->isVariadic() != rproto->isVariadic())
3023 return QualType();
3024
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003025 if (lproto->getTypeQuals() != rproto->getTypeQuals())
3026 return QualType();
3027
Eli Friedman3d815e72008-08-22 00:56:42 +00003028 // Check argument compatibility
3029 llvm::SmallVector<QualType, 10> types;
3030 for (unsigned i = 0; i < lproto_nargs; i++) {
3031 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
3032 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
3033 QualType argtype = mergeTypes(largtype, rargtype);
3034 if (argtype.isNull()) return QualType();
3035 types.push_back(argtype);
Chris Lattner61710852008-10-05 17:34:18 +00003036 if (getCanonicalType(argtype) != getCanonicalType(largtype))
3037 allLTypes = false;
3038 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
3039 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00003040 }
3041 if (allLTypes) return lhs;
3042 if (allRTypes) return rhs;
3043 return getFunctionType(retType, types.begin(), types.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003044 lproto->isVariadic(), lproto->getTypeQuals());
Eli Friedman3d815e72008-08-22 00:56:42 +00003045 }
3046
3047 if (lproto) allRTypes = false;
3048 if (rproto) allLTypes = false;
3049
Douglas Gregor72564e72009-02-26 23:50:07 +00003050 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00003051 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00003052 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00003053 if (proto->isVariadic()) return QualType();
3054 // Check that the types are compatible with the types that
3055 // would result from default argument promotions (C99 6.7.5.3p15).
3056 // The only types actually affected are promotable integer
3057 // types and floats, which would be passed as a different
3058 // type depending on whether the prototype is visible.
3059 unsigned proto_nargs = proto->getNumArgs();
3060 for (unsigned i = 0; i < proto_nargs; ++i) {
3061 QualType argTy = proto->getArgType(i);
3062 if (argTy->isPromotableIntegerType() ||
3063 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
3064 return QualType();
3065 }
3066
3067 if (allLTypes) return lhs;
3068 if (allRTypes) return rhs;
3069 return getFunctionType(retType, proto->arg_type_begin(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003070 proto->getNumArgs(), lproto->isVariadic(),
3071 lproto->getTypeQuals());
Eli Friedman3d815e72008-08-22 00:56:42 +00003072 }
3073
3074 if (allLTypes) return lhs;
3075 if (allRTypes) return rhs;
Douglas Gregor72564e72009-02-26 23:50:07 +00003076 return getFunctionNoProtoType(retType);
Eli Friedman3d815e72008-08-22 00:56:42 +00003077}
3078
3079QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
Bill Wendling43d69752007-12-03 07:33:35 +00003080 // C++ [expr]: If an expression initially has the type "reference to T", the
3081 // type is adjusted to "T" prior to any further analysis, the expression
3082 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003083 // expression is an lvalue unless the reference is an rvalue reference and
3084 // the expression is a function call (possibly inside parentheses).
Eli Friedman3d815e72008-08-22 00:56:42 +00003085 // FIXME: C++ shouldn't be going through here! The rules are different
3086 // enough that they should be handled separately.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003087 // FIXME: Merging of lvalue and rvalue references is incorrect. C++ *really*
3088 // shouldn't be going through here!
Eli Friedman3d815e72008-08-22 00:56:42 +00003089 if (const ReferenceType *RT = LHS->getAsReferenceType())
Chris Lattnerc4e40592008-04-07 04:07:56 +00003090 LHS = RT->getPointeeType();
Eli Friedman3d815e72008-08-22 00:56:42 +00003091 if (const ReferenceType *RT = RHS->getAsReferenceType())
Chris Lattnerc4e40592008-04-07 04:07:56 +00003092 RHS = RT->getPointeeType();
Chris Lattnerf3692dc2008-04-07 05:37:56 +00003093
Eli Friedman3d815e72008-08-22 00:56:42 +00003094 QualType LHSCan = getCanonicalType(LHS),
3095 RHSCan = getCanonicalType(RHS);
3096
3097 // If two types are identical, they are compatible.
3098 if (LHSCan == RHSCan)
3099 return LHS;
3100
3101 // If the qualifiers are different, the types aren't compatible
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003102 // Note that we handle extended qualifiers later, in the
3103 // case for ExtQualType.
3104 if (LHSCan.getCVRQualifiers() != RHSCan.getCVRQualifiers())
Eli Friedman3d815e72008-08-22 00:56:42 +00003105 return QualType();
3106
Eli Friedman852d63b2009-06-01 01:22:52 +00003107 Type::TypeClass LHSClass = LHSCan->getTypeClass();
3108 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00003109
Chris Lattner1adb8832008-01-14 05:45:46 +00003110 // We want to consider the two function types to be the same for these
3111 // comparisons, just force one to the other.
3112 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
3113 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00003114
Eli Friedman07d25872009-06-02 05:28:56 +00003115 // Strip off objc_gc attributes off the top level so they can be merged.
3116 // This is a complete mess, but the attribute itself doesn't make much sense.
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003117 if (RHSClass == Type::ExtQual) {
Eli Friedman07d25872009-06-02 05:28:56 +00003118 QualType::GCAttrTypes GCAttr = RHSCan.getObjCGCAttr();
3119 if (GCAttr != QualType::GCNone) {
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003120 QualType::GCAttrTypes GCLHSAttr = LHSCan.getObjCGCAttr();
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003121 // __weak attribute must appear on both declarations.
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003122 // __strong attribue is redundant if other decl is an objective-c
3123 // object pointer (or decorated with __strong attribute); otherwise
3124 // issue error.
3125 if ((GCAttr == QualType::Weak && GCLHSAttr != GCAttr) ||
3126 (GCAttr == QualType::Strong && GCLHSAttr != GCAttr &&
3127 LHSCan->isPointerType() && !isObjCObjectPointerType(LHSCan) &&
3128 !isObjCIdStructType(LHSCan->getAsPointerType()->getPointeeType())))
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003129 return QualType();
3130
Eli Friedman07d25872009-06-02 05:28:56 +00003131 RHS = QualType(cast<ExtQualType>(RHS.getDesugaredType())->getBaseType(),
3132 RHS.getCVRQualifiers());
3133 QualType Result = mergeTypes(LHS, RHS);
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003134 if (!Result.isNull()) {
3135 if (Result.getObjCGCAttr() == QualType::GCNone)
3136 Result = getObjCGCQualType(Result, GCAttr);
3137 else if (Result.getObjCGCAttr() != GCAttr)
3138 Result = QualType();
3139 }
Eli Friedman07d25872009-06-02 05:28:56 +00003140 return Result;
3141 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003142 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003143 if (LHSClass == Type::ExtQual) {
Eli Friedman07d25872009-06-02 05:28:56 +00003144 QualType::GCAttrTypes GCAttr = LHSCan.getObjCGCAttr();
3145 if (GCAttr != QualType::GCNone) {
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003146 QualType::GCAttrTypes GCRHSAttr = RHSCan.getObjCGCAttr();
3147 // __weak attribute must appear on both declarations. __strong
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003148 // __strong attribue is redundant if other decl is an objective-c
3149 // object pointer (or decorated with __strong attribute); otherwise
3150 // issue error.
3151 if ((GCAttr == QualType::Weak && GCRHSAttr != GCAttr) ||
3152 (GCAttr == QualType::Strong && GCRHSAttr != GCAttr &&
3153 RHSCan->isPointerType() && !isObjCObjectPointerType(RHSCan) &&
3154 !isObjCIdStructType(RHSCan->getAsPointerType()->getPointeeType())))
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003155 return QualType();
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003156
Eli Friedman07d25872009-06-02 05:28:56 +00003157 LHS = QualType(cast<ExtQualType>(LHS.getDesugaredType())->getBaseType(),
3158 LHS.getCVRQualifiers());
3159 QualType Result = mergeTypes(LHS, RHS);
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003160 if (!Result.isNull()) {
3161 if (Result.getObjCGCAttr() == QualType::GCNone)
3162 Result = getObjCGCQualType(Result, GCAttr);
3163 else if (Result.getObjCGCAttr() != GCAttr)
3164 Result = QualType();
3165 }
Eli Friedman354e53d2009-06-02 07:45:37 +00003166 return Result;
Eli Friedman07d25872009-06-02 05:28:56 +00003167 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003168 }
3169
Eli Friedman4c721d32008-02-12 08:23:06 +00003170 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00003171 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
3172 LHSClass = Type::ConstantArray;
3173 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
3174 RHSClass = Type::ConstantArray;
Steve Naroffec0550f2007-10-15 20:41:53 +00003175
Nate Begeman213541a2008-04-18 23:10:10 +00003176 // Canonicalize ExtVector -> Vector.
3177 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
3178 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Chris Lattnera36a61f2008-04-07 05:43:21 +00003179
Chris Lattnerb0489812008-04-07 06:38:24 +00003180 // Consider qualified interfaces and interfaces the same.
3181 if (LHSClass == Type::ObjCQualifiedInterface) LHSClass = Type::ObjCInterface;
3182 if (RHSClass == Type::ObjCQualifiedInterface) RHSClass = Type::ObjCInterface;
Eli Friedman3d815e72008-08-22 00:56:42 +00003183
Chris Lattnera36a61f2008-04-07 05:43:21 +00003184 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00003185 if (LHSClass != RHSClass) {
Steve Naroff5fd659d2009-02-21 16:18:07 +00003186 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
3187 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
Fariborz Jahanianc8d2e772009-04-15 21:54:48 +00003188
Steve Naroffd824c9c2009-04-14 15:11:46 +00003189 // 'id' and 'Class' act sort of like void* for ObjC interfaces
3190 if (LHSIface && (isObjCIdStructType(RHS) || isObjCClassStructType(RHS)))
Steve Naroff5fd659d2009-02-21 16:18:07 +00003191 return LHS;
Steve Naroffd824c9c2009-04-14 15:11:46 +00003192 if (RHSIface && (isObjCIdStructType(LHS) || isObjCClassStructType(LHS)))
Steve Naroff5fd659d2009-02-21 16:18:07 +00003193 return RHS;
3194
Steve Naroffbc76dd02008-12-10 22:14:21 +00003195 // ID is compatible with all qualified id types.
3196 if (LHS->isObjCQualifiedIdType()) {
3197 if (const PointerType *PT = RHS->getAsPointerType()) {
3198 QualType pType = PT->getPointeeType();
Steve Naroffd824c9c2009-04-14 15:11:46 +00003199 if (isObjCIdStructType(pType) || isObjCClassStructType(pType))
Steve Naroffbc76dd02008-12-10 22:14:21 +00003200 return LHS;
3201 // FIXME: need to use ObjCQualifiedIdTypesAreCompatible(LHS, RHS, true).
3202 // Unfortunately, this API is part of Sema (which we don't have access
3203 // to. Need to refactor. The following check is insufficient, since we
3204 // need to make sure the class implements the protocol.
3205 if (pType->isObjCInterfaceType())
3206 return LHS;
3207 }
3208 }
3209 if (RHS->isObjCQualifiedIdType()) {
3210 if (const PointerType *PT = LHS->getAsPointerType()) {
3211 QualType pType = PT->getPointeeType();
Steve Naroffd824c9c2009-04-14 15:11:46 +00003212 if (isObjCIdStructType(pType) || isObjCClassStructType(pType))
Steve Naroffbc76dd02008-12-10 22:14:21 +00003213 return RHS;
3214 // FIXME: need to use ObjCQualifiedIdTypesAreCompatible(LHS, RHS, true).
3215 // Unfortunately, this API is part of Sema (which we don't have access
3216 // to. Need to refactor. The following check is insufficient, since we
3217 // need to make sure the class implements the protocol.
3218 if (pType->isObjCInterfaceType())
3219 return RHS;
3220 }
3221 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003222 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
3223 // a signed integer type, or an unsigned integer type.
Eli Friedman3d815e72008-08-22 00:56:42 +00003224 if (const EnumType* ETy = LHS->getAsEnumType()) {
3225 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
3226 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00003227 }
Eli Friedman3d815e72008-08-22 00:56:42 +00003228 if (const EnumType* ETy = RHS->getAsEnumType()) {
3229 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
3230 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00003231 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003232
Eli Friedman3d815e72008-08-22 00:56:42 +00003233 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00003234 }
Eli Friedman3d815e72008-08-22 00:56:42 +00003235
Steve Naroff4a746782008-01-09 22:43:08 +00003236 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00003237 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00003238#define TYPE(Class, Base)
3239#define ABSTRACT_TYPE(Class, Base)
3240#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3241#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3242#include "clang/AST/TypeNodes.def"
3243 assert(false && "Non-canonical and dependent types shouldn't get here");
3244 return QualType();
3245
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003246 case Type::LValueReference:
3247 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00003248 case Type::MemberPointer:
3249 assert(false && "C++ should never be in mergeTypes");
3250 return QualType();
3251
3252 case Type::IncompleteArray:
3253 case Type::VariableArray:
3254 case Type::FunctionProto:
3255 case Type::ExtVector:
3256 case Type::ObjCQualifiedInterface:
3257 assert(false && "Types are eliminated above");
3258 return QualType();
3259
Chris Lattner1adb8832008-01-14 05:45:46 +00003260 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00003261 {
3262 // Merge two pointer types, while trying to preserve typedef info
3263 QualType LHSPointee = LHS->getAsPointerType()->getPointeeType();
3264 QualType RHSPointee = RHS->getAsPointerType()->getPointeeType();
3265 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
3266 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00003267 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00003268 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00003269 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00003270 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00003271 return getPointerType(ResultType);
3272 }
Steve Naroffc0febd52008-12-10 17:49:55 +00003273 case Type::BlockPointer:
3274 {
3275 // Merge two block pointer types, while trying to preserve typedef info
3276 QualType LHSPointee = LHS->getAsBlockPointerType()->getPointeeType();
3277 QualType RHSPointee = RHS->getAsBlockPointerType()->getPointeeType();
3278 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
3279 if (ResultType.isNull()) return QualType();
3280 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
3281 return LHS;
3282 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
3283 return RHS;
3284 return getBlockPointerType(ResultType);
3285 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003286 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00003287 {
3288 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
3289 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
3290 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
3291 return QualType();
3292
3293 QualType LHSElem = getAsArrayType(LHS)->getElementType();
3294 QualType RHSElem = getAsArrayType(RHS)->getElementType();
3295 QualType ResultType = mergeTypes(LHSElem, RHSElem);
3296 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00003297 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3298 return LHS;
3299 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3300 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00003301 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
3302 ArrayType::ArraySizeModifier(), 0);
3303 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
3304 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00003305 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
3306 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00003307 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3308 return LHS;
3309 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3310 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00003311 if (LVAT) {
3312 // FIXME: This isn't correct! But tricky to implement because
3313 // the array's size has to be the size of LHS, but the type
3314 // has to be different.
3315 return LHS;
3316 }
3317 if (RVAT) {
3318 // FIXME: This isn't correct! But tricky to implement because
3319 // the array's size has to be the size of RHS, but the type
3320 // has to be different.
3321 return RHS;
3322 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00003323 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
3324 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Chris Lattner61710852008-10-05 17:34:18 +00003325 return getIncompleteArrayType(ResultType, ArrayType::ArraySizeModifier(),0);
Eli Friedman3d815e72008-08-22 00:56:42 +00003326 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003327 case Type::FunctionNoProto:
Eli Friedman3d815e72008-08-22 00:56:42 +00003328 return mergeFunctionTypes(LHS, RHS);
Douglas Gregor72564e72009-02-26 23:50:07 +00003329 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00003330 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00003331 // FIXME: Why are these compatible?
Steve Naroff389bf462009-02-12 17:52:19 +00003332 if (isObjCIdStructType(LHS) && isObjCClassStructType(RHS)) return LHS;
3333 if (isObjCClassStructType(LHS) && isObjCIdStructType(RHS)) return LHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00003334 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00003335 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00003336 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00003337 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00003338 case Type::Complex:
3339 // Distinct complex types are incompatible.
3340 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00003341 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003342 // FIXME: The merged type should be an ExtVector!
Eli Friedman3d815e72008-08-22 00:56:42 +00003343 if (areCompatVectorTypes(LHS->getAsVectorType(), RHS->getAsVectorType()))
3344 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00003345 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00003346 case Type::ObjCInterface: {
Steve Naroff5fd659d2009-02-21 16:18:07 +00003347 // Check if the interfaces are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003348 // FIXME: This should be type compatibility, e.g. whether
3349 // "LHS x; RHS x;" at global scope is legal.
Steve Naroff5fd659d2009-02-21 16:18:07 +00003350 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
3351 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
3352 if (LHSIface && RHSIface &&
3353 canAssignObjCInterfaces(LHSIface, RHSIface))
3354 return LHS;
3355
Eli Friedman3d815e72008-08-22 00:56:42 +00003356 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00003357 }
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003358 case Type::ObjCObjectPointer:
3359 // FIXME: finish
Steve Naroffbc76dd02008-12-10 22:14:21 +00003360 // Distinct qualified id's are not compatible.
3361 return QualType();
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003362 case Type::FixedWidthInt:
3363 // Distinct fixed-width integers are not compatible.
3364 return QualType();
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003365 case Type::ExtQual:
3366 // FIXME: ExtQual types can be compatible even if they're not
3367 // identical!
3368 return QualType();
3369 // First attempt at an implementation, but I'm not really sure it's
3370 // right...
3371#if 0
3372 ExtQualType* LQual = cast<ExtQualType>(LHSCan);
3373 ExtQualType* RQual = cast<ExtQualType>(RHSCan);
3374 if (LQual->getAddressSpace() != RQual->getAddressSpace() ||
3375 LQual->getObjCGCAttr() != RQual->getObjCGCAttr())
3376 return QualType();
3377 QualType LHSBase, RHSBase, ResultType, ResCanUnqual;
3378 LHSBase = QualType(LQual->getBaseType(), 0);
3379 RHSBase = QualType(RQual->getBaseType(), 0);
3380 ResultType = mergeTypes(LHSBase, RHSBase);
3381 if (ResultType.isNull()) return QualType();
3382 ResCanUnqual = getCanonicalType(ResultType).getUnqualifiedType();
3383 if (LHSCan.getUnqualifiedType() == ResCanUnqual)
3384 return LHS;
3385 if (RHSCan.getUnqualifiedType() == ResCanUnqual)
3386 return RHS;
3387 ResultType = getAddrSpaceQualType(ResultType, LQual->getAddressSpace());
3388 ResultType = getObjCGCQualType(ResultType, LQual->getObjCGCAttr());
3389 ResultType.setCVRQualifiers(LHSCan.getCVRQualifiers());
3390 return ResultType;
3391#endif
Douglas Gregor7532dc62009-03-30 22:58:21 +00003392
3393 case Type::TemplateSpecialization:
3394 assert(false && "Dependent types have no size");
3395 break;
Steve Naroffec0550f2007-10-15 20:41:53 +00003396 }
Douglas Gregor72564e72009-02-26 23:50:07 +00003397
3398 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00003399}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00003400
Chris Lattner5426bf62008-04-07 07:01:58 +00003401//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00003402// Integer Predicates
3403//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00003404
Eli Friedmanad74a752008-06-28 06:23:08 +00003405unsigned ASTContext::getIntWidth(QualType T) {
3406 if (T == BoolTy)
3407 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00003408 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T)) {
3409 return FWIT->getWidth();
3410 }
3411 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00003412 return (unsigned)getTypeSize(T);
3413}
3414
3415QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
3416 assert(T->isSignedIntegerType() && "Unexpected type");
3417 if (const EnumType* ETy = T->getAsEnumType())
3418 T = ETy->getDecl()->getIntegerType();
3419 const BuiltinType* BTy = T->getAsBuiltinType();
3420 assert (BTy && "Unexpected signed integer type");
3421 switch (BTy->getKind()) {
3422 case BuiltinType::Char_S:
3423 case BuiltinType::SChar:
3424 return UnsignedCharTy;
3425 case BuiltinType::Short:
3426 return UnsignedShortTy;
3427 case BuiltinType::Int:
3428 return UnsignedIntTy;
3429 case BuiltinType::Long:
3430 return UnsignedLongTy;
3431 case BuiltinType::LongLong:
3432 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00003433 case BuiltinType::Int128:
3434 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00003435 default:
3436 assert(0 && "Unexpected signed integer type");
3437 return QualType();
3438 }
3439}
3440
Douglas Gregor2cf26342009-04-09 22:27:44 +00003441ExternalASTSource::~ExternalASTSource() { }
3442
3443void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00003444
3445
3446//===----------------------------------------------------------------------===//
3447// Builtin Type Computation
3448//===----------------------------------------------------------------------===//
3449
3450/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
3451/// pointer over the consumed characters. This returns the resultant type.
3452static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
3453 ASTContext::GetBuiltinTypeError &Error,
3454 bool AllowTypeModifiers = true) {
3455 // Modifiers.
3456 int HowLong = 0;
3457 bool Signed = false, Unsigned = false;
3458
3459 // Read the modifiers first.
3460 bool Done = false;
3461 while (!Done) {
3462 switch (*Str++) {
3463 default: Done = true; --Str; break;
3464 case 'S':
3465 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
3466 assert(!Signed && "Can't use 'S' modifier multiple times!");
3467 Signed = true;
3468 break;
3469 case 'U':
3470 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
3471 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
3472 Unsigned = true;
3473 break;
3474 case 'L':
3475 assert(HowLong <= 2 && "Can't have LLLL modifier");
3476 ++HowLong;
3477 break;
3478 }
3479 }
3480
3481 QualType Type;
3482
3483 // Read the base type.
3484 switch (*Str++) {
3485 default: assert(0 && "Unknown builtin type letter!");
3486 case 'v':
3487 assert(HowLong == 0 && !Signed && !Unsigned &&
3488 "Bad modifiers used with 'v'!");
3489 Type = Context.VoidTy;
3490 break;
3491 case 'f':
3492 assert(HowLong == 0 && !Signed && !Unsigned &&
3493 "Bad modifiers used with 'f'!");
3494 Type = Context.FloatTy;
3495 break;
3496 case 'd':
3497 assert(HowLong < 2 && !Signed && !Unsigned &&
3498 "Bad modifiers used with 'd'!");
3499 if (HowLong)
3500 Type = Context.LongDoubleTy;
3501 else
3502 Type = Context.DoubleTy;
3503 break;
3504 case 's':
3505 assert(HowLong == 0 && "Bad modifiers used with 's'!");
3506 if (Unsigned)
3507 Type = Context.UnsignedShortTy;
3508 else
3509 Type = Context.ShortTy;
3510 break;
3511 case 'i':
3512 if (HowLong == 3)
3513 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
3514 else if (HowLong == 2)
3515 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
3516 else if (HowLong == 1)
3517 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
3518 else
3519 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
3520 break;
3521 case 'c':
3522 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
3523 if (Signed)
3524 Type = Context.SignedCharTy;
3525 else if (Unsigned)
3526 Type = Context.UnsignedCharTy;
3527 else
3528 Type = Context.CharTy;
3529 break;
3530 case 'b': // boolean
3531 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
3532 Type = Context.BoolTy;
3533 break;
3534 case 'z': // size_t.
3535 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
3536 Type = Context.getSizeType();
3537 break;
3538 case 'F':
3539 Type = Context.getCFConstantStringType();
3540 break;
3541 case 'a':
3542 Type = Context.getBuiltinVaListType();
3543 assert(!Type.isNull() && "builtin va list type not initialized!");
3544 break;
3545 case 'A':
3546 // This is a "reference" to a va_list; however, what exactly
3547 // this means depends on how va_list is defined. There are two
3548 // different kinds of va_list: ones passed by value, and ones
3549 // passed by reference. An example of a by-value va_list is
3550 // x86, where va_list is a char*. An example of by-ref va_list
3551 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
3552 // we want this argument to be a char*&; for x86-64, we want
3553 // it to be a __va_list_tag*.
3554 Type = Context.getBuiltinVaListType();
3555 assert(!Type.isNull() && "builtin va list type not initialized!");
3556 if (Type->isArrayType()) {
3557 Type = Context.getArrayDecayedType(Type);
3558 } else {
3559 Type = Context.getLValueReferenceType(Type);
3560 }
3561 break;
3562 case 'V': {
3563 char *End;
3564
3565 unsigned NumElements = strtoul(Str, &End, 10);
3566 assert(End != Str && "Missing vector size");
3567
3568 Str = End;
3569
3570 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
3571 Type = Context.getVectorType(ElementType, NumElements);
3572 break;
3573 }
3574 case 'P': {
3575 IdentifierInfo *II = &Context.Idents.get("FILE");
3576 DeclContext::lookup_result Lookup
3577 = Context.getTranslationUnitDecl()->lookup(Context, II);
3578 if (Lookup.first != Lookup.second && isa<TypeDecl>(*Lookup.first)) {
3579 Type = Context.getTypeDeclType(cast<TypeDecl>(*Lookup.first));
3580 break;
3581 }
3582 else {
3583 Error = ASTContext::GE_Missing_FILE;
3584 return QualType();
3585 }
3586 }
3587 }
3588
3589 if (!AllowTypeModifiers)
3590 return Type;
3591
3592 Done = false;
3593 while (!Done) {
3594 switch (*Str++) {
3595 default: Done = true; --Str; break;
3596 case '*':
3597 Type = Context.getPointerType(Type);
3598 break;
3599 case '&':
3600 Type = Context.getLValueReferenceType(Type);
3601 break;
3602 // FIXME: There's no way to have a built-in with an rvalue ref arg.
3603 case 'C':
3604 Type = Type.getQualifiedType(QualType::Const);
3605 break;
3606 }
3607 }
3608
3609 return Type;
3610}
3611
3612/// GetBuiltinType - Return the type for the specified builtin.
3613QualType ASTContext::GetBuiltinType(unsigned id,
3614 GetBuiltinTypeError &Error) {
3615 const char *TypeStr = BuiltinInfo.GetTypeString(id);
3616
3617 llvm::SmallVector<QualType, 8> ArgTypes;
3618
3619 Error = GE_None;
3620 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
3621 if (Error != GE_None)
3622 return QualType();
3623 while (TypeStr[0] && TypeStr[0] != '.') {
3624 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
3625 if (Error != GE_None)
3626 return QualType();
3627
3628 // Do array -> pointer decay. The builtin should use the decayed type.
3629 if (Ty->isArrayType())
3630 Ty = getArrayDecayedType(Ty);
3631
3632 ArgTypes.push_back(Ty);
3633 }
3634
3635 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
3636 "'.' should only occur at end of builtin type list!");
3637
3638 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
3639 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
3640 return getFunctionNoProtoType(ResType);
3641 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
3642 TypeStr[0] == '.', 0);
3643}