blob: 304799cf91b9ff478e7ba74852128e8868c77019 [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"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +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"
Anders Carlsson29445a02009-07-18 21:19:52 +000027#include "RecordLayoutBuilder.h"
28
Reid Spencer5f016e22007-07-11 17:01:13 +000029using namespace clang;
30
31enum FloatingRank {
32 FloatRank, DoubleRank, LongDoubleRank
33};
34
Chris Lattner61710852008-10-05 17:34:18 +000035ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
36 TargetInfo &t,
Daniel Dunbare91593e2008-08-11 04:54:23 +000037 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +000038 Builtin::Context &builtins,
39 bool FreeMem, unsigned size_reserve) :
Douglas Gregorab452ba2009-03-26 23:50:42 +000040 GlobalNestedNameSpecifier(0), CFConstantStringTypeDecl(0),
Douglas Gregorc29f77b2009-07-07 16:35:42 +000041 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0),
42 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregor2e222532009-07-02 17:08:52 +000043 LoadedExternalComments(false), FreeMemory(FreeMem), Target(t),
44 Idents(idents), Selectors(sels),
Chris Lattnere4f21422009-06-30 01:26:17 +000045 BuiltinInfo(builtins), ExternalSource(0), PrintingPolicy(LOpts) {
Daniel Dunbare91593e2008-08-11 04:54:23 +000046 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +000047 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff14108da2009-07-10 23:34:53 +000048 InitBuiltinTypes();
Daniel Dunbare91593e2008-08-11 04:54:23 +000049}
50
Reid Spencer5f016e22007-07-11 17:01:13 +000051ASTContext::~ASTContext() {
52 // Deallocate all the types.
53 while (!Types.empty()) {
Ted Kremenek4b05b1d2008-05-21 16:38:54 +000054 Types.back()->Destroy(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +000055 Types.pop_back();
56 }
Eli Friedmanb26153c2008-05-27 03:08:09 +000057
Nuno Lopesb74668e2008-12-17 22:30:25 +000058 {
59 llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
60 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end();
61 while (I != E) {
62 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
63 delete R;
64 }
65 }
66
67 {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +000068 llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>::iterator
69 I = ObjCLayouts.begin(), E = ObjCLayouts.end();
Nuno Lopesb74668e2008-12-17 22:30:25 +000070 while (I != E) {
71 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
72 delete R;
73 }
74 }
75
Douglas Gregorab452ba2009-03-26 23:50:42 +000076 // Destroy nested-name-specifiers.
Douglas Gregor1ae0afa2009-03-27 23:54:10 +000077 for (llvm::FoldingSet<NestedNameSpecifier>::iterator
78 NNS = NestedNameSpecifiers.begin(),
79 NNSEnd = NestedNameSpecifiers.end();
Douglas Gregore7dcd782009-03-27 23:25:45 +000080 NNS != NNSEnd;
Douglas Gregor1ae0afa2009-03-27 23:54:10 +000081 /* Increment in loop */)
82 (*NNS++).Destroy(*this);
Douglas Gregorab452ba2009-03-26 23:50:42 +000083
84 if (GlobalNestedNameSpecifier)
85 GlobalNestedNameSpecifier->Destroy(*this);
86
Eli Friedmanb26153c2008-05-27 03:08:09 +000087 TUDecl->Destroy(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +000088}
89
Douglas Gregor2cf26342009-04-09 22:27:44 +000090void
91ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
92 ExternalSource.reset(Source.take());
93}
94
Reid Spencer5f016e22007-07-11 17:01:13 +000095void ASTContext::PrintStats() const {
96 fprintf(stderr, "*** AST Context Stats:\n");
97 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl7c80bd62009-03-16 23:22:08 +000098
Douglas Gregordbe833d2009-05-26 14:40:08 +000099 unsigned counts[] = {
100#define TYPE(Name, Parent) 0,
101#define ABSTRACT_TYPE(Name, Parent)
102#include "clang/AST/TypeNodes.def"
103 0 // Extra
104 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000105
Reid Spencer5f016e22007-07-11 17:01:13 +0000106 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
107 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000108 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000109 }
110
Douglas Gregordbe833d2009-05-26 14:40:08 +0000111 unsigned Idx = 0;
112 unsigned TotalBytes = 0;
113#define TYPE(Name, Parent) \
114 if (counts[Idx]) \
115 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
116 TotalBytes += counts[Idx] * sizeof(Name##Type); \
117 ++Idx;
118#define ABSTRACT_TYPE(Name, Parent)
119#include "clang/AST/TypeNodes.def"
120
121 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregor2cf26342009-04-09 22:27:44 +0000122
123 if (ExternalSource.get()) {
124 fprintf(stderr, "\n");
125 ExternalSource->PrintStats();
126 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000127}
128
129
130void ASTContext::InitBuiltinType(QualType &R, BuiltinType::Kind K) {
Steve Narofff83820b2009-01-27 22:08:43 +0000131 Types.push_back((R = QualType(new (*this,8) BuiltinType(K),0)).getTypePtr());
Reid Spencer5f016e22007-07-11 17:01:13 +0000132}
133
Reid Spencer5f016e22007-07-11 17:01:13 +0000134void ASTContext::InitBuiltinTypes() {
135 assert(VoidTy.isNull() && "Context reinitialized?");
136
137 // C99 6.2.5p19.
138 InitBuiltinType(VoidTy, BuiltinType::Void);
139
140 // C99 6.2.5p2.
141 InitBuiltinType(BoolTy, BuiltinType::Bool);
142 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000143 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000144 InitBuiltinType(CharTy, BuiltinType::Char_S);
145 else
146 InitBuiltinType(CharTy, BuiltinType::Char_U);
147 // C99 6.2.5p4.
148 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
149 InitBuiltinType(ShortTy, BuiltinType::Short);
150 InitBuiltinType(IntTy, BuiltinType::Int);
151 InitBuiltinType(LongTy, BuiltinType::Long);
152 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
153
154 // C99 6.2.5p6.
155 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
156 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
157 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
158 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
159 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
160
161 // C99 6.2.5p10.
162 InitBuiltinType(FloatTy, BuiltinType::Float);
163 InitBuiltinType(DoubleTy, BuiltinType::Double);
164 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000165
Chris Lattner2df9ced2009-04-30 02:43:43 +0000166 // GNU extension, 128-bit integers.
167 InitBuiltinType(Int128Ty, BuiltinType::Int128);
168 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
169
Chris Lattner3a250322009-02-26 23:43:47 +0000170 if (LangOpts.CPlusPlus) // C++ 3.9.1p5
171 InitBuiltinType(WCharTy, BuiltinType::WChar);
172 else // C99
173 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000174
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000175 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
176 InitBuiltinType(Char16Ty, BuiltinType::Char16);
177 else // C99
178 Char16Ty = getFromTargetType(Target.getChar16Type());
179
180 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
181 InitBuiltinType(Char32Ty, BuiltinType::Char32);
182 else // C99
183 Char32Ty = getFromTargetType(Target.getChar32Type());
184
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000185 // Placeholder type for functions.
Douglas Gregor898574e2008-12-05 23:32:09 +0000186 InitBuiltinType(OverloadTy, BuiltinType::Overload);
187
188 // Placeholder type for type-dependent expressions whose type is
189 // completely unknown. No code should ever check a type against
190 // DependentTy and users should never see it; however, it is here to
191 // help diagnose failures to properly check for type-dependent
192 // expressions.
193 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000194
Anders Carlssone89d1592009-06-26 18:41:36 +0000195 // Placeholder type for C++0x auto declarations whose real type has
196 // not yet been deduced.
197 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
198
Reid Spencer5f016e22007-07-11 17:01:13 +0000199 // C99 6.2.5p11.
200 FloatComplexTy = getComplexType(FloatTy);
201 DoubleComplexTy = getComplexType(DoubleTy);
202 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000203
Steve Naroff7e219e42007-10-15 14:41:52 +0000204 BuiltinVaListType = QualType();
Anders Carlsson8baaca52007-10-31 02:53:19 +0000205
Steve Naroffde2e22d2009-07-15 18:40:39 +0000206 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
207 ObjCIdTypedefType = QualType();
208 ObjCClassTypedefType = QualType();
209
210 // Builtin types for 'id' and 'Class'.
211 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
212 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Steve Naroff14108da2009-07-10 23:34:53 +0000213
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000214 ObjCConstantStringType = QualType();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000215
216 // void * type
217 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000218
219 // nullptr type (C++0x 2.14.7)
220 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000221}
222
Douglas Gregor2e222532009-07-02 17:08:52 +0000223namespace {
224 class BeforeInTranslationUnit
225 : std::binary_function<SourceRange, SourceRange, bool> {
226 SourceManager *SourceMgr;
227
228 public:
229 explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { }
230
231 bool operator()(SourceRange X, SourceRange Y) {
232 return SourceMgr->isBeforeInTranslationUnit(X.getBegin(), Y.getBegin());
233 }
234 };
235}
236
237/// \brief Determine whether the given comment is a Doxygen-style comment.
238///
239/// \param Start the start of the comment text.
240///
241/// \param End the end of the comment text.
242///
243/// \param Member whether we want to check whether this is a member comment
244/// (which requires a < after the Doxygen-comment delimiter). Otherwise,
245/// we only return true when we find a non-member comment.
246static bool
247isDoxygenComment(SourceManager &SourceMgr, SourceRange Comment,
248 bool Member = false) {
249 const char *BufferStart
250 = SourceMgr.getBufferData(SourceMgr.getFileID(Comment.getBegin())).first;
251 const char *Start = BufferStart + SourceMgr.getFileOffset(Comment.getBegin());
252 const char* End = BufferStart + SourceMgr.getFileOffset(Comment.getEnd());
253
254 if (End - Start < 4)
255 return false;
256
257 assert(Start[0] == '/' && "Not a comment?");
258 if (Start[1] == '*' && !(Start[2] == '!' || Start[2] == '*'))
259 return false;
260 if (Start[1] == '/' && !(Start[2] == '!' || Start[2] == '/'))
261 return false;
262
263 return (Start[3] == '<') == Member;
264}
265
266/// \brief Retrieve the comment associated with the given declaration, if
267/// it has one.
268const char *ASTContext::getCommentForDecl(const Decl *D) {
269 if (!D)
270 return 0;
271
272 // Check whether we have cached a comment string for this declaration
273 // already.
274 llvm::DenseMap<const Decl *, std::string>::iterator Pos
275 = DeclComments.find(D);
276 if (Pos != DeclComments.end())
277 return Pos->second.c_str();
278
279 // If we have an external AST source and have not yet loaded comments from
280 // that source, do so now.
281 if (ExternalSource && !LoadedExternalComments) {
282 std::vector<SourceRange> LoadedComments;
283 ExternalSource->ReadComments(LoadedComments);
284
285 if (!LoadedComments.empty())
286 Comments.insert(Comments.begin(), LoadedComments.begin(),
287 LoadedComments.end());
288
289 LoadedExternalComments = true;
290 }
291
292 // If there are no comments anywhere, we won't find anything.
293 if (Comments.empty())
294 return 0;
295
296 // If the declaration doesn't map directly to a location in a file, we
297 // can't find the comment.
298 SourceLocation DeclStartLoc = D->getLocStart();
299 if (DeclStartLoc.isInvalid() || !DeclStartLoc.isFileID())
300 return 0;
301
302 // Find the comment that occurs just before this declaration.
303 std::vector<SourceRange>::iterator LastComment
304 = std::lower_bound(Comments.begin(), Comments.end(),
305 SourceRange(DeclStartLoc),
306 BeforeInTranslationUnit(&SourceMgr));
307
308 // Decompose the location for the start of the declaration and find the
309 // beginning of the file buffer.
310 std::pair<FileID, unsigned> DeclStartDecomp
311 = SourceMgr.getDecomposedLoc(DeclStartLoc);
312 const char *FileBufferStart
313 = SourceMgr.getBufferData(DeclStartDecomp.first).first;
314
315 // First check whether we have a comment for a member.
316 if (LastComment != Comments.end() &&
317 !isa<TagDecl>(D) && !isa<NamespaceDecl>(D) &&
318 isDoxygenComment(SourceMgr, *LastComment, true)) {
319 std::pair<FileID, unsigned> LastCommentEndDecomp
320 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
321 if (DeclStartDecomp.first == LastCommentEndDecomp.first &&
322 SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second)
323 == SourceMgr.getLineNumber(LastCommentEndDecomp.first,
324 LastCommentEndDecomp.second)) {
325 // The Doxygen member comment comes after the declaration starts and
326 // is on the same line and in the same file as the declaration. This
327 // is the comment we want.
328 std::string &Result = DeclComments[D];
329 Result.append(FileBufferStart +
330 SourceMgr.getFileOffset(LastComment->getBegin()),
331 FileBufferStart + LastCommentEndDecomp.second + 1);
332 return Result.c_str();
333 }
334 }
335
336 if (LastComment == Comments.begin())
337 return 0;
338 --LastComment;
339
340 // Decompose the end of the comment.
341 std::pair<FileID, unsigned> LastCommentEndDecomp
342 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
343
344 // If the comment and the declaration aren't in the same file, then they
345 // aren't related.
346 if (DeclStartDecomp.first != LastCommentEndDecomp.first)
347 return 0;
348
349 // Check that we actually have a Doxygen comment.
350 if (!isDoxygenComment(SourceMgr, *LastComment))
351 return 0;
352
353 // Compute the starting line for the declaration and for the end of the
354 // comment (this is expensive).
355 unsigned DeclStartLine
356 = SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second);
357 unsigned CommentEndLine
358 = SourceMgr.getLineNumber(LastCommentEndDecomp.first,
359 LastCommentEndDecomp.second);
360
361 // If the comment does not end on the line prior to the declaration, then
362 // the comment is not associated with the declaration at all.
363 if (CommentEndLine + 1 != DeclStartLine)
364 return 0;
365
366 // We have a comment, but there may be more comments on the previous lines.
367 // Keep looking so long as the comments are still Doxygen comments and are
368 // still adjacent.
369 unsigned ExpectedLine
370 = SourceMgr.getSpellingLineNumber(LastComment->getBegin()) - 1;
371 std::vector<SourceRange>::iterator FirstComment = LastComment;
372 while (FirstComment != Comments.begin()) {
373 // Look at the previous comment
374 --FirstComment;
375 std::pair<FileID, unsigned> Decomp
376 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
377
378 // If this previous comment is in a different file, we're done.
379 if (Decomp.first != DeclStartDecomp.first) {
380 ++FirstComment;
381 break;
382 }
383
384 // If this comment is not a Doxygen comment, we're done.
385 if (!isDoxygenComment(SourceMgr, *FirstComment)) {
386 ++FirstComment;
387 break;
388 }
389
390 // If the line number is not what we expected, we're done.
391 unsigned Line = SourceMgr.getLineNumber(Decomp.first, Decomp.second);
392 if (Line != ExpectedLine) {
393 ++FirstComment;
394 break;
395 }
396
397 // Set the next expected line number.
398 ExpectedLine
399 = SourceMgr.getSpellingLineNumber(FirstComment->getBegin()) - 1;
400 }
401
402 // The iterator range [FirstComment, LastComment] contains all of the
403 // BCPL comments that, together, are associated with this declaration.
404 // Form a single comment block string for this declaration that concatenates
405 // all of these comments.
406 std::string &Result = DeclComments[D];
407 while (FirstComment != LastComment) {
408 std::pair<FileID, unsigned> DecompStart
409 = SourceMgr.getDecomposedLoc(FirstComment->getBegin());
410 std::pair<FileID, unsigned> DecompEnd
411 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
412 Result.append(FileBufferStart + DecompStart.second,
413 FileBufferStart + DecompEnd.second + 1);
414 ++FirstComment;
415 }
416
417 // Append the last comment line.
418 Result.append(FileBufferStart +
419 SourceMgr.getFileOffset(LastComment->getBegin()),
420 FileBufferStart + LastCommentEndDecomp.second + 1);
421 return Result.c_str();
422}
423
Chris Lattner464175b2007-07-18 17:52:12 +0000424//===----------------------------------------------------------------------===//
425// Type Sizing and Analysis
426//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000427
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000428/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
429/// scalar floating point type.
430const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
431 const BuiltinType *BT = T->getAsBuiltinType();
432 assert(BT && "Not a floating point type!");
433 switch (BT->getKind()) {
434 default: assert(0 && "Not a floating point type!");
435 case BuiltinType::Float: return Target.getFloatFormat();
436 case BuiltinType::Double: return Target.getDoubleFormat();
437 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
438 }
439}
440
Chris Lattneraf707ab2009-01-24 21:53:27 +0000441/// getDeclAlign - Return a conservative estimate of the alignment of the
442/// specified decl. Note that bitfields do not have a valid alignment, so
443/// this method will assert on them.
Daniel Dunbarb7d08442009-02-17 22:16:19 +0000444unsigned ASTContext::getDeclAlignInBytes(const Decl *D) {
Eli Friedmandcdafb62009-02-22 02:56:25 +0000445 unsigned Align = Target.getCharWidth();
446
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000447 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
Eli Friedmandcdafb62009-02-22 02:56:25 +0000448 Align = std::max(Align, AA->getAlignment());
449
Chris Lattneraf707ab2009-01-24 21:53:27 +0000450 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
451 QualType T = VD->getType();
Ted Kremenek35366a62009-07-17 17:50:17 +0000452 if (const ReferenceType* RT = T->getAsReferenceType()) {
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000453 unsigned AS = RT->getPointeeType().getAddressSpace();
Anders Carlssonf0930232009-04-10 04:52:36 +0000454 Align = Target.getPointerAlign(AS);
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000455 } else if (!T->isIncompleteType() && !T->isFunctionType()) {
456 // Incomplete or function types default to 1.
Eli Friedmandcdafb62009-02-22 02:56:25 +0000457 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
458 T = cast<ArrayType>(T)->getElementType();
459
460 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
461 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000462 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000463
464 return Align / Target.getCharWidth();
Chris Lattneraf707ab2009-01-24 21:53:27 +0000465}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000466
Chris Lattnera7674d82007-07-13 22:13:22 +0000467/// getTypeSize - Return the size of the specified type, in bits. This method
468/// does not work on incomplete types.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000469std::pair<uint64_t, unsigned>
Daniel Dunbar1d751182008-11-08 05:48:37 +0000470ASTContext::getTypeInfo(const Type *T) {
Mike Stump5e301002009-02-27 18:32:39 +0000471 uint64_t Width=0;
472 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000473 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000474#define TYPE(Class, Base)
475#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000476#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000477#define DEPENDENT_TYPE(Class, Base) case Type::Class:
478#include "clang/AST/TypeNodes.def"
Douglas Gregor18857642009-04-30 17:32:17 +0000479 assert(false && "Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000480 break;
481
Chris Lattner692233e2007-07-13 22:27:08 +0000482 case Type::FunctionNoProto:
483 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000484 // GCC extension: alignof(function) = 32 bits
485 Width = 0;
486 Align = 32;
487 break;
488
Douglas Gregor72564e72009-02-26 23:50:07 +0000489 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000490 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000491 Width = 0;
492 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
493 break;
494
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +0000495 case Type::ConstantArrayWithExpr:
496 case Type::ConstantArrayWithoutExpr:
Steve Narofffb22d962007-08-30 01:06:46 +0000497 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000498 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Steve Narofffb22d962007-08-30 01:06:46 +0000499
Chris Lattner98be4942008-03-05 18:54:05 +0000500 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000501 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000502 Align = EltInfo.second;
503 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000504 }
Nate Begeman213541a2008-04-18 23:10:10 +0000505 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000506 case Type::Vector: {
507 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000508 getTypeInfo(cast<VectorType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000509 Width = EltInfo.first*cast<VectorType>(T)->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000510 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000511 // If the alignment is not a power of 2, round up to the next power of 2.
512 // This happens for non-power-of-2 length vectors.
513 // FIXME: this should probably be a target property.
514 Align = 1 << llvm::Log2_32_Ceil(Align);
Chris Lattner030d8842007-07-19 22:06:24 +0000515 break;
516 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000517
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000518 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000519 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000520 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000521 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000522 // GCC extension: alignof(void) = 8 bits.
523 Width = 0;
524 Align = 8;
525 break;
526
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000527 case BuiltinType::Bool:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000528 Width = Target.getBoolWidth();
529 Align = Target.getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000530 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000531 case BuiltinType::Char_S:
532 case BuiltinType::Char_U:
533 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000534 case BuiltinType::SChar:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000535 Width = Target.getCharWidth();
536 Align = Target.getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000537 break;
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000538 case BuiltinType::WChar:
539 Width = Target.getWCharWidth();
540 Align = Target.getWCharAlign();
541 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000542 case BuiltinType::Char16:
543 Width = Target.getChar16Width();
544 Align = Target.getChar16Align();
545 break;
546 case BuiltinType::Char32:
547 Width = Target.getChar32Width();
548 Align = Target.getChar32Align();
549 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000550 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000551 case BuiltinType::Short:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000552 Width = Target.getShortWidth();
553 Align = Target.getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000554 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000555 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000556 case BuiltinType::Int:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000557 Width = Target.getIntWidth();
558 Align = Target.getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000559 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000560 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000561 case BuiltinType::Long:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000562 Width = Target.getLongWidth();
563 Align = Target.getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000564 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000565 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000566 case BuiltinType::LongLong:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000567 Width = Target.getLongLongWidth();
568 Align = Target.getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000569 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000570 case BuiltinType::Int128:
571 case BuiltinType::UInt128:
572 Width = 128;
573 Align = 128; // int128_t is 128-bit aligned on all targets.
574 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000575 case BuiltinType::Float:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000576 Width = Target.getFloatWidth();
577 Align = Target.getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000578 break;
579 case BuiltinType::Double:
Chris Lattner5426bf62008-04-07 07:01:58 +0000580 Width = Target.getDoubleWidth();
581 Align = Target.getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000582 break;
583 case BuiltinType::LongDouble:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000584 Width = Target.getLongDoubleWidth();
585 Align = Target.getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000586 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000587 case BuiltinType::NullPtr:
588 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
589 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000590 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000591 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000592 break;
Eli Friedmanf98aba32009-02-13 02:31:07 +0000593 case Type::FixedWidthInt:
594 // FIXME: This isn't precisely correct; the width/alignment should depend
595 // on the available types for the target
596 Width = cast<FixedWidthIntType>(T)->getWidth();
Chris Lattner736166b2009-02-15 21:20:13 +0000597 Width = std::max(llvm::NextPowerOf2(Width - 1), (uint64_t)8);
Eli Friedmanf98aba32009-02-13 02:31:07 +0000598 Align = Width;
599 break;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000600 case Type::ExtQual:
Chris Lattner98be4942008-03-05 18:54:05 +0000601 // FIXME: Pointers into different addr spaces could have different sizes and
602 // alignment requirements: getPointerInfo should take an AddrSpace.
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000603 return getTypeInfo(QualType(cast<ExtQualType>(T)->getBaseType(), 0));
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000604 case Type::ObjCObjectPointer:
Chris Lattner5426bf62008-04-07 07:01:58 +0000605 Width = Target.getPointerWidth(0);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000606 Align = Target.getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000607 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000608 case Type::BlockPointer: {
609 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
610 Width = Target.getPointerWidth(AS);
611 Align = Target.getPointerAlign(AS);
612 break;
613 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000614 case Type::Pointer: {
615 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner5426bf62008-04-07 07:01:58 +0000616 Width = Target.getPointerWidth(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000617 Align = Target.getPointerAlign(AS);
618 break;
619 }
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000620 case Type::LValueReference:
621 case Type::RValueReference:
Chris Lattner7ab2ed82007-07-13 22:16:13 +0000622 // "When applied to a reference or a reference type, the result is the size
Chris Lattner5d2a6302007-07-18 18:26:58 +0000623 // of the referenced type." C++98 5.3.3p2: expr.sizeof.
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000624 // FIXME: This is wrong for struct layout: a reference in a struct has
625 // pointer size.
Chris Lattnerbdcd6372008-04-02 17:35:06 +0000626 return getTypeInfo(cast<ReferenceType>(T)->getPointeeType());
Sebastian Redlf30208a2009-01-24 21:16:55 +0000627 case Type::MemberPointer: {
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000628 // FIXME: This is ABI dependent. We use the Itanium C++ ABI.
629 // http://www.codesourcery.com/public/cxx-abi/abi.html#member-pointers
630 // If we ever want to support other ABIs this needs to be abstracted.
631
Sebastian Redlf30208a2009-01-24 21:16:55 +0000632 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000633 std::pair<uint64_t, unsigned> PtrDiffInfo =
634 getTypeInfo(getPointerDiffType());
635 Width = PtrDiffInfo.first;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000636 if (Pointee->isFunctionType())
637 Width *= 2;
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000638 Align = PtrDiffInfo.second;
639 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000640 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000641 case Type::Complex: {
642 // Complex types have the same alignment as their elements, but twice the
643 // size.
644 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000645 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000646 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000647 Align = EltInfo.second;
648 break;
649 }
Devang Patel44a3dde2008-06-04 21:54:36 +0000650 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000651 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000652 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
653 Width = Layout.getSize();
654 Align = Layout.getAlignment();
655 break;
656 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000657 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000658 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000659 const TagType *TT = cast<TagType>(T);
660
661 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner8389eab2008-08-09 21:35:13 +0000662 Width = 1;
663 Align = 1;
664 break;
665 }
666
Daniel Dunbar1d751182008-11-08 05:48:37 +0000667 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000668 return getTypeInfo(ET->getDecl()->getIntegerType());
669
Daniel Dunbar1d751182008-11-08 05:48:37 +0000670 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000671 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
672 Width = Layout.getSize();
673 Align = Layout.getAlignment();
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000674 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000675 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000676
Douglas Gregor18857642009-04-30 17:32:17 +0000677 case Type::Typedef: {
678 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000679 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
Douglas Gregor18857642009-04-30 17:32:17 +0000680 Align = Aligned->getAlignment();
681 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
682 } else
683 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregor7532dc62009-03-30 22:58:21 +0000684 break;
Chris Lattner71763312008-04-06 22:05:18 +0000685 }
Douglas Gregor18857642009-04-30 17:32:17 +0000686
687 case Type::TypeOfExpr:
688 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
689 .getTypePtr());
690
691 case Type::TypeOf:
692 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
693
Anders Carlsson395b4752009-06-24 19:06:50 +0000694 case Type::Decltype:
695 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
696 .getTypePtr());
697
Douglas Gregor18857642009-04-30 17:32:17 +0000698 case Type::QualifiedName:
699 return getTypeInfo(cast<QualifiedNameType>(T)->getNamedType().getTypePtr());
700
701 case Type::TemplateSpecialization:
702 assert(getCanonicalType(T) != T &&
703 "Cannot request the size of a dependent type");
704 // FIXME: this is likely to be wrong once we support template
705 // aliases, since a template alias could refer to a typedef that
706 // has an __aligned__ attribute on it.
707 return getTypeInfo(getCanonicalType(T));
708 }
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000709
Chris Lattner464175b2007-07-18 17:52:12 +0000710 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000711 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +0000712}
713
Chris Lattner34ebde42009-01-27 18:08:34 +0000714/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
715/// type for the current target in bits. This can be different than the ABI
716/// alignment in cases where it is beneficial for performance to overalign
717/// a data type.
718unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
719 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +0000720
721 // Double and long long should be naturally aligned if possible.
722 if (const ComplexType* CT = T->getAsComplexType())
723 T = CT->getElementType().getTypePtr();
724 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
725 T->isSpecificBuiltinType(BuiltinType::LongLong))
726 return std::max(ABIAlign, (unsigned)getTypeSize(T));
727
Chris Lattner34ebde42009-01-27 18:08:34 +0000728 return ABIAlign;
729}
730
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000731static void CollectLocalObjCIvars(ASTContext *Ctx,
732 const ObjCInterfaceDecl *OI,
733 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000734 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
735 E = OI->ivar_end(); I != E; ++I) {
Chris Lattnerf1690852009-03-31 08:48:01 +0000736 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000737 if (!IVDecl->isInvalidDecl())
738 Fields.push_back(cast<FieldDecl>(IVDecl));
739 }
740}
741
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000742void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
743 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
744 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
745 CollectObjCIvars(SuperClass, Fields);
746 CollectLocalObjCIvars(this, OI, Fields);
747}
748
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000749/// ShallowCollectObjCIvars -
750/// Collect all ivars, including those synthesized, in the current class.
751///
752void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
753 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars,
754 bool CollectSynthesized) {
755 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
756 E = OI->ivar_end(); I != E; ++I) {
757 Ivars.push_back(*I);
758 }
759 if (CollectSynthesized)
760 CollectSynthesizedIvars(OI, Ivars);
761}
762
Fariborz Jahanian98200742009-05-12 18:14:29 +0000763void ASTContext::CollectProtocolSynthesizedIvars(const ObjCProtocolDecl *PD,
764 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000765 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
766 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian98200742009-05-12 18:14:29 +0000767 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
768 Ivars.push_back(Ivar);
769
770 // Also look into nested protocols.
771 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
772 E = PD->protocol_end(); P != E; ++P)
773 CollectProtocolSynthesizedIvars(*P, Ivars);
774}
775
776/// CollectSynthesizedIvars -
777/// This routine collect synthesized ivars for the designated class.
778///
779void ASTContext::CollectSynthesizedIvars(const ObjCInterfaceDecl *OI,
780 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000781 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
782 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian98200742009-05-12 18:14:29 +0000783 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
784 Ivars.push_back(Ivar);
785 }
786 // Also look into interface's protocol list for properties declared
787 // in the protocol and whose ivars are synthesized.
788 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
789 PE = OI->protocol_end(); P != PE; ++P) {
790 ObjCProtocolDecl *PD = (*P);
791 CollectProtocolSynthesizedIvars(PD, Ivars);
792 }
793}
794
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000795unsigned ASTContext::CountProtocolSynthesizedIvars(const ObjCProtocolDecl *PD) {
796 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000797 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
798 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000799 if ((*I)->getPropertyIvarDecl())
800 ++count;
801
802 // Also look into nested protocols.
803 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
804 E = PD->protocol_end(); P != E; ++P)
805 count += CountProtocolSynthesizedIvars(*P);
806 return count;
807}
808
809unsigned ASTContext::CountSynthesizedIvars(const ObjCInterfaceDecl *OI)
810{
811 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000812 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
813 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000814 if ((*I)->getPropertyIvarDecl())
815 ++count;
816 }
817 // Also look into interface's protocol list for properties declared
818 // in the protocol and whose ivars are synthesized.
819 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
820 PE = OI->protocol_end(); P != PE; ++P) {
821 ObjCProtocolDecl *PD = (*P);
822 count += CountProtocolSynthesizedIvars(PD);
823 }
824 return count;
825}
826
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +0000827/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
828ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
829 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
830 I = ObjCImpls.find(D);
831 if (I != ObjCImpls.end())
832 return cast<ObjCImplementationDecl>(I->second);
833 return 0;
834}
835/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
836ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
837 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
838 I = ObjCImpls.find(D);
839 if (I != ObjCImpls.end())
840 return cast<ObjCCategoryImplDecl>(I->second);
841 return 0;
842}
843
844/// \brief Set the implementation of ObjCInterfaceDecl.
845void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
846 ObjCImplementationDecl *ImplD) {
847 assert(IFaceD && ImplD && "Passed null params");
848 ObjCImpls[IFaceD] = ImplD;
849}
850/// \brief Set the implementation of ObjCCategoryDecl.
851void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
852 ObjCCategoryImplDecl *ImplD) {
853 assert(CatD && ImplD && "Passed null params");
854 ObjCImpls[CatD] = ImplD;
855}
856
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000857/// getInterfaceLayoutImpl - Get or compute information about the
858/// layout of the given interface.
859///
860/// \param Impl - If given, also include the layout of the interface's
861/// implementation. This may differ by including synthesized ivars.
Devang Patel44a3dde2008-06-04 21:54:36 +0000862const ASTRecordLayout &
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000863ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
864 const ObjCImplementationDecl *Impl) {
Daniel Dunbar532d4da2009-05-03 13:15:50 +0000865 assert(!D->isForwardDecl() && "Invalid interface decl!");
866
Devang Patel44a3dde2008-06-04 21:54:36 +0000867 // Look up this layout, if already laid out, return what we have.
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000868 ObjCContainerDecl *Key =
869 Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
870 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
871 return *Entry;
Devang Patel44a3dde2008-06-04 21:54:36 +0000872
Daniel Dunbar453addb2009-05-03 11:16:44 +0000873 // Add in synthesized ivar count if laying out an implementation.
874 if (Impl) {
Anders Carlsson29445a02009-07-18 21:19:52 +0000875 unsigned FieldCount = D->ivar_size();
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000876 unsigned SynthCount = CountSynthesizedIvars(D);
877 FieldCount += SynthCount;
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000878 // If there aren't any sythesized ivars then reuse the interface
Daniel Dunbar453addb2009-05-03 11:16:44 +0000879 // entry. Note we can't cache this because we simply free all
880 // entries later; however we shouldn't look up implementations
881 // frequently.
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000882 if (SynthCount == 0)
Daniel Dunbar453addb2009-05-03 11:16:44 +0000883 return getObjCLayout(D, 0);
884 }
885
Anders Carlsson29445a02009-07-18 21:19:52 +0000886 const ASTRecordLayout *NewEntry =
887 ASTRecordLayoutBuilder::ComputeLayout(*this, D, Impl);
888 ObjCLayouts[Key] = NewEntry;
889
Devang Patel44a3dde2008-06-04 21:54:36 +0000890 return *NewEntry;
891}
892
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000893const ASTRecordLayout &
894ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
895 return getObjCLayout(D, 0);
896}
897
898const ASTRecordLayout &
899ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
900 return getObjCLayout(D->getClassInterface(), D);
901}
902
Devang Patel88a981b2007-11-01 19:11:01 +0000903/// getASTRecordLayout - Get or compute information about the layout of the
Chris Lattner464175b2007-07-18 17:52:12 +0000904/// specified record (struct/union/class), which indicates its size and field
905/// position information.
Chris Lattner98be4942008-03-05 18:54:05 +0000906const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +0000907 D = D->getDefinition(*this);
908 assert(D && "Cannot get layout of forward declarations!");
Eli Friedman4bd998b2008-05-30 09:31:38 +0000909
Chris Lattner464175b2007-07-18 17:52:12 +0000910 // Look up this layout, if already laid out, return what we have.
Devang Patel88a981b2007-11-01 19:11:01 +0000911 const ASTRecordLayout *&Entry = ASTRecordLayouts[D];
Chris Lattner464175b2007-07-18 17:52:12 +0000912 if (Entry) return *Entry;
Eli Friedman4bd998b2008-05-30 09:31:38 +0000913
Anders Carlsson29445a02009-07-18 21:19:52 +0000914 const ASTRecordLayout *NewEntry =
915 ASTRecordLayoutBuilder::ComputeLayout(*this, D);
Chris Lattner464175b2007-07-18 17:52:12 +0000916 Entry = NewEntry;
Anders Carlsson29445a02009-07-18 21:19:52 +0000917
Chris Lattner5d2a6302007-07-18 18:26:58 +0000918 return *NewEntry;
Chris Lattner464175b2007-07-18 17:52:12 +0000919}
920
Chris Lattnera7674d82007-07-13 22:13:22 +0000921//===----------------------------------------------------------------------===//
922// Type creation/memoization methods
923//===----------------------------------------------------------------------===//
924
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000925QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerf52ab252008-04-06 22:59:24 +0000926 QualType CanT = getCanonicalType(T);
927 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +0000928 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +0000929
930 // If we are composing extended qualifiers together, merge together into one
931 // ExtQualType node.
932 unsigned CVRQuals = T.getCVRQualifiers();
933 QualType::GCAttrTypes GCAttr = QualType::GCNone;
934 Type *TypeNode = T.getTypePtr();
Chris Lattnerf46699c2008-02-20 20:55:12 +0000935
Chris Lattnerb7d25532009-02-18 22:53:11 +0000936 if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
937 // If this type already has an address space specified, it cannot get
938 // another one.
939 assert(EQT->getAddressSpace() == 0 &&
940 "Type cannot be in multiple addr spaces!");
941 GCAttr = EQT->getObjCGCAttr();
942 TypeNode = EQT->getBaseType();
943 }
Chris Lattnerf46699c2008-02-20 20:55:12 +0000944
Chris Lattnerb7d25532009-02-18 22:53:11 +0000945 // Check if we've already instantiated this type.
Christopher Lambebb97e92008-02-04 02:31:56 +0000946 llvm::FoldingSetNodeID ID;
Chris Lattnerb7d25532009-02-18 22:53:11 +0000947 ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
Christopher Lambebb97e92008-02-04 02:31:56 +0000948 void *InsertPos = 0;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000949 if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattnerb7d25532009-02-18 22:53:11 +0000950 return QualType(EXTQy, CVRQuals);
951
Christopher Lambebb97e92008-02-04 02:31:56 +0000952 // If the base type isn't canonical, this won't be a canonical type either,
953 // so fill in the canonical type field.
954 QualType Canonical;
Chris Lattnerb7d25532009-02-18 22:53:11 +0000955 if (!TypeNode->isCanonical()) {
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000956 Canonical = getAddrSpaceQualType(CanT, AddressSpace);
Christopher Lambebb97e92008-02-04 02:31:56 +0000957
Chris Lattnerb7d25532009-02-18 22:53:11 +0000958 // Update InsertPos, the previous call could have invalidated it.
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000959 ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +0000960 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Christopher Lambebb97e92008-02-04 02:31:56 +0000961 }
Chris Lattnerb7d25532009-02-18 22:53:11 +0000962 ExtQualType *New =
963 new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000964 ExtQualTypes.InsertNode(New, InsertPos);
Christopher Lambebb97e92008-02-04 02:31:56 +0000965 Types.push_back(New);
Chris Lattnerb7d25532009-02-18 22:53:11 +0000966 return QualType(New, CVRQuals);
Christopher Lambebb97e92008-02-04 02:31:56 +0000967}
968
Chris Lattnerb7d25532009-02-18 22:53:11 +0000969QualType ASTContext::getObjCGCQualType(QualType T,
970 QualType::GCAttrTypes GCAttr) {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000971 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +0000972 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000973 return T;
974
Fariborz Jahanian4027cd12009-06-03 17:15:17 +0000975 if (T->isPointerType()) {
Ted Kremenek35366a62009-07-17 17:50:17 +0000976 QualType Pointee = T->getAsPointerType()->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +0000977 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +0000978 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
979 return getPointerType(ResultType);
980 }
981 }
Chris Lattnerb7d25532009-02-18 22:53:11 +0000982 // If we are composing extended qualifiers together, merge together into one
983 // ExtQualType node.
984 unsigned CVRQuals = T.getCVRQualifiers();
985 Type *TypeNode = T.getTypePtr();
986 unsigned AddressSpace = 0;
987
988 if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
989 // If this type already has an address space specified, it cannot get
990 // another one.
991 assert(EQT->getObjCGCAttr() == QualType::GCNone &&
992 "Type cannot be in multiple addr spaces!");
993 AddressSpace = EQT->getAddressSpace();
994 TypeNode = EQT->getBaseType();
995 }
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000996
997 // Check if we've already instantiated an gc qual'd type of this type.
998 llvm::FoldingSetNodeID ID;
Chris Lattnerb7d25532009-02-18 22:53:11 +0000999 ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001000 void *InsertPos = 0;
1001 if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattnerb7d25532009-02-18 22:53:11 +00001002 return QualType(EXTQy, CVRQuals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001003
1004 // If the base type isn't canonical, this won't be a canonical type either,
1005 // so fill in the canonical type field.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00001006 // FIXME: Isn't this also not canonical if the base type is a array
1007 // or pointer type? I can't find any documentation for objc_gc, though...
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001008 QualType Canonical;
1009 if (!T->isCanonical()) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00001010 Canonical = getObjCGCQualType(CanT, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001011
Chris Lattnerb7d25532009-02-18 22:53:11 +00001012 // Update InsertPos, the previous call could have invalidated it.
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001013 ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
1014 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1015 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00001016 ExtQualType *New =
1017 new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001018 ExtQualTypes.InsertNode(New, InsertPos);
1019 Types.push_back(New);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001020 return QualType(New, CVRQuals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001021}
Chris Lattnera7674d82007-07-13 22:13:22 +00001022
Reid Spencer5f016e22007-07-11 17:01:13 +00001023/// getComplexType - Return the uniqued reference to the type for a complex
1024/// number with the specified element type.
1025QualType ASTContext::getComplexType(QualType T) {
1026 // Unique pointers, to guarantee there is only one pointer of a particular
1027 // structure.
1028 llvm::FoldingSetNodeID ID;
1029 ComplexType::Profile(ID, T);
1030
1031 void *InsertPos = 0;
1032 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1033 return QualType(CT, 0);
1034
1035 // If the pointee type isn't canonical, this won't be a canonical type either,
1036 // so fill in the canonical type field.
1037 QualType Canonical;
1038 if (!T->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001039 Canonical = getComplexType(getCanonicalType(T));
Reid Spencer5f016e22007-07-11 17:01:13 +00001040
1041 // Get the new insert position for the node we care about.
1042 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001043 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001044 }
Steve Narofff83820b2009-01-27 22:08:43 +00001045 ComplexType *New = new (*this,8) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001046 Types.push_back(New);
1047 ComplexTypes.InsertNode(New, InsertPos);
1048 return QualType(New, 0);
1049}
1050
Eli Friedmanf98aba32009-02-13 02:31:07 +00001051QualType ASTContext::getFixedWidthIntType(unsigned Width, bool Signed) {
1052 llvm::DenseMap<unsigned, FixedWidthIntType*> &Map = Signed ?
1053 SignedFixedWidthIntTypes : UnsignedFixedWidthIntTypes;
1054 FixedWidthIntType *&Entry = Map[Width];
1055 if (!Entry)
1056 Entry = new FixedWidthIntType(Width, Signed);
1057 return QualType(Entry, 0);
1058}
Reid Spencer5f016e22007-07-11 17:01:13 +00001059
1060/// getPointerType - Return the uniqued reference to the type for a pointer to
1061/// the specified type.
1062QualType ASTContext::getPointerType(QualType T) {
1063 // Unique pointers, to guarantee there is only one pointer of a particular
1064 // structure.
1065 llvm::FoldingSetNodeID ID;
1066 PointerType::Profile(ID, T);
1067
1068 void *InsertPos = 0;
1069 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1070 return QualType(PT, 0);
1071
1072 // If the pointee type isn't canonical, this won't be a canonical type either,
1073 // so fill in the canonical type field.
1074 QualType Canonical;
1075 if (!T->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001076 Canonical = getPointerType(getCanonicalType(T));
Reid Spencer5f016e22007-07-11 17:01:13 +00001077
1078 // Get the new insert position for the node we care about.
1079 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001080 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001081 }
Steve Narofff83820b2009-01-27 22:08:43 +00001082 PointerType *New = new (*this,8) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001083 Types.push_back(New);
1084 PointerTypes.InsertNode(New, InsertPos);
1085 return QualType(New, 0);
1086}
1087
Steve Naroff5618bd42008-08-27 16:04:49 +00001088/// getBlockPointerType - Return the uniqued reference to the type for
1089/// a pointer to the specified block.
1090QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff296e8d52008-08-28 19:20:44 +00001091 assert(T->isFunctionType() && "block of function types only");
1092 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001093 // structure.
1094 llvm::FoldingSetNodeID ID;
1095 BlockPointerType::Profile(ID, T);
1096
1097 void *InsertPos = 0;
1098 if (BlockPointerType *PT =
1099 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1100 return QualType(PT, 0);
1101
Steve Naroff296e8d52008-08-28 19:20:44 +00001102 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001103 // type either so fill in the canonical type field.
1104 QualType Canonical;
1105 if (!T->isCanonical()) {
1106 Canonical = getBlockPointerType(getCanonicalType(T));
1107
1108 // Get the new insert position for the node we care about.
1109 BlockPointerType *NewIP =
1110 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001111 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001112 }
Steve Narofff83820b2009-01-27 22:08:43 +00001113 BlockPointerType *New = new (*this,8) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001114 Types.push_back(New);
1115 BlockPointerTypes.InsertNode(New, InsertPos);
1116 return QualType(New, 0);
1117}
1118
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001119/// getLValueReferenceType - Return the uniqued reference to the type for an
1120/// lvalue reference to the specified type.
1121QualType ASTContext::getLValueReferenceType(QualType T) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001122 // Unique pointers, to guarantee there is only one pointer of a particular
1123 // structure.
1124 llvm::FoldingSetNodeID ID;
1125 ReferenceType::Profile(ID, T);
1126
1127 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001128 if (LValueReferenceType *RT =
1129 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001130 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001131
Reid Spencer5f016e22007-07-11 17:01:13 +00001132 // If the referencee type isn't canonical, this won't be a canonical type
1133 // either, so fill in the canonical type field.
1134 QualType Canonical;
1135 if (!T->isCanonical()) {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001136 Canonical = getLValueReferenceType(getCanonicalType(T));
1137
Reid Spencer5f016e22007-07-11 17:01:13 +00001138 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001139 LValueReferenceType *NewIP =
1140 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001141 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001142 }
1143
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001144 LValueReferenceType *New = new (*this,8) LValueReferenceType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001145 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001146 LValueReferenceTypes.InsertNode(New, InsertPos);
1147 return QualType(New, 0);
1148}
1149
1150/// getRValueReferenceType - Return the uniqued reference to the type for an
1151/// rvalue reference to the specified type.
1152QualType ASTContext::getRValueReferenceType(QualType T) {
1153 // Unique pointers, to guarantee there is only one pointer of a particular
1154 // structure.
1155 llvm::FoldingSetNodeID ID;
1156 ReferenceType::Profile(ID, T);
1157
1158 void *InsertPos = 0;
1159 if (RValueReferenceType *RT =
1160 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1161 return QualType(RT, 0);
1162
1163 // If the referencee type isn't canonical, this won't be a canonical type
1164 // either, so fill in the canonical type field.
1165 QualType Canonical;
1166 if (!T->isCanonical()) {
1167 Canonical = getRValueReferenceType(getCanonicalType(T));
1168
1169 // Get the new insert position for the node we care about.
1170 RValueReferenceType *NewIP =
1171 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1172 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1173 }
1174
1175 RValueReferenceType *New = new (*this,8) RValueReferenceType(T, Canonical);
1176 Types.push_back(New);
1177 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001178 return QualType(New, 0);
1179}
1180
Sebastian Redlf30208a2009-01-24 21:16:55 +00001181/// getMemberPointerType - Return the uniqued reference to the type for a
1182/// member pointer to the specified type, in the specified class.
1183QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls)
1184{
1185 // Unique pointers, to guarantee there is only one pointer of a particular
1186 // structure.
1187 llvm::FoldingSetNodeID ID;
1188 MemberPointerType::Profile(ID, T, Cls);
1189
1190 void *InsertPos = 0;
1191 if (MemberPointerType *PT =
1192 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1193 return QualType(PT, 0);
1194
1195 // If the pointee or class type isn't canonical, this won't be a canonical
1196 // type either, so fill in the canonical type field.
1197 QualType Canonical;
1198 if (!T->isCanonical()) {
1199 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1200
1201 // Get the new insert position for the node we care about.
1202 MemberPointerType *NewIP =
1203 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1204 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1205 }
Steve Narofff83820b2009-01-27 22:08:43 +00001206 MemberPointerType *New = new (*this,8) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001207 Types.push_back(New);
1208 MemberPointerTypes.InsertNode(New, InsertPos);
1209 return QualType(New, 0);
1210}
1211
Steve Narofffb22d962007-08-30 01:06:46 +00001212/// getConstantArrayType - Return the unique reference to the type for an
1213/// array of the specified element type.
1214QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001215 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001216 ArrayType::ArraySizeModifier ASM,
1217 unsigned EltTypeQuals) {
Eli Friedman587cbdf2009-05-29 20:17:55 +00001218 assert((EltTy->isDependentType() || EltTy->isConstantSizeType()) &&
1219 "Constant array of VLAs is illegal!");
1220
Chris Lattner38aeec72009-05-13 04:12:56 +00001221 // Convert the array size into a canonical width matching the pointer size for
1222 // the target.
1223 llvm::APInt ArySize(ArySizeIn);
1224 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1225
Reid Spencer5f016e22007-07-11 17:01:13 +00001226 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001227 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001228
1229 void *InsertPos = 0;
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001230 if (ConstantArrayType *ATP =
1231 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001232 return QualType(ATP, 0);
1233
1234 // If the element type isn't canonical, this won't be a canonical type either,
1235 // so fill in the canonical type field.
1236 QualType Canonical;
1237 if (!EltTy->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001238 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroffc9406122007-08-30 18:10:14 +00001239 ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001240 // Get the new insert position for the node we care about.
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001241 ConstantArrayType *NewIP =
1242 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001243 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001244 }
1245
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001246 ConstantArrayType *New =
Steve Narofff83820b2009-01-27 22:08:43 +00001247 new(*this,8)ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001248 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001249 Types.push_back(New);
1250 return QualType(New, 0);
1251}
1252
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001253/// getConstantArrayWithExprType - Return a reference to the type for
1254/// an array of the specified element type.
1255QualType
1256ASTContext::getConstantArrayWithExprType(QualType EltTy,
1257 const llvm::APInt &ArySizeIn,
1258 Expr *ArySizeExpr,
1259 ArrayType::ArraySizeModifier ASM,
1260 unsigned EltTypeQuals,
1261 SourceRange Brackets) {
1262 // Convert the array size into a canonical width matching the pointer
1263 // size for the target.
1264 llvm::APInt ArySize(ArySizeIn);
1265 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1266
1267 // Compute the canonical ConstantArrayType.
1268 QualType Canonical = getConstantArrayType(getCanonicalType(EltTy),
1269 ArySize, ASM, EltTypeQuals);
1270 // Since we don't unique expressions, it isn't possible to unique VLA's
1271 // that have an expression provided for their size.
1272 ConstantArrayWithExprType *New =
1273 new(*this,8)ConstantArrayWithExprType(EltTy, Canonical,
1274 ArySize, ArySizeExpr,
1275 ASM, EltTypeQuals, Brackets);
1276 Types.push_back(New);
1277 return QualType(New, 0);
1278}
1279
1280/// getConstantArrayWithoutExprType - Return a reference to the type for
1281/// an array of the specified element type.
1282QualType
1283ASTContext::getConstantArrayWithoutExprType(QualType EltTy,
1284 const llvm::APInt &ArySizeIn,
1285 ArrayType::ArraySizeModifier ASM,
1286 unsigned EltTypeQuals) {
1287 // Convert the array size into a canonical width matching the pointer
1288 // size for the target.
1289 llvm::APInt ArySize(ArySizeIn);
1290 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1291
1292 // Compute the canonical ConstantArrayType.
1293 QualType Canonical = getConstantArrayType(getCanonicalType(EltTy),
1294 ArySize, ASM, EltTypeQuals);
1295 ConstantArrayWithoutExprType *New =
1296 new(*this,8)ConstantArrayWithoutExprType(EltTy, Canonical,
1297 ArySize, ASM, EltTypeQuals);
1298 Types.push_back(New);
1299 return QualType(New, 0);
1300}
1301
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001302/// getVariableArrayType - Returns a non-unique reference to the type for a
1303/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001304QualType ASTContext::getVariableArrayType(QualType EltTy,
1305 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001306 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001307 unsigned EltTypeQuals,
1308 SourceRange Brackets) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001309 // Since we don't unique expressions, it isn't possible to unique VLA's
1310 // that have an expression provided for their size.
1311
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001312 VariableArrayType *New =
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001313 new(*this,8)VariableArrayType(EltTy, QualType(),
1314 NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001315
1316 VariableArrayTypes.push_back(New);
1317 Types.push_back(New);
1318 return QualType(New, 0);
1319}
1320
Douglas Gregor898574e2008-12-05 23:32:09 +00001321/// getDependentSizedArrayType - Returns a non-unique reference to
1322/// the type for a dependently-sized array of the specified element
1323/// type. FIXME: We will need these to be uniqued, or at least
1324/// comparable, at some point.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001325QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1326 Expr *NumElts,
Douglas Gregor898574e2008-12-05 23:32:09 +00001327 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001328 unsigned EltTypeQuals,
1329 SourceRange Brackets) {
Douglas Gregor898574e2008-12-05 23:32:09 +00001330 assert((NumElts->isTypeDependent() || NumElts->isValueDependent()) &&
1331 "Size must be type- or value-dependent!");
1332
1333 // Since we don't unique expressions, it isn't possible to unique
1334 // dependently-sized array types.
1335
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001336 DependentSizedArrayType *New =
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001337 new (*this,8) DependentSizedArrayType(EltTy, QualType(),
1338 NumElts, ASM, EltTypeQuals,
1339 Brackets);
Douglas Gregor898574e2008-12-05 23:32:09 +00001340
1341 DependentSizedArrayTypes.push_back(New);
1342 Types.push_back(New);
1343 return QualType(New, 0);
1344}
1345
Eli Friedmanc5773c42008-02-15 18:16:39 +00001346QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1347 ArrayType::ArraySizeModifier ASM,
1348 unsigned EltTypeQuals) {
1349 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001350 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001351
1352 void *InsertPos = 0;
1353 if (IncompleteArrayType *ATP =
1354 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1355 return QualType(ATP, 0);
1356
1357 // If the element type isn't canonical, this won't be a canonical type
1358 // either, so fill in the canonical type field.
1359 QualType Canonical;
1360
1361 if (!EltTy->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001362 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001363 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001364
1365 // Get the new insert position for the node we care about.
1366 IncompleteArrayType *NewIP =
1367 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001368 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001369 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001370
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001371 IncompleteArrayType *New
1372 = new (*this,8) IncompleteArrayType(EltTy, Canonical,
1373 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001374
1375 IncompleteArrayTypes.InsertNode(New, InsertPos);
1376 Types.push_back(New);
1377 return QualType(New, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001378}
1379
Steve Naroff73322922007-07-18 18:00:27 +00001380/// getVectorType - Return the unique reference to a vector type of
1381/// the specified element type and size. VectorType must be a built-in type.
1382QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001383 BuiltinType *baseType;
1384
Chris Lattnerf52ab252008-04-06 22:59:24 +00001385 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff73322922007-07-18 18:00:27 +00001386 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Reid Spencer5f016e22007-07-11 17:01:13 +00001387
1388 // Check if we've already instantiated a vector of this type.
1389 llvm::FoldingSetNodeID ID;
Steve Naroff73322922007-07-18 18:00:27 +00001390 VectorType::Profile(ID, vecType, NumElts, Type::Vector);
Reid Spencer5f016e22007-07-11 17:01:13 +00001391 void *InsertPos = 0;
1392 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1393 return QualType(VTP, 0);
1394
1395 // If the element type isn't canonical, this won't be a canonical type either,
1396 // so fill in the canonical type field.
1397 QualType Canonical;
1398 if (!vecType->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001399 Canonical = getVectorType(getCanonicalType(vecType), NumElts);
Reid Spencer5f016e22007-07-11 17:01:13 +00001400
1401 // Get the new insert position for the node we care about.
1402 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001403 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001404 }
Steve Narofff83820b2009-01-27 22:08:43 +00001405 VectorType *New = new (*this,8) VectorType(vecType, NumElts, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001406 VectorTypes.InsertNode(New, InsertPos);
1407 Types.push_back(New);
1408 return QualType(New, 0);
1409}
1410
Nate Begeman213541a2008-04-18 23:10:10 +00001411/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001412/// the specified element type and size. VectorType must be a built-in type.
Nate Begeman213541a2008-04-18 23:10:10 +00001413QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff73322922007-07-18 18:00:27 +00001414 BuiltinType *baseType;
1415
Chris Lattnerf52ab252008-04-06 22:59:24 +00001416 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begeman213541a2008-04-18 23:10:10 +00001417 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Steve Naroff73322922007-07-18 18:00:27 +00001418
1419 // Check if we've already instantiated a vector of this type.
1420 llvm::FoldingSetNodeID ID;
Nate Begeman213541a2008-04-18 23:10:10 +00001421 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector);
Steve Naroff73322922007-07-18 18:00:27 +00001422 void *InsertPos = 0;
1423 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1424 return QualType(VTP, 0);
1425
1426 // If the element type isn't canonical, this won't be a canonical type either,
1427 // so fill in the canonical type field.
1428 QualType Canonical;
1429 if (!vecType->isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001430 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Steve Naroff73322922007-07-18 18:00:27 +00001431
1432 // Get the new insert position for the node we care about.
1433 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001434 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001435 }
Steve Narofff83820b2009-01-27 22:08:43 +00001436 ExtVectorType *New = new (*this,8) ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001437 VectorTypes.InsertNode(New, InsertPos);
1438 Types.push_back(New);
1439 return QualType(New, 0);
1440}
1441
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001442QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
1443 Expr *SizeExpr,
1444 SourceLocation AttrLoc) {
1445 DependentSizedExtVectorType *New =
1446 new (*this,8) DependentSizedExtVectorType(vecType, QualType(),
1447 SizeExpr, AttrLoc);
1448
1449 DependentSizedExtVectorTypes.push_back(New);
1450 Types.push_back(New);
1451 return QualType(New, 0);
1452}
1453
Douglas Gregor72564e72009-02-26 23:50:07 +00001454/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001455///
Douglas Gregor72564e72009-02-26 23:50:07 +00001456QualType ASTContext::getFunctionNoProtoType(QualType ResultTy) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001457 // Unique functions, to guarantee there is only one function of a particular
1458 // structure.
1459 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001460 FunctionNoProtoType::Profile(ID, ResultTy);
Reid Spencer5f016e22007-07-11 17:01:13 +00001461
1462 void *InsertPos = 0;
Douglas Gregor72564e72009-02-26 23:50:07 +00001463 if (FunctionNoProtoType *FT =
1464 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001465 return QualType(FT, 0);
1466
1467 QualType Canonical;
1468 if (!ResultTy->isCanonical()) {
Douglas Gregor72564e72009-02-26 23:50:07 +00001469 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy));
Reid Spencer5f016e22007-07-11 17:01:13 +00001470
1471 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001472 FunctionNoProtoType *NewIP =
1473 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001474 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001475 }
1476
Douglas Gregor72564e72009-02-26 23:50:07 +00001477 FunctionNoProtoType *New =new(*this,8)FunctionNoProtoType(ResultTy,Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001478 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001479 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001480 return QualType(New, 0);
1481}
1482
1483/// getFunctionType - Return a normal function type with a typed argument
1484/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner61710852008-10-05 17:34:18 +00001485QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001486 unsigned NumArgs, bool isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001487 unsigned TypeQuals, bool hasExceptionSpec,
1488 bool hasAnyExceptionSpec, unsigned NumExs,
1489 const QualType *ExArray) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001490 // Unique functions, to guarantee there is only one function of a particular
1491 // structure.
1492 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001493 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001494 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
1495 NumExs, ExArray);
Reid Spencer5f016e22007-07-11 17:01:13 +00001496
1497 void *InsertPos = 0;
Douglas Gregor72564e72009-02-26 23:50:07 +00001498 if (FunctionProtoType *FTP =
1499 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001500 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001501
1502 // Determine whether the type being created is already canonical or not.
Reid Spencer5f016e22007-07-11 17:01:13 +00001503 bool isCanonical = ResultTy->isCanonical();
Sebastian Redl465226e2009-05-27 22:11:52 +00001504 if (hasExceptionSpec)
1505 isCanonical = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001506 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
1507 if (!ArgArray[i]->isCanonical())
1508 isCanonical = false;
1509
1510 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001511 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001512 QualType Canonical;
1513 if (!isCanonical) {
1514 llvm::SmallVector<QualType, 16> CanonicalArgs;
1515 CanonicalArgs.reserve(NumArgs);
1516 for (unsigned i = 0; i != NumArgs; ++i)
Chris Lattnerf52ab252008-04-06 22:59:24 +00001517 CanonicalArgs.push_back(getCanonicalType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001518
Chris Lattnerf52ab252008-04-06 22:59:24 +00001519 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001520 CanonicalArgs.data(), NumArgs,
Sebastian Redlbfa2fcb2009-05-06 23:27:55 +00001521 isVariadic, TypeQuals);
Sebastian Redl465226e2009-05-27 22:11:52 +00001522
Reid Spencer5f016e22007-07-11 17:01:13 +00001523 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001524 FunctionProtoType *NewIP =
1525 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001526 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001527 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001528
Douglas Gregor72564e72009-02-26 23:50:07 +00001529 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001530 // for two variable size arrays (for parameter and exception types) at the
1531 // end of them.
Douglas Gregor72564e72009-02-26 23:50:07 +00001532 FunctionProtoType *FTP =
Sebastian Redl465226e2009-05-27 22:11:52 +00001533 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1534 NumArgs*sizeof(QualType) +
1535 NumExs*sizeof(QualType), 8);
Douglas Gregor72564e72009-02-26 23:50:07 +00001536 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001537 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
1538 ExArray, NumExs, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001539 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001540 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001541 return QualType(FTP, 0);
1542}
1543
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001544/// getTypeDeclType - Return the unique reference to the type for the
1545/// specified type declaration.
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001546QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001547 assert(Decl && "Passed null for Decl param");
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001548 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1549
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001550 if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001551 return getTypedefType(Typedef);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001552 else if (isa<TemplateTypeParmDecl>(Decl)) {
1553 assert(false && "Template type parameter types are always available.");
1554 } else if (ObjCInterfaceDecl *ObjCInterface = dyn_cast<ObjCInterfaceDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001555 return getObjCInterfaceType(ObjCInterface);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001556
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001557 if (RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001558 if (PrevDecl)
1559 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001560 else
1561 Decl->TypeForDecl = new (*this,8) RecordType(Record);
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001562 }
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001563 else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
1564 if (PrevDecl)
1565 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001566 else
1567 Decl->TypeForDecl = new (*this,8) EnumType(Enum);
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001568 }
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001569 else
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001570 assert(false && "TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001571
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001572 if (!PrevDecl) Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001573 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001574}
1575
Reid Spencer5f016e22007-07-11 17:01:13 +00001576/// getTypedefType - Return the unique reference to the type for the
1577/// specified typename decl.
1578QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
1579 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1580
Chris Lattnerf52ab252008-04-06 22:59:24 +00001581 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
Douglas Gregor72564e72009-02-26 23:50:07 +00001582 Decl->TypeForDecl = new(*this,8) TypedefType(Type::Typedef, Decl, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001583 Types.push_back(Decl->TypeForDecl);
1584 return QualType(Decl->TypeForDecl, 0);
1585}
1586
Douglas Gregorfab9d672009-02-05 23:33:38 +00001587/// \brief Retrieve the template type parameter type for a template
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001588/// parameter or parameter pack with the given depth, index, and (optionally)
1589/// name.
Douglas Gregorfab9d672009-02-05 23:33:38 +00001590QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001591 bool ParameterPack,
Douglas Gregorfab9d672009-02-05 23:33:38 +00001592 IdentifierInfo *Name) {
1593 llvm::FoldingSetNodeID ID;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001594 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001595 void *InsertPos = 0;
1596 TemplateTypeParmType *TypeParm
1597 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1598
1599 if (TypeParm)
1600 return QualType(TypeParm, 0);
1601
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001602 if (Name) {
1603 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
1604 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, ParameterPack,
1605 Name, Canon);
1606 } else
1607 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001608
1609 Types.push_back(TypeParm);
1610 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1611
1612 return QualType(TypeParm, 0);
1613}
1614
Douglas Gregor55f6b142009-02-09 18:46:07 +00001615QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00001616ASTContext::getTemplateSpecializationType(TemplateName Template,
1617 const TemplateArgument *Args,
1618 unsigned NumArgs,
1619 QualType Canon) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001620 if (!Canon.isNull())
1621 Canon = getCanonicalType(Canon);
Douglas Gregorfc705b82009-02-26 22:19:44 +00001622
Douglas Gregor55f6b142009-02-09 18:46:07 +00001623 llvm::FoldingSetNodeID ID;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001624 TemplateSpecializationType::Profile(ID, Template, Args, NumArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001625
Douglas Gregor55f6b142009-02-09 18:46:07 +00001626 void *InsertPos = 0;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001627 TemplateSpecializationType *Spec
1628 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001629
1630 if (Spec)
1631 return QualType(Spec, 0);
1632
Douglas Gregor7532dc62009-03-30 22:58:21 +00001633 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00001634 sizeof(TemplateArgument) * NumArgs),
1635 8);
Douglas Gregor7532dc62009-03-30 22:58:21 +00001636 Spec = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, Canon);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001637 Types.push_back(Spec);
Douglas Gregor7532dc62009-03-30 22:58:21 +00001638 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001639
1640 return QualType(Spec, 0);
1641}
1642
Douglas Gregore4e5b052009-03-19 00:18:19 +00001643QualType
Douglas Gregorab452ba2009-03-26 23:50:42 +00001644ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
Douglas Gregore4e5b052009-03-19 00:18:19 +00001645 QualType NamedType) {
1646 llvm::FoldingSetNodeID ID;
Douglas Gregorab452ba2009-03-26 23:50:42 +00001647 QualifiedNameType::Profile(ID, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001648
1649 void *InsertPos = 0;
1650 QualifiedNameType *T
1651 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
1652 if (T)
1653 return QualType(T, 0);
1654
Douglas Gregorab452ba2009-03-26 23:50:42 +00001655 T = new (*this) QualifiedNameType(NNS, NamedType,
1656 getCanonicalType(NamedType));
Douglas Gregore4e5b052009-03-19 00:18:19 +00001657 Types.push_back(T);
1658 QualifiedNameTypes.InsertNode(T, InsertPos);
1659 return QualType(T, 0);
1660}
1661
Douglas Gregord57959a2009-03-27 23:10:48 +00001662QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1663 const IdentifierInfo *Name,
1664 QualType Canon) {
1665 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1666
1667 if (Canon.isNull()) {
1668 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1669 if (CanonNNS != NNS)
1670 Canon = getTypenameType(CanonNNS, Name);
1671 }
1672
1673 llvm::FoldingSetNodeID ID;
1674 TypenameType::Profile(ID, NNS, Name);
1675
1676 void *InsertPos = 0;
1677 TypenameType *T
1678 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1679 if (T)
1680 return QualType(T, 0);
1681
1682 T = new (*this) TypenameType(NNS, Name, Canon);
1683 Types.push_back(T);
1684 TypenameTypes.InsertNode(T, InsertPos);
1685 return QualType(T, 0);
1686}
1687
Douglas Gregor17343172009-04-01 00:28:59 +00001688QualType
1689ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1690 const TemplateSpecializationType *TemplateId,
1691 QualType Canon) {
1692 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1693
1694 if (Canon.isNull()) {
1695 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1696 QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
1697 if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
1698 const TemplateSpecializationType *CanonTemplateId
1699 = CanonType->getAsTemplateSpecializationType();
1700 assert(CanonTemplateId &&
1701 "Canonical type must also be a template specialization type");
1702 Canon = getTypenameType(CanonNNS, CanonTemplateId);
1703 }
1704 }
1705
1706 llvm::FoldingSetNodeID ID;
1707 TypenameType::Profile(ID, NNS, TemplateId);
1708
1709 void *InsertPos = 0;
1710 TypenameType *T
1711 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1712 if (T)
1713 return QualType(T, 0);
1714
1715 T = new (*this) TypenameType(NNS, TemplateId, Canon);
1716 Types.push_back(T);
1717 TypenameTypes.InsertNode(T, InsertPos);
1718 return QualType(T, 0);
1719}
1720
Chris Lattner88cb27a2008-04-07 04:56:42 +00001721/// CmpProtocolNames - Comparison predicate for sorting protocols
1722/// alphabetically.
1723static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
1724 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001725 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00001726}
1727
1728static void SortAndUniqueProtocols(ObjCProtocolDecl **&Protocols,
1729 unsigned &NumProtocols) {
1730 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
1731
1732 // Sort protocols, keyed by name.
1733 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
1734
1735 // Remove duplicates.
1736 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
1737 NumProtocols = ProtocolsEnd-Protocols;
1738}
1739
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001740/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
1741/// the given interface decl and the conforming protocol list.
Steve Naroff14108da2009-07-10 23:34:53 +00001742QualType ASTContext::getObjCObjectPointerType(QualType InterfaceT,
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001743 ObjCProtocolDecl **Protocols,
1744 unsigned NumProtocols) {
Steve Naroff14108da2009-07-10 23:34:53 +00001745 if (InterfaceT.isNull())
Steve Naroffde2e22d2009-07-15 18:40:39 +00001746 InterfaceT = ObjCBuiltinIdTy;
Steve Naroff14108da2009-07-10 23:34:53 +00001747
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001748 // Sort the protocol list alphabetically to canonicalize it.
1749 if (NumProtocols)
1750 SortAndUniqueProtocols(Protocols, NumProtocols);
1751
1752 llvm::FoldingSetNodeID ID;
Steve Naroff14108da2009-07-10 23:34:53 +00001753 ObjCObjectPointerType::Profile(ID, InterfaceT, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001754
1755 void *InsertPos = 0;
1756 if (ObjCObjectPointerType *QT =
1757 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1758 return QualType(QT, 0);
1759
1760 // No Match;
1761 ObjCObjectPointerType *QType =
Steve Naroff14108da2009-07-10 23:34:53 +00001762 new (*this,8) ObjCObjectPointerType(InterfaceT, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001763
1764 Types.push_back(QType);
1765 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
1766 return QualType(QType, 0);
1767}
Chris Lattner88cb27a2008-04-07 04:56:42 +00001768
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001769/// getObjCInterfaceType - Return the unique reference to the type for the
1770/// specified ObjC interface decl. The list of protocols is optional.
1771QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001772 ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001773 if (NumProtocols)
1774 // Sort the protocol list alphabetically to canonicalize it.
1775 SortAndUniqueProtocols(Protocols, NumProtocols);
Chris Lattner88cb27a2008-04-07 04:56:42 +00001776
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001777 llvm::FoldingSetNodeID ID;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001778 ObjCInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001779
1780 void *InsertPos = 0;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001781 if (ObjCInterfaceType *QT =
1782 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001783 return QualType(QT, 0);
1784
1785 // No Match;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001786 ObjCInterfaceType *QType =
1787 new (*this,8) ObjCInterfaceType(const_cast<ObjCInterfaceDecl*>(Decl),
1788 Protocols, NumProtocols);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001789 Types.push_back(QType);
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001790 ObjCInterfaceTypes.InsertNode(QType, InsertPos);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001791 return QualType(QType, 0);
1792}
1793
Douglas Gregor72564e72009-02-26 23:50:07 +00001794/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
1795/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00001796/// multiple declarations that refer to "typeof(x)" all contain different
1797/// DeclRefExpr's. This doesn't effect the type checker, since it operates
1798/// on canonical type's (which are always unique).
Douglas Gregor72564e72009-02-26 23:50:07 +00001799QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00001800 TypeOfExprType *toe;
1801 if (tofExpr->isTypeDependent())
1802 toe = new (*this, 8) TypeOfExprType(tofExpr);
1803 else {
1804 QualType Canonical = getCanonicalType(tofExpr->getType());
1805 toe = new (*this,8) TypeOfExprType(tofExpr, Canonical);
1806 }
Steve Naroff9752f252007-08-01 18:02:17 +00001807 Types.push_back(toe);
1808 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00001809}
1810
Steve Naroff9752f252007-08-01 18:02:17 +00001811/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
1812/// TypeOfType AST's. The only motivation to unique these nodes would be
1813/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
1814/// an issue. This doesn't effect the type checker, since it operates
1815/// on canonical type's (which are always unique).
Steve Naroffd1861fd2007-07-31 12:34:36 +00001816QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001817 QualType Canonical = getCanonicalType(tofType);
Steve Narofff83820b2009-01-27 22:08:43 +00001818 TypeOfType *tot = new (*this,8) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00001819 Types.push_back(tot);
1820 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00001821}
1822
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00001823/// getDecltypeForExpr - Given an expr, will return the decltype for that
1824/// expression, according to the rules in C++0x [dcl.type.simple]p4
1825static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00001826 if (e->isTypeDependent())
1827 return Context.DependentTy;
1828
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00001829 // If e is an id expression or a class member access, decltype(e) is defined
1830 // as the type of the entity named by e.
1831 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
1832 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
1833 return VD->getType();
1834 }
1835 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
1836 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
1837 return FD->getType();
1838 }
1839 // If e is a function call or an invocation of an overloaded operator,
1840 // (parentheses around e are ignored), decltype(e) is defined as the
1841 // return type of that function.
1842 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
1843 return CE->getCallReturnType();
1844
1845 QualType T = e->getType();
1846
1847 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
1848 // defined as T&, otherwise decltype(e) is defined as T.
1849 if (e->isLvalue(Context) == Expr::LV_Valid)
1850 T = Context.getLValueReferenceType(T);
1851
1852 return T;
1853}
1854
Anders Carlsson395b4752009-06-24 19:06:50 +00001855/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
1856/// DecltypeType AST's. The only motivation to unique these nodes would be
1857/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
1858/// an issue. This doesn't effect the type checker, since it operates
1859/// on canonical type's (which are always unique).
1860QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00001861 DecltypeType *dt;
1862 if (e->isTypeDependent()) // FIXME: canonicalize the expression
Anders Carlsson563a03b2009-07-10 19:20:26 +00001863 dt = new (*this, 8) DecltypeType(e, DependentTy);
Douglas Gregordd0257c2009-07-08 00:03:05 +00001864 else {
1865 QualType T = getDecltypeForExpr(e, *this);
Anders Carlsson563a03b2009-07-10 19:20:26 +00001866 dt = new (*this, 8) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00001867 }
Anders Carlsson395b4752009-06-24 19:06:50 +00001868 Types.push_back(dt);
1869 return QualType(dt, 0);
1870}
1871
Reid Spencer5f016e22007-07-11 17:01:13 +00001872/// getTagDeclType - Return the unique reference to the type for the
1873/// specified TagDecl (struct/union/class/enum) decl.
1874QualType ASTContext::getTagDeclType(TagDecl *Decl) {
Ted Kremenekd778f882007-11-26 21:16:01 +00001875 assert (Decl);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001876 return getTypeDeclType(Decl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001877}
1878
1879/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
1880/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
1881/// needs to agree with the definition in <stddef.h>.
1882QualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00001883 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00001884}
1885
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00001886/// getSignedWCharType - Return the type of "signed wchar_t".
1887/// Used when in C++, as a GCC extension.
1888QualType ASTContext::getSignedWCharType() const {
1889 // FIXME: derive from "Target" ?
1890 return WCharTy;
1891}
1892
1893/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
1894/// Used when in C++, as a GCC extension.
1895QualType ASTContext::getUnsignedWCharType() const {
1896 // FIXME: derive from "Target" ?
1897 return UnsignedIntTy;
1898}
1899
Chris Lattner8b9023b2007-07-13 03:05:23 +00001900/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
1901/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
1902QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00001903 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00001904}
1905
Chris Lattnere6327742008-04-02 05:18:44 +00001906//===----------------------------------------------------------------------===//
1907// Type Operators
1908//===----------------------------------------------------------------------===//
1909
Chris Lattner77c96472008-04-06 22:41:35 +00001910/// getCanonicalType - Return the canonical (structural) type corresponding to
1911/// the specified potentially non-canonical type. The non-canonical version
1912/// of a type may have many "decorated" versions of types. Decorators can
1913/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
1914/// to be free of any of these, allowing two canonical types to be compared
1915/// for exact equality with a simple pointer comparison.
1916QualType ASTContext::getCanonicalType(QualType T) {
1917 QualType CanType = T.getTypePtr()->getCanonicalTypeInternal();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001918
1919 // If the result has type qualifiers, make sure to canonicalize them as well.
1920 unsigned TypeQuals = T.getCVRQualifiers() | CanType.getCVRQualifiers();
1921 if (TypeQuals == 0) return CanType;
1922
1923 // If the type qualifiers are on an array type, get the canonical type of the
1924 // array with the qualifiers applied to the element type.
1925 ArrayType *AT = dyn_cast<ArrayType>(CanType);
1926 if (!AT)
1927 return CanType.getQualifiedType(TypeQuals);
1928
1929 // Get the canonical version of the element with the extra qualifiers on it.
1930 // This can recursively sink qualifiers through multiple levels of arrays.
1931 QualType NewEltTy=AT->getElementType().getWithAdditionalQualifiers(TypeQuals);
1932 NewEltTy = getCanonicalType(NewEltTy);
1933
1934 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
1935 return getConstantArrayType(NewEltTy, CAT->getSize(),CAT->getSizeModifier(),
1936 CAT->getIndexTypeQualifier());
1937 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
1938 return getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
1939 IAT->getIndexTypeQualifier());
1940
Douglas Gregor898574e2008-12-05 23:32:09 +00001941 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001942 return getDependentSizedArrayType(NewEltTy,
1943 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00001944 DSAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001945 DSAT->getIndexTypeQualifier(),
1946 DSAT->getBracketsRange());
Douglas Gregor898574e2008-12-05 23:32:09 +00001947
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001948 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001949 return getVariableArrayType(NewEltTy,
1950 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001951 VAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001952 VAT->getIndexTypeQualifier(),
1953 VAT->getBracketsRange());
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001954}
1955
Douglas Gregor25a3ef72009-05-07 06:41:52 +00001956TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
1957 // If this template name refers to a template, the canonical
1958 // template name merely stores the template itself.
1959 if (TemplateDecl *Template = Name.getAsTemplateDecl())
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001960 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor25a3ef72009-05-07 06:41:52 +00001961
1962 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
1963 assert(DTN && "Non-dependent template names must refer to template decls.");
1964 return DTN->CanonicalTemplateName;
1965}
1966
Douglas Gregord57959a2009-03-27 23:10:48 +00001967NestedNameSpecifier *
1968ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
1969 if (!NNS)
1970 return 0;
1971
1972 switch (NNS->getKind()) {
1973 case NestedNameSpecifier::Identifier:
1974 // Canonicalize the prefix but keep the identifier the same.
1975 return NestedNameSpecifier::Create(*this,
1976 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
1977 NNS->getAsIdentifier());
1978
1979 case NestedNameSpecifier::Namespace:
1980 // A namespace is canonical; build a nested-name-specifier with
1981 // this namespace and no prefix.
1982 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
1983
1984 case NestedNameSpecifier::TypeSpec:
1985 case NestedNameSpecifier::TypeSpecWithTemplate: {
1986 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
1987 NestedNameSpecifier *Prefix = 0;
1988
1989 // FIXME: This isn't the right check!
1990 if (T->isDependentType())
1991 Prefix = getCanonicalNestedNameSpecifier(NNS->getPrefix());
1992
1993 return NestedNameSpecifier::Create(*this, Prefix,
1994 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
1995 T.getTypePtr());
1996 }
1997
1998 case NestedNameSpecifier::Global:
1999 // The global specifier is canonical and unique.
2000 return NNS;
2001 }
2002
2003 // Required to silence a GCC warning
2004 return 0;
2005}
2006
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002007
2008const ArrayType *ASTContext::getAsArrayType(QualType T) {
2009 // Handle the non-qualified case efficiently.
2010 if (T.getCVRQualifiers() == 0) {
2011 // Handle the common positive case fast.
2012 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2013 return AT;
2014 }
2015
2016 // Handle the common negative case fast, ignoring CVR qualifiers.
2017 QualType CType = T->getCanonicalTypeInternal();
2018
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002019 // Make sure to look through type qualifiers (like ExtQuals) for the negative
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002020 // test.
2021 if (!isa<ArrayType>(CType) &&
2022 !isa<ArrayType>(CType.getUnqualifiedType()))
2023 return 0;
2024
2025 // Apply any CVR qualifiers from the array type to the element type. This
2026 // implements C99 6.7.3p8: "If the specification of an array type includes
2027 // any type qualifiers, the element type is so qualified, not the array type."
2028
2029 // If we get here, we either have type qualifiers on the type, or we have
2030 // sugar such as a typedef in the way. If we have type qualifiers on the type
2031 // we must propagate them down into the elemeng type.
2032 unsigned CVRQuals = T.getCVRQualifiers();
2033 unsigned AddrSpace = 0;
2034 Type *Ty = T.getTypePtr();
2035
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002036 // Rip through ExtQualType's and typedefs to get to a concrete type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002037 while (1) {
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002038 if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(Ty)) {
2039 AddrSpace = EXTQT->getAddressSpace();
2040 Ty = EXTQT->getBaseType();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002041 } else {
2042 T = Ty->getDesugaredType();
2043 if (T.getTypePtr() == Ty && T.getCVRQualifiers() == 0)
2044 break;
2045 CVRQuals |= T.getCVRQualifiers();
2046 Ty = T.getTypePtr();
2047 }
2048 }
2049
2050 // If we have a simple case, just return now.
2051 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
2052 if (ATy == 0 || (AddrSpace == 0 && CVRQuals == 0))
2053 return ATy;
2054
2055 // Otherwise, we have an array and we have qualifiers on it. Push the
2056 // qualifiers into the array element type and return a new array type.
2057 // Get the canonical version of the element with the extra qualifiers on it.
2058 // This can recursively sink qualifiers through multiple levels of arrays.
2059 QualType NewEltTy = ATy->getElementType();
2060 if (AddrSpace)
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002061 NewEltTy = getAddrSpaceQualType(NewEltTy, AddrSpace);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002062 NewEltTy = NewEltTy.getWithAdditionalQualifiers(CVRQuals);
2063
2064 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2065 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2066 CAT->getSizeModifier(),
2067 CAT->getIndexTypeQualifier()));
2068 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2069 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2070 IAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002071 IAT->getIndexTypeQualifier()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002072
Douglas Gregor898574e2008-12-05 23:32:09 +00002073 if (const DependentSizedArrayType *DSAT
2074 = dyn_cast<DependentSizedArrayType>(ATy))
2075 return cast<ArrayType>(
2076 getDependentSizedArrayType(NewEltTy,
2077 DSAT->getSizeExpr(),
2078 DSAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002079 DSAT->getIndexTypeQualifier(),
2080 DSAT->getBracketsRange()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002081
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002082 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002083 return cast<ArrayType>(getVariableArrayType(NewEltTy,
2084 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002085 VAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002086 VAT->getIndexTypeQualifier(),
2087 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00002088}
2089
2090
Chris Lattnere6327742008-04-02 05:18:44 +00002091/// getArrayDecayedType - Return the properly qualified result of decaying the
2092/// specified array type to a pointer. This operation is non-trivial when
2093/// handling typedefs etc. The canonical type of "T" must be an array type,
2094/// this returns a pointer to a properly qualified element of the array.
2095///
2096/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2097QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002098 // Get the element type with 'getAsArrayType' so that we don't lose any
2099 // typedefs in the element type of the array. This also handles propagation
2100 // of type qualifiers from the array type into the element type if present
2101 // (C99 6.7.3p8).
2102 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2103 assert(PrettyArrayType && "Not an array type!");
Chris Lattnere6327742008-04-02 05:18:44 +00002104
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002105 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00002106
2107 // int x[restrict 4] -> int *restrict
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002108 return PtrTy.getQualifiedType(PrettyArrayType->getIndexTypeQualifier());
Chris Lattnere6327742008-04-02 05:18:44 +00002109}
2110
Daniel Dunbard786f6a2009-01-05 22:14:37 +00002111QualType ASTContext::getBaseElementType(const VariableArrayType *VAT) {
Anders Carlsson6183a992008-12-21 03:44:36 +00002112 QualType ElemTy = VAT->getElementType();
2113
2114 if (const VariableArrayType *VAT = getAsVariableArrayType(ElemTy))
2115 return getBaseElementType(VAT);
2116
2117 return ElemTy;
2118}
2119
Reid Spencer5f016e22007-07-11 17:01:13 +00002120/// getFloatingRank - Return a relative rank for floating point types.
2121/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00002122static FloatingRank getFloatingRank(QualType T) {
Christopher Lambebb97e92008-02-04 02:31:56 +00002123 if (const ComplexType *CT = T->getAsComplexType())
Reid Spencer5f016e22007-07-11 17:01:13 +00002124 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00002125
Daniel Dunbard786f6a2009-01-05 22:14:37 +00002126 assert(T->getAsBuiltinType() && "getFloatingRank(): not a floating type");
Christopher Lambebb97e92008-02-04 02:31:56 +00002127 switch (T->getAsBuiltinType()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00002128 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002129 case BuiltinType::Float: return FloatRank;
2130 case BuiltinType::Double: return DoubleRank;
2131 case BuiltinType::LongDouble: return LongDoubleRank;
2132 }
2133}
2134
Steve Naroff716c7302007-08-27 01:41:48 +00002135/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2136/// point or a complex type (based on typeDomain/typeSize).
2137/// 'typeDomain' is a real floating point or complex type.
2138/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00002139QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2140 QualType Domain) const {
2141 FloatingRank EltRank = getFloatingRank(Size);
2142 if (Domain->isComplexType()) {
2143 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00002144 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00002145 case FloatRank: return FloatComplexTy;
2146 case DoubleRank: return DoubleComplexTy;
2147 case LongDoubleRank: return LongDoubleComplexTy;
2148 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002149 }
Chris Lattner1361b112008-04-06 23:58:54 +00002150
2151 assert(Domain->isRealFloatingType() && "Unknown domain!");
2152 switch (EltRank) {
2153 default: assert(0 && "getFloatingRank(): illegal value for rank");
2154 case FloatRank: return FloatTy;
2155 case DoubleRank: return DoubleTy;
2156 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00002157 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002158}
2159
Chris Lattner7cfeb082008-04-06 23:55:33 +00002160/// getFloatingTypeOrder - Compare the rank of the two specified floating
2161/// point types, ignoring the domain of the type (i.e. 'double' ==
2162/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
2163/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00002164int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2165 FloatingRank LHSR = getFloatingRank(LHS);
2166 FloatingRank RHSR = getFloatingRank(RHS);
2167
2168 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002169 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00002170 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002171 return 1;
2172 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002173}
2174
Chris Lattnerf52ab252008-04-06 22:59:24 +00002175/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2176/// routine will assert if passed a built-in type that isn't an integer or enum,
2177/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00002178unsigned ASTContext::getIntegerRank(Type *T) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002179 assert(T->isCanonical() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00002180 if (EnumType* ET = dyn_cast<EnumType>(T))
2181 T = ET->getDecl()->getIntegerType().getTypePtr();
2182
Eli Friedmana3426752009-07-05 23:44:27 +00002183 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2184 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2185
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002186 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2187 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2188
2189 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2190 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2191
Eli Friedmanf98aba32009-02-13 02:31:07 +00002192 // There are two things which impact the integer rank: the width, and
2193 // the ordering of builtins. The builtin ordering is encoded in the
2194 // bottom three bits; the width is encoded in the bits above that.
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002195 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T))
Eli Friedmanf98aba32009-02-13 02:31:07 +00002196 return FWIT->getWidth() << 3;
Eli Friedmanf98aba32009-02-13 02:31:07 +00002197
Chris Lattnerf52ab252008-04-06 22:59:24 +00002198 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00002199 default: assert(0 && "getIntegerRank(): not a built-in integer");
2200 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002201 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002202 case BuiltinType::Char_S:
2203 case BuiltinType::Char_U:
2204 case BuiltinType::SChar:
2205 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002206 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002207 case BuiltinType::Short:
2208 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002209 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002210 case BuiltinType::Int:
2211 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002212 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002213 case BuiltinType::Long:
2214 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002215 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002216 case BuiltinType::LongLong:
2217 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002218 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00002219 case BuiltinType::Int128:
2220 case BuiltinType::UInt128:
2221 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00002222 }
2223}
2224
Chris Lattner7cfeb082008-04-06 23:55:33 +00002225/// getIntegerTypeOrder - Returns the highest ranked integer type:
2226/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
2227/// LHS < RHS, return -1.
2228int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002229 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2230 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00002231 if (LHSC == RHSC) return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00002232
Chris Lattnerf52ab252008-04-06 22:59:24 +00002233 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2234 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002235
Chris Lattner7cfeb082008-04-06 23:55:33 +00002236 unsigned LHSRank = getIntegerRank(LHSC);
2237 unsigned RHSRank = getIntegerRank(RHSC);
Reid Spencer5f016e22007-07-11 17:01:13 +00002238
Chris Lattner7cfeb082008-04-06 23:55:33 +00002239 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2240 if (LHSRank == RHSRank) return 0;
2241 return LHSRank > RHSRank ? 1 : -1;
2242 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002243
Chris Lattner7cfeb082008-04-06 23:55:33 +00002244 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2245 if (LHSUnsigned) {
2246 // If the unsigned [LHS] type is larger, return it.
2247 if (LHSRank >= RHSRank)
2248 return 1;
2249
2250 // If the signed type can represent all values of the unsigned type, it
2251 // wins. Because we are dealing with 2's complement and types that are
2252 // powers of two larger than each other, this is always safe.
2253 return -1;
2254 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00002255
Chris Lattner7cfeb082008-04-06 23:55:33 +00002256 // If the unsigned [RHS] type is larger, return it.
2257 if (RHSRank >= LHSRank)
2258 return -1;
2259
2260 // If the signed type can represent all values of the unsigned type, it
2261 // wins. Because we are dealing with 2's complement and types that are
2262 // powers of two larger than each other, this is always safe.
2263 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002264}
Anders Carlsson71993dd2007-08-17 05:31:46 +00002265
2266// getCFConstantStringType - Return the type used for constant CFStrings.
2267QualType ASTContext::getCFConstantStringType() {
2268 if (!CFConstantStringTypeDecl) {
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002269 CFConstantStringTypeDecl =
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002270 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002271 &Idents.get("NSConstantString"));
Anders Carlssonf06273f2007-11-19 00:25:30 +00002272 QualType FieldTypes[4];
Anders Carlsson71993dd2007-08-17 05:31:46 +00002273
2274 // const int *isa;
2275 FieldTypes[0] = getPointerType(IntTy.getQualifiedType(QualType::Const));
Anders Carlssonf06273f2007-11-19 00:25:30 +00002276 // int flags;
2277 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00002278 // const char *str;
Anders Carlssonf06273f2007-11-19 00:25:30 +00002279 FieldTypes[2] = getPointerType(CharTy.getQualifiedType(QualType::Const));
Anders Carlsson71993dd2007-08-17 05:31:46 +00002280 // long length;
Anders Carlssonf06273f2007-11-19 00:25:30 +00002281 FieldTypes[3] = LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002282
Anders Carlsson71993dd2007-08-17 05:31:46 +00002283 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002284 for (unsigned i = 0; i < 4; ++i) {
2285 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
2286 SourceLocation(), 0,
2287 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002288 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002289 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002290 }
2291
2292 CFConstantStringTypeDecl->completeDefinition(*this);
Anders Carlsson71993dd2007-08-17 05:31:46 +00002293 }
2294
2295 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00002296}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002297
Douglas Gregor319ac892009-04-23 22:29:11 +00002298void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek35366a62009-07-17 17:50:17 +00002299 const RecordType *Rec = T->getAsRecordType();
Douglas Gregor319ac892009-04-23 22:29:11 +00002300 assert(Rec && "Invalid CFConstantStringType");
2301 CFConstantStringTypeDecl = Rec->getDecl();
2302}
2303
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002304QualType ASTContext::getObjCFastEnumerationStateType()
2305{
2306 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00002307 ObjCFastEnumerationStateTypeDecl =
2308 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2309 &Idents.get("__objcFastEnumerationState"));
2310
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002311 QualType FieldTypes[] = {
2312 UnsignedLongTy,
Steve Naroffde2e22d2009-07-15 18:40:39 +00002313 getPointerType(ObjCIdTypedefType),
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002314 getPointerType(UnsignedLongTy),
2315 getConstantArrayType(UnsignedLongTy,
2316 llvm::APInt(32, 5), ArrayType::Normal, 0)
2317 };
2318
Douglas Gregor44b43212008-12-11 16:49:14 +00002319 for (size_t i = 0; i < 4; ++i) {
2320 FieldDecl *Field = FieldDecl::Create(*this,
2321 ObjCFastEnumerationStateTypeDecl,
2322 SourceLocation(), 0,
2323 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002324 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002325 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002326 }
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002327
Douglas Gregor44b43212008-12-11 16:49:14 +00002328 ObjCFastEnumerationStateTypeDecl->completeDefinition(*this);
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002329 }
2330
2331 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2332}
2333
Douglas Gregor319ac892009-04-23 22:29:11 +00002334void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenek35366a62009-07-17 17:50:17 +00002335 const RecordType *Rec = T->getAsRecordType();
Douglas Gregor319ac892009-04-23 22:29:11 +00002336 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
2337 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
2338}
2339
Anders Carlssone8c49532007-10-29 06:33:42 +00002340// This returns true if a type has been typedefed to BOOL:
2341// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00002342static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00002343 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00002344 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
2345 return II->isStr("BOOL");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002346
2347 return false;
2348}
2349
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002350/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002351/// purpose.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002352int ASTContext::getObjCEncodingTypeSize(QualType type) {
Chris Lattner98be4942008-03-05 18:54:05 +00002353 uint64_t sz = getTypeSize(type);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002354
2355 // Make all integer and enum types at least as large as an int
2356 if (sz > 0 && type->isIntegralType())
Chris Lattner98be4942008-03-05 18:54:05 +00002357 sz = std::max(sz, getTypeSize(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002358 // Treat arrays as pointers, since that's how they're passed in.
2359 else if (type->isArrayType())
Chris Lattner98be4942008-03-05 18:54:05 +00002360 sz = getTypeSize(VoidPtrTy);
2361 return sz / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002362}
2363
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002364/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002365/// declaration.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002366void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00002367 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002368 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002369 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002370 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002371 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002372 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002373 // Compute size of all parameters.
2374 // Start with computing size of a pointer in number of bytes.
2375 // FIXME: There might(should) be a better way of doing this computation!
2376 SourceLocation Loc;
Chris Lattner98be4942008-03-05 18:54:05 +00002377 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002378 // The first two arguments (self and _cmd) are pointers; account for
2379 // their size.
2380 int ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00002381 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2382 E = Decl->param_end(); PI != E; ++PI) {
2383 QualType PType = (*PI)->getType();
2384 int sz = getObjCEncodingTypeSize(PType);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002385 assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002386 ParmOffset += sz;
2387 }
2388 S += llvm::utostr(ParmOffset);
2389 S += "@0:";
2390 S += llvm::utostr(PtrSize);
2391
2392 // Argument types.
2393 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00002394 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2395 E = Decl->param_end(); PI != E; ++PI) {
2396 ParmVarDecl *PVDecl = *PI;
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00002397 QualType PType = PVDecl->getOriginalType();
2398 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00002399 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
2400 // Use array's original type only if it has known number of
2401 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00002402 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00002403 PType = PVDecl->getType();
2404 } else if (PType->isFunctionType())
2405 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002406 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002407 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00002408 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002409 getObjCEncodingForType(PType, S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002410 S += llvm::utostr(ParmOffset);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002411 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002412 }
2413}
2414
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002415/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00002416/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002417/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
2418/// NULL when getting encodings for protocol properties.
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00002419/// Property attributes are stored as a comma-delimited C string. The simple
2420/// attributes readonly and bycopy are encoded as single characters. The
2421/// parametrized attributes, getter=name, setter=name, and ivar=name, are
2422/// encoded as single characters, followed by an identifier. Property types
2423/// are also encoded as a parametrized attribute. The characters used to encode
2424/// these attributes are defined by the following enumeration:
2425/// @code
2426/// enum PropertyAttributes {
2427/// kPropertyReadOnly = 'R', // property is read-only.
2428/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
2429/// kPropertyByref = '&', // property is a reference to the value last assigned
2430/// kPropertyDynamic = 'D', // property is dynamic
2431/// kPropertyGetter = 'G', // followed by getter selector name
2432/// kPropertySetter = 'S', // followed by setter selector name
2433/// kPropertyInstanceVariable = 'V' // followed by instance variable name
2434/// kPropertyType = 't' // followed by old-style type encoding.
2435/// kPropertyWeak = 'W' // 'weak' property
2436/// kPropertyStrong = 'P' // property GC'able
2437/// kPropertyNonAtomic = 'N' // property non-atomic
2438/// };
2439/// @endcode
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002440void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
2441 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00002442 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002443 // Collect information from the property implementation decl(s).
2444 bool Dynamic = false;
2445 ObjCPropertyImplDecl *SynthesizePID = 0;
2446
2447 // FIXME: Duplicated code due to poor abstraction.
2448 if (Container) {
2449 if (const ObjCCategoryImplDecl *CID =
2450 dyn_cast<ObjCCategoryImplDecl>(Container)) {
2451 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002452 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00002453 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002454 ObjCPropertyImplDecl *PID = *i;
2455 if (PID->getPropertyDecl() == PD) {
2456 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2457 Dynamic = true;
2458 } else {
2459 SynthesizePID = PID;
2460 }
2461 }
2462 }
2463 } else {
Chris Lattner61710852008-10-05 17:34:18 +00002464 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002465 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002466 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00002467 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002468 ObjCPropertyImplDecl *PID = *i;
2469 if (PID->getPropertyDecl() == PD) {
2470 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2471 Dynamic = true;
2472 } else {
2473 SynthesizePID = PID;
2474 }
2475 }
2476 }
2477 }
2478 }
2479
2480 // FIXME: This is not very efficient.
2481 S = "T";
2482
2483 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002484 // GCC has some special rules regarding encoding of properties which
2485 // closely resembles encoding of ivars.
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002486 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002487 true /* outermost type */,
2488 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002489
2490 if (PD->isReadOnly()) {
2491 S += ",R";
2492 } else {
2493 switch (PD->getSetterKind()) {
2494 case ObjCPropertyDecl::Assign: break;
2495 case ObjCPropertyDecl::Copy: S += ",C"; break;
2496 case ObjCPropertyDecl::Retain: S += ",&"; break;
2497 }
2498 }
2499
2500 // It really isn't clear at all what this means, since properties
2501 // are "dynamic by default".
2502 if (Dynamic)
2503 S += ",D";
2504
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002505 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
2506 S += ",N";
2507
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002508 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
2509 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002510 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002511 }
2512
2513 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
2514 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002515 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002516 }
2517
2518 if (SynthesizePID) {
2519 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
2520 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00002521 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002522 }
2523
2524 // FIXME: OBJCGC: weak & strong
2525}
2526
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002527/// getLegacyIntegralTypeEncoding -
2528/// Another legacy compatibility encoding: 32-bit longs are encoded as
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002529/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002530/// 'i' or 'I' instead if encoding a struct field, or a pointer!
2531///
2532void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
2533 if (dyn_cast<TypedefType>(PointeeTy.getTypePtr())) {
2534 if (const BuiltinType *BT = PointeeTy->getAsBuiltinType()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002535 if (BT->getKind() == BuiltinType::ULong &&
2536 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002537 PointeeTy = UnsignedIntTy;
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002538 else
2539 if (BT->getKind() == BuiltinType::Long &&
2540 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002541 PointeeTy = IntTy;
2542 }
2543 }
2544}
2545
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002546void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002547 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002548 // We follow the behavior of gcc, expanding structures which are
2549 // directly pointed to, and expanding embedded structures. Note that
2550 // these rules are sufficient to prevent recursive encoding of the
2551 // same type.
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00002552 getObjCEncodingForTypeImpl(T, S, true, true, Field,
2553 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002554}
2555
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002556static void EncodeBitField(const ASTContext *Context, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002557 const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002558 const Expr *E = FD->getBitWidth();
2559 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
2560 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Eli Friedman9a901bb2009-04-26 19:19:15 +00002561 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002562 S += 'b';
2563 S += llvm::utostr(N);
2564}
2565
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002566void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
2567 bool ExpandPointedToStructures,
2568 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002569 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002570 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002571 bool EncodingProperty) {
Anders Carlssone8c49532007-10-29 06:33:42 +00002572 if (const BuiltinType *BT = T->getAsBuiltinType()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002573 if (FD && FD->isBitField())
2574 return EncodeBitField(this, S, FD);
2575 char encoding;
2576 switch (BT->getKind()) {
2577 default: assert(0 && "Unhandled builtin type kind");
2578 case BuiltinType::Void: encoding = 'v'; break;
2579 case BuiltinType::Bool: encoding = 'B'; break;
2580 case BuiltinType::Char_U:
2581 case BuiltinType::UChar: encoding = 'C'; break;
2582 case BuiltinType::UShort: encoding = 'S'; break;
2583 case BuiltinType::UInt: encoding = 'I'; break;
2584 case BuiltinType::ULong:
Fariborz Jahanian72696e12009-02-11 22:31:45 +00002585 encoding =
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002586 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
Fariborz Jahanian72696e12009-02-11 22:31:45 +00002587 break;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002588 case BuiltinType::UInt128: encoding = 'T'; break;
2589 case BuiltinType::ULongLong: encoding = 'Q'; break;
2590 case BuiltinType::Char_S:
2591 case BuiltinType::SChar: encoding = 'c'; break;
2592 case BuiltinType::Short: encoding = 's'; break;
2593 case BuiltinType::Int: encoding = 'i'; break;
2594 case BuiltinType::Long:
2595 encoding =
2596 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
2597 break;
2598 case BuiltinType::LongLong: encoding = 'q'; break;
2599 case BuiltinType::Int128: encoding = 't'; break;
2600 case BuiltinType::Float: encoding = 'f'; break;
2601 case BuiltinType::Double: encoding = 'd'; break;
2602 case BuiltinType::LongDouble: encoding = 'd'; break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002603 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002604
2605 S += encoding;
2606 return;
2607 }
2608
2609 if (const ComplexType *CT = T->getAsComplexType()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00002610 S += 'j';
2611 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
2612 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002613 return;
2614 }
2615
Ted Kremenek35366a62009-07-17 17:50:17 +00002616 if (const PointerType *PT = T->getAsPointerType()) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002617 QualType PointeeTy = PT->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002618 bool isReadOnly = false;
2619 // For historical/compatibility reasons, the read-only qualifier of the
2620 // pointee gets emitted _before_ the '^'. The read-only qualifier of
2621 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
2622 // Also, do not emit the 'r' for anything but the outermost type!
2623 if (dyn_cast<TypedefType>(T.getTypePtr())) {
2624 if (OutermostType && T.isConstQualified()) {
2625 isReadOnly = true;
2626 S += 'r';
2627 }
2628 }
2629 else if (OutermostType) {
2630 QualType P = PointeeTy;
Ted Kremenek35366a62009-07-17 17:50:17 +00002631 while (P->getAsPointerType())
2632 P = P->getAsPointerType()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002633 if (P.isConstQualified()) {
2634 isReadOnly = true;
2635 S += 'r';
2636 }
2637 }
2638 if (isReadOnly) {
2639 // Another legacy compatibility encoding. Some ObjC qualifier and type
2640 // combinations need to be rearranged.
2641 // Rewrite "in const" from "nr" to "rn"
2642 const char * s = S.c_str();
2643 int len = S.length();
2644 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
2645 std::string replace = "rn";
2646 S.replace(S.end()-2, S.end(), replace);
2647 }
2648 }
Steve Naroff14108da2009-07-10 23:34:53 +00002649 if (isObjCSelType(PointeeTy)) {
Anders Carlsson8baaca52007-10-31 02:53:19 +00002650 S += ':';
2651 return;
Fariborz Jahanianc2939bc2007-10-30 17:06:23 +00002652 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002653
2654 if (PointeeTy->isCharType()) {
2655 // char pointer types should be encoded as '*' unless it is a
2656 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00002657 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002658 S += '*';
2659 return;
2660 }
2661 }
2662
2663 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002664 getLegacyIntegralTypeEncoding(PointeeTy);
2665
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002666 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002667 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002668 return;
2669 }
2670
2671 if (const ArrayType *AT =
2672 // Ignore type qualifiers etc.
2673 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00002674 if (isa<IncompleteArrayType>(AT)) {
2675 // Incomplete arrays are encoded as a pointer to the array element.
2676 S += '^';
2677
2678 getObjCEncodingForTypeImpl(AT->getElementType(), S,
2679 false, ExpandStructures, FD);
2680 } else {
2681 S += '[';
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002682
Anders Carlsson559a8332009-02-22 01:38:57 +00002683 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
2684 S += llvm::utostr(CAT->getSize().getZExtValue());
2685 else {
2686 //Variable length arrays are encoded as a regular array with 0 elements.
2687 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
2688 S += '0';
2689 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002690
Anders Carlsson559a8332009-02-22 01:38:57 +00002691 getObjCEncodingForTypeImpl(AT->getElementType(), S,
2692 false, ExpandStructures, FD);
2693 S += ']';
2694 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002695 return;
2696 }
2697
2698 if (T->getAsFunctionType()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00002699 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002700 return;
2701 }
2702
Ted Kremenek35366a62009-07-17 17:50:17 +00002703 if (const RecordType *RTy = T->getAsRecordType()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002704 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002705 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00002706 // Anonymous structures print as '?'
2707 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
2708 S += II->getName();
2709 } else {
2710 S += '?';
2711 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002712 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002713 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002714 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
2715 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00002716 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002717 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002718 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00002719 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002720 S += '"';
2721 }
2722
2723 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002724 if (Field->isBitField()) {
2725 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
2726 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002727 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002728 QualType qt = Field->getType();
2729 getLegacyIntegralTypeEncoding(qt);
2730 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002731 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002732 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002733 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00002734 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002735 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002736 return;
2737 }
2738
2739 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002740 if (FD && FD->isBitField())
2741 EncodeBitField(this, S, FD);
2742 else
2743 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002744 return;
2745 }
2746
2747 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00002748 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002749 return;
2750 }
2751
2752 if (T->isObjCInterfaceType()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002753 // @encode(class_name)
2754 ObjCInterfaceDecl *OI = T->getAsObjCInterfaceType()->getDecl();
2755 S += '{';
2756 const IdentifierInfo *II = OI->getIdentifier();
2757 S += II->getName();
2758 S += '=';
Chris Lattnerf1690852009-03-31 08:48:01 +00002759 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002760 CollectObjCIvars(OI, RecFields);
Chris Lattnerf1690852009-03-31 08:48:01 +00002761 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002762 if (RecFields[i]->isBitField())
2763 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2764 RecFields[i]);
2765 else
2766 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2767 FD);
2768 }
2769 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002770 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002771 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002772
2773 if (const ObjCObjectPointerType *OPT = T->getAsObjCObjectPointerType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002774 if (OPT->isObjCIdType()) {
2775 S += '@';
2776 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002777 }
2778
2779 if (OPT->isObjCClassType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002780 S += '#';
2781 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002782 }
2783
2784 if (OPT->isObjCQualifiedIdType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002785 getObjCEncodingForTypeImpl(getObjCIdType(), S,
2786 ExpandPointedToStructures,
2787 ExpandStructures, FD);
2788 if (FD || EncodingProperty) {
2789 // Note that we do extended encoding of protocol qualifer list
2790 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00002791 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00002792 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2793 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00002794 S += '<';
2795 S += (*I)->getNameAsString();
2796 S += '>';
2797 }
2798 S += '"';
2799 }
2800 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002801 }
2802
2803 QualType PointeeTy = OPT->getPointeeType();
2804 if (!EncodingProperty &&
2805 isa<TypedefType>(PointeeTy.getTypePtr())) {
2806 // Another historical/compatibility reason.
2807 // We encode the underlying type which comes out as
2808 // {...};
2809 S += '^';
2810 getObjCEncodingForTypeImpl(PointeeTy, S,
2811 false, ExpandPointedToStructures,
2812 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00002813 return;
2814 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002815
2816 S += '@';
2817 if (FD || EncodingProperty) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002818 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00002819 S += OPT->getInterfaceDecl()->getNameAsCString();
2820 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2821 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002822 S += '<';
2823 S += (*I)->getNameAsString();
2824 S += '>';
2825 }
2826 S += '"';
2827 }
2828 return;
2829 }
2830
2831 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002832}
2833
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002834void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002835 std::string& S) const {
2836 if (QT & Decl::OBJC_TQ_In)
2837 S += 'n';
2838 if (QT & Decl::OBJC_TQ_Inout)
2839 S += 'N';
2840 if (QT & Decl::OBJC_TQ_Out)
2841 S += 'o';
2842 if (QT & Decl::OBJC_TQ_Bycopy)
2843 S += 'O';
2844 if (QT & Decl::OBJC_TQ_Byref)
2845 S += 'R';
2846 if (QT & Decl::OBJC_TQ_Oneway)
2847 S += 'V';
2848}
2849
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002850void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002851 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
2852
2853 BuiltinVaListType = T;
2854}
2855
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002856void ASTContext::setObjCIdType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00002857 ObjCIdTypedefType = T;
Steve Naroff7e219e42007-10-15 14:41:52 +00002858}
2859
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002860void ASTContext::setObjCSelType(QualType T) {
Douglas Gregor319ac892009-04-23 22:29:11 +00002861 ObjCSelType = T;
2862
2863 const TypedefType *TT = T->getAsTypedefType();
2864 if (!TT)
2865 return;
2866 TypedefDecl *TD = TT->getDecl();
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002867
2868 // typedef struct objc_selector *SEL;
Ted Kremenek35366a62009-07-17 17:50:17 +00002869 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00002870 if (!ptr)
2871 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002872 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00002873 if (!rec)
2874 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002875 SelStructType = rec;
2876}
2877
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002878void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002879 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00002880}
2881
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002882void ASTContext::setObjCClassType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00002883 ObjCClassTypedefType = T;
Anders Carlsson8baaca52007-10-31 02:53:19 +00002884}
2885
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002886void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
2887 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00002888 "'NSConstantString' type already set!");
2889
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002890 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00002891}
2892
Douglas Gregor7532dc62009-03-30 22:58:21 +00002893/// \brief Retrieve the template name that represents a qualified
2894/// template name such as \c std::vector.
2895TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
2896 bool TemplateKeyword,
2897 TemplateDecl *Template) {
2898 llvm::FoldingSetNodeID ID;
2899 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
2900
2901 void *InsertPos = 0;
2902 QualifiedTemplateName *QTN =
2903 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
2904 if (!QTN) {
2905 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
2906 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
2907 }
2908
2909 return TemplateName(QTN);
2910}
2911
2912/// \brief Retrieve the template name that represents a dependent
2913/// template name such as \c MetaFun::template apply.
2914TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
2915 const IdentifierInfo *Name) {
2916 assert(NNS->isDependent() && "Nested name specifier must be dependent");
2917
2918 llvm::FoldingSetNodeID ID;
2919 DependentTemplateName::Profile(ID, NNS, Name);
2920
2921 void *InsertPos = 0;
2922 DependentTemplateName *QTN =
2923 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
2924
2925 if (QTN)
2926 return TemplateName(QTN);
2927
2928 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2929 if (CanonNNS == NNS) {
2930 QTN = new (*this,4) DependentTemplateName(NNS, Name);
2931 } else {
2932 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
2933 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
2934 }
2935
2936 DependentTemplateNames.InsertNode(QTN, InsertPos);
2937 return TemplateName(QTN);
2938}
2939
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002940/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00002941/// TargetInfo, produce the corresponding type. The unsigned @p Type
2942/// is actually a value of type @c TargetInfo::IntType.
2943QualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002944 switch (Type) {
2945 case TargetInfo::NoInt: return QualType();
2946 case TargetInfo::SignedShort: return ShortTy;
2947 case TargetInfo::UnsignedShort: return UnsignedShortTy;
2948 case TargetInfo::SignedInt: return IntTy;
2949 case TargetInfo::UnsignedInt: return UnsignedIntTy;
2950 case TargetInfo::SignedLong: return LongTy;
2951 case TargetInfo::UnsignedLong: return UnsignedLongTy;
2952 case TargetInfo::SignedLongLong: return LongLongTy;
2953 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
2954 }
2955
2956 assert(false && "Unhandled TargetInfo::IntType value");
Daniel Dunbarb3ac5432008-11-11 01:16:00 +00002957 return QualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002958}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00002959
2960//===----------------------------------------------------------------------===//
2961// Type Predicates.
2962//===----------------------------------------------------------------------===//
2963
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00002964/// isObjCNSObjectType - Return true if this is an NSObject object using
2965/// NSObject attribute on a c-style pointer type.
2966/// FIXME - Make it work directly on types.
Steve Narofff4954562009-07-16 15:41:00 +00002967/// FIXME: Move to Type.
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00002968///
2969bool ASTContext::isObjCNSObjectType(QualType Ty) const {
2970 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
2971 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00002972 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00002973 return true;
2974 }
2975 return false;
2976}
2977
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00002978/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
2979/// garbage collection attribute.
2980///
2981QualType::GCAttrTypes ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
Chris Lattnerb7d25532009-02-18 22:53:11 +00002982 QualType::GCAttrTypes GCAttrs = QualType::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00002983 if (getLangOptions().ObjC1 &&
2984 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00002985 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00002986 // Default behavious under objective-c's gc is for objective-c pointers
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00002987 // (or pointers to them) be treated as though they were declared
2988 // as __strong.
2989 if (GCAttrs == QualType::GCNone) {
Steve Narofff4954562009-07-16 15:41:00 +00002990 if (Ty->isObjCObjectPointerType())
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00002991 GCAttrs = QualType::Strong;
2992 else if (Ty->isPointerType())
Ted Kremenek35366a62009-07-17 17:50:17 +00002993 return getObjCGCAttrKind(Ty->getAsPointerType()->getPointeeType());
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00002994 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00002995 // Non-pointers have none gc'able attribute regardless of the attribute
2996 // set on them.
Steve Narofff4954562009-07-16 15:41:00 +00002997 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
Fariborz Jahanianc2112182009-04-11 00:00:54 +00002998 return QualType::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00002999 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00003000 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003001}
3002
Chris Lattner6ac46a42008-04-07 06:51:04 +00003003//===----------------------------------------------------------------------===//
3004// Type Compatibility Testing
3005//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00003006
Chris Lattner6ac46a42008-04-07 06:51:04 +00003007/// areCompatVectorTypes - Return true if the two specified vector types are
3008/// compatible.
3009static bool areCompatVectorTypes(const VectorType *LHS,
3010 const VectorType *RHS) {
3011 assert(LHS->isCanonical() && RHS->isCanonical());
3012 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00003013 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00003014}
3015
Eli Friedman3d815e72008-08-22 00:56:42 +00003016/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00003017/// compatible for assignment from RHS to LHS. This handles validation of any
3018/// protocol qualifiers on the LHS or RHS.
3019///
Steve Naroff14108da2009-07-10 23:34:53 +00003020/// FIXME: Move the following to ObjCObjectPointerType/ObjCInterfaceType.
3021bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
3022 const ObjCObjectPointerType *RHSOPT) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003023 // If either type represents the built-in 'id' or 'Class' types, return true.
3024 if (LHSOPT->isObjCBuiltinType() || RHSOPT->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00003025 return true;
3026
3027 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
3028 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
Steve Naroffde2e22d2009-07-15 18:40:39 +00003029 if (!LHS || !RHS) {
3030 // We have qualified builtin types.
3031 // Both the right and left sides have qualifiers.
3032 for (ObjCObjectPointerType::qual_iterator I = LHSOPT->qual_begin(),
3033 E = LHSOPT->qual_end(); I != E; ++I) {
3034 bool RHSImplementsProtocol = false;
3035
3036 // when comparing an id<P> on lhs with a static type on rhs,
3037 // see if static class implements all of id's protocols, directly or
3038 // through its super class and categories.
3039 for (ObjCObjectPointerType::qual_iterator J = RHSOPT->qual_begin(),
3040 E = RHSOPT->qual_end(); J != E; ++J) {
Steve Naroff8f167562009-07-16 16:21:02 +00003041 if ((*J)->lookupProtocolNamed((*I)->getIdentifier())) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003042 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00003043 break;
3044 }
Steve Naroffde2e22d2009-07-15 18:40:39 +00003045 }
3046 if (!RHSImplementsProtocol)
3047 return false;
3048 }
3049 // The RHS implements all protocols listed on the LHS.
3050 return true;
3051 }
Steve Naroff14108da2009-07-10 23:34:53 +00003052 return canAssignObjCInterfaces(LHS, RHS);
3053}
3054
Eli Friedman3d815e72008-08-22 00:56:42 +00003055bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
3056 const ObjCInterfaceType *RHS) {
Chris Lattner6ac46a42008-04-07 06:51:04 +00003057 // Verify that the base decls are compatible: the RHS must be a subclass of
3058 // the LHS.
3059 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
3060 return false;
3061
3062 // RHS must have a superset of the protocols in the LHS. If the LHS is not
3063 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00003064 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00003065 return true;
3066
3067 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
3068 // isn't a superset.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00003069 if (RHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00003070 return true; // FIXME: should return false!
3071
Steve Naroffc15cb2a2009-07-18 15:33:26 +00003072 for (ObjCInterfaceType::qual_iterator LHSPI = LHS->qual_begin(),
3073 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003074 LHSPI != LHSPE; LHSPI++) {
3075 bool RHSImplementsProtocol = false;
3076
3077 // If the RHS doesn't implement the protocol on the left, the types
3078 // are incompatible.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00003079 for (ObjCInterfaceType::qual_iterator RHSPI = RHS->qual_begin(),
3080 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00003081 RHSPI != RHSPE; RHSPI++) {
3082 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003083 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00003084 break;
3085 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003086 }
3087 // FIXME: For better diagnostics, consider passing back the protocol name.
3088 if (!RHSImplementsProtocol)
3089 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00003090 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003091 // The RHS implements all protocols listed on the LHS.
3092 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00003093}
3094
Steve Naroff389bf462009-02-12 17:52:19 +00003095bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
3096 // get the "pointed to" types
Steve Naroff14108da2009-07-10 23:34:53 +00003097 const ObjCObjectPointerType *LHSOPT = LHS->getAsObjCObjectPointerType();
3098 const ObjCObjectPointerType *RHSOPT = RHS->getAsObjCObjectPointerType();
Steve Naroff389bf462009-02-12 17:52:19 +00003099
Steve Naroff14108da2009-07-10 23:34:53 +00003100 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00003101 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00003102
3103 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
3104 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00003105}
3106
Steve Naroffec0550f2007-10-15 20:41:53 +00003107/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
3108/// both shall have the identically qualified version of a compatible type.
3109/// C99 6.2.7p1: Two types have compatible types if their types are the
3110/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman3d815e72008-08-22 00:56:42 +00003111bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
3112 return !mergeTypes(LHS, RHS).isNull();
3113}
3114
3115QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
3116 const FunctionType *lbase = lhs->getAsFunctionType();
3117 const FunctionType *rbase = rhs->getAsFunctionType();
Douglas Gregor72564e72009-02-26 23:50:07 +00003118 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
3119 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00003120 bool allLTypes = true;
3121 bool allRTypes = true;
3122
3123 // Check return type
3124 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
3125 if (retType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00003126 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
3127 allLTypes = false;
3128 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
3129 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00003130
3131 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00003132 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
3133 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00003134 unsigned lproto_nargs = lproto->getNumArgs();
3135 unsigned rproto_nargs = rproto->getNumArgs();
3136
3137 // Compatible functions must have the same number of arguments
3138 if (lproto_nargs != rproto_nargs)
3139 return QualType();
3140
3141 // Variadic and non-variadic functions aren't compatible
3142 if (lproto->isVariadic() != rproto->isVariadic())
3143 return QualType();
3144
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003145 if (lproto->getTypeQuals() != rproto->getTypeQuals())
3146 return QualType();
3147
Eli Friedman3d815e72008-08-22 00:56:42 +00003148 // Check argument compatibility
3149 llvm::SmallVector<QualType, 10> types;
3150 for (unsigned i = 0; i < lproto_nargs; i++) {
3151 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
3152 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
3153 QualType argtype = mergeTypes(largtype, rargtype);
3154 if (argtype.isNull()) return QualType();
3155 types.push_back(argtype);
Chris Lattner61710852008-10-05 17:34:18 +00003156 if (getCanonicalType(argtype) != getCanonicalType(largtype))
3157 allLTypes = false;
3158 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
3159 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00003160 }
3161 if (allLTypes) return lhs;
3162 if (allRTypes) return rhs;
3163 return getFunctionType(retType, types.begin(), types.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003164 lproto->isVariadic(), lproto->getTypeQuals());
Eli Friedman3d815e72008-08-22 00:56:42 +00003165 }
3166
3167 if (lproto) allRTypes = false;
3168 if (rproto) allLTypes = false;
3169
Douglas Gregor72564e72009-02-26 23:50:07 +00003170 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00003171 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00003172 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00003173 if (proto->isVariadic()) return QualType();
3174 // Check that the types are compatible with the types that
3175 // would result from default argument promotions (C99 6.7.5.3p15).
3176 // The only types actually affected are promotable integer
3177 // types and floats, which would be passed as a different
3178 // type depending on whether the prototype is visible.
3179 unsigned proto_nargs = proto->getNumArgs();
3180 for (unsigned i = 0; i < proto_nargs; ++i) {
3181 QualType argTy = proto->getArgType(i);
3182 if (argTy->isPromotableIntegerType() ||
3183 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
3184 return QualType();
3185 }
3186
3187 if (allLTypes) return lhs;
3188 if (allRTypes) return rhs;
3189 return getFunctionType(retType, proto->arg_type_begin(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003190 proto->getNumArgs(), lproto->isVariadic(),
3191 lproto->getTypeQuals());
Eli Friedman3d815e72008-08-22 00:56:42 +00003192 }
3193
3194 if (allLTypes) return lhs;
3195 if (allRTypes) return rhs;
Douglas Gregor72564e72009-02-26 23:50:07 +00003196 return getFunctionNoProtoType(retType);
Eli Friedman3d815e72008-08-22 00:56:42 +00003197}
3198
3199QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
Bill Wendling43d69752007-12-03 07:33:35 +00003200 // C++ [expr]: If an expression initially has the type "reference to T", the
3201 // type is adjusted to "T" prior to any further analysis, the expression
3202 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003203 // expression is an lvalue unless the reference is an rvalue reference and
3204 // the expression is a function call (possibly inside parentheses).
Eli Friedman3d815e72008-08-22 00:56:42 +00003205 // FIXME: C++ shouldn't be going through here! The rules are different
3206 // enough that they should be handled separately.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003207 // FIXME: Merging of lvalue and rvalue references is incorrect. C++ *really*
3208 // shouldn't be going through here!
Ted Kremenek35366a62009-07-17 17:50:17 +00003209 if (const ReferenceType *RT = LHS->getAsReferenceType())
Chris Lattnerc4e40592008-04-07 04:07:56 +00003210 LHS = RT->getPointeeType();
Ted Kremenek35366a62009-07-17 17:50:17 +00003211 if (const ReferenceType *RT = RHS->getAsReferenceType())
Chris Lattnerc4e40592008-04-07 04:07:56 +00003212 RHS = RT->getPointeeType();
Chris Lattnerf3692dc2008-04-07 05:37:56 +00003213
Eli Friedman3d815e72008-08-22 00:56:42 +00003214 QualType LHSCan = getCanonicalType(LHS),
3215 RHSCan = getCanonicalType(RHS);
3216
3217 // If two types are identical, they are compatible.
3218 if (LHSCan == RHSCan)
3219 return LHS;
3220
3221 // If the qualifiers are different, the types aren't compatible
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003222 // Note that we handle extended qualifiers later, in the
3223 // case for ExtQualType.
3224 if (LHSCan.getCVRQualifiers() != RHSCan.getCVRQualifiers())
Eli Friedman3d815e72008-08-22 00:56:42 +00003225 return QualType();
3226
Eli Friedman852d63b2009-06-01 01:22:52 +00003227 Type::TypeClass LHSClass = LHSCan->getTypeClass();
3228 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00003229
Chris Lattner1adb8832008-01-14 05:45:46 +00003230 // We want to consider the two function types to be the same for these
3231 // comparisons, just force one to the other.
3232 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
3233 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00003234
Eli Friedman07d25872009-06-02 05:28:56 +00003235 // Strip off objc_gc attributes off the top level so they can be merged.
3236 // This is a complete mess, but the attribute itself doesn't make much sense.
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003237 if (RHSClass == Type::ExtQual) {
Eli Friedman07d25872009-06-02 05:28:56 +00003238 QualType::GCAttrTypes GCAttr = RHSCan.getObjCGCAttr();
3239 if (GCAttr != QualType::GCNone) {
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003240 QualType::GCAttrTypes GCLHSAttr = LHSCan.getObjCGCAttr();
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003241 // __weak attribute must appear on both declarations.
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003242 // __strong attribue is redundant if other decl is an objective-c
3243 // object pointer (or decorated with __strong attribute); otherwise
3244 // issue error.
3245 if ((GCAttr == QualType::Weak && GCLHSAttr != GCAttr) ||
3246 (GCAttr == QualType::Strong && GCLHSAttr != GCAttr &&
Steve Naroff14108da2009-07-10 23:34:53 +00003247 !LHSCan->isObjCObjectPointerType()))
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003248 return QualType();
3249
Eli Friedman07d25872009-06-02 05:28:56 +00003250 RHS = QualType(cast<ExtQualType>(RHS.getDesugaredType())->getBaseType(),
3251 RHS.getCVRQualifiers());
3252 QualType Result = mergeTypes(LHS, RHS);
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003253 if (!Result.isNull()) {
3254 if (Result.getObjCGCAttr() == QualType::GCNone)
3255 Result = getObjCGCQualType(Result, GCAttr);
3256 else if (Result.getObjCGCAttr() != GCAttr)
3257 Result = QualType();
3258 }
Eli Friedman07d25872009-06-02 05:28:56 +00003259 return Result;
3260 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003261 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003262 if (LHSClass == Type::ExtQual) {
Eli Friedman07d25872009-06-02 05:28:56 +00003263 QualType::GCAttrTypes GCAttr = LHSCan.getObjCGCAttr();
3264 if (GCAttr != QualType::GCNone) {
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003265 QualType::GCAttrTypes GCRHSAttr = RHSCan.getObjCGCAttr();
3266 // __weak attribute must appear on both declarations. __strong
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003267 // __strong attribue is redundant if other decl is an objective-c
3268 // object pointer (or decorated with __strong attribute); otherwise
3269 // issue error.
3270 if ((GCAttr == QualType::Weak && GCRHSAttr != GCAttr) ||
3271 (GCAttr == QualType::Strong && GCRHSAttr != GCAttr &&
Steve Naroff14108da2009-07-10 23:34:53 +00003272 !RHSCan->isObjCObjectPointerType()))
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003273 return QualType();
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003274
Eli Friedman07d25872009-06-02 05:28:56 +00003275 LHS = QualType(cast<ExtQualType>(LHS.getDesugaredType())->getBaseType(),
3276 LHS.getCVRQualifiers());
3277 QualType Result = mergeTypes(LHS, RHS);
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003278 if (!Result.isNull()) {
3279 if (Result.getObjCGCAttr() == QualType::GCNone)
3280 Result = getObjCGCQualType(Result, GCAttr);
3281 else if (Result.getObjCGCAttr() != GCAttr)
3282 Result = QualType();
3283 }
Eli Friedman354e53d2009-06-02 07:45:37 +00003284 return Result;
Eli Friedman07d25872009-06-02 05:28:56 +00003285 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003286 }
3287
Eli Friedman4c721d32008-02-12 08:23:06 +00003288 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00003289 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
3290 LHSClass = Type::ConstantArray;
3291 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
3292 RHSClass = Type::ConstantArray;
Steve Naroffec0550f2007-10-15 20:41:53 +00003293
Nate Begeman213541a2008-04-18 23:10:10 +00003294 // Canonicalize ExtVector -> Vector.
3295 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
3296 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Chris Lattnera36a61f2008-04-07 05:43:21 +00003297
3298 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00003299 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00003300 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
3301 // a signed integer type, or an unsigned integer type.
Eli Friedman3d815e72008-08-22 00:56:42 +00003302 if (const EnumType* ETy = LHS->getAsEnumType()) {
3303 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
3304 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00003305 }
Eli Friedman3d815e72008-08-22 00:56:42 +00003306 if (const EnumType* ETy = RHS->getAsEnumType()) {
3307 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
3308 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00003309 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003310
Eli Friedman3d815e72008-08-22 00:56:42 +00003311 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00003312 }
Eli Friedman3d815e72008-08-22 00:56:42 +00003313
Steve Naroff4a746782008-01-09 22:43:08 +00003314 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00003315 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00003316#define TYPE(Class, Base)
3317#define ABSTRACT_TYPE(Class, Base)
3318#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3319#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3320#include "clang/AST/TypeNodes.def"
3321 assert(false && "Non-canonical and dependent types shouldn't get here");
3322 return QualType();
3323
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003324 case Type::LValueReference:
3325 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00003326 case Type::MemberPointer:
3327 assert(false && "C++ should never be in mergeTypes");
3328 return QualType();
3329
3330 case Type::IncompleteArray:
3331 case Type::VariableArray:
3332 case Type::FunctionProto:
3333 case Type::ExtVector:
Douglas Gregor72564e72009-02-26 23:50:07 +00003334 assert(false && "Types are eliminated above");
3335 return QualType();
3336
Chris Lattner1adb8832008-01-14 05:45:46 +00003337 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00003338 {
3339 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek35366a62009-07-17 17:50:17 +00003340 QualType LHSPointee = LHS->getAsPointerType()->getPointeeType();
3341 QualType RHSPointee = RHS->getAsPointerType()->getPointeeType();
Eli Friedman3d815e72008-08-22 00:56:42 +00003342 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
3343 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00003344 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00003345 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00003346 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00003347 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00003348 return getPointerType(ResultType);
3349 }
Steve Naroffc0febd52008-12-10 17:49:55 +00003350 case Type::BlockPointer:
3351 {
3352 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek35366a62009-07-17 17:50:17 +00003353 QualType LHSPointee = LHS->getAsBlockPointerType()->getPointeeType();
3354 QualType RHSPointee = RHS->getAsBlockPointerType()->getPointeeType();
Steve Naroffc0febd52008-12-10 17:49:55 +00003355 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
3356 if (ResultType.isNull()) return QualType();
3357 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
3358 return LHS;
3359 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
3360 return RHS;
3361 return getBlockPointerType(ResultType);
3362 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003363 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00003364 {
3365 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
3366 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
3367 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
3368 return QualType();
3369
3370 QualType LHSElem = getAsArrayType(LHS)->getElementType();
3371 QualType RHSElem = getAsArrayType(RHS)->getElementType();
3372 QualType ResultType = mergeTypes(LHSElem, RHSElem);
3373 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00003374 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3375 return LHS;
3376 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3377 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00003378 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
3379 ArrayType::ArraySizeModifier(), 0);
3380 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
3381 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00003382 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
3383 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00003384 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3385 return LHS;
3386 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3387 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00003388 if (LVAT) {
3389 // FIXME: This isn't correct! But tricky to implement because
3390 // the array's size has to be the size of LHS, but the type
3391 // has to be different.
3392 return LHS;
3393 }
3394 if (RVAT) {
3395 // FIXME: This isn't correct! But tricky to implement because
3396 // the array's size has to be the size of RHS, but the type
3397 // has to be different.
3398 return RHS;
3399 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00003400 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
3401 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003402 return getIncompleteArrayType(ResultType,
3403 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00003404 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003405 case Type::FunctionNoProto:
Eli Friedman3d815e72008-08-22 00:56:42 +00003406 return mergeFunctionTypes(LHS, RHS);
Douglas Gregor72564e72009-02-26 23:50:07 +00003407 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00003408 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00003409 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00003410 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00003411 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00003412 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00003413 case Type::Complex:
3414 // Distinct complex types are incompatible.
3415 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00003416 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003417 // FIXME: The merged type should be an ExtVector!
Eli Friedman3d815e72008-08-22 00:56:42 +00003418 if (areCompatVectorTypes(LHS->getAsVectorType(), RHS->getAsVectorType()))
3419 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00003420 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00003421 case Type::ObjCInterface: {
Steve Naroff5fd659d2009-02-21 16:18:07 +00003422 // Check if the interfaces are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003423 // FIXME: This should be type compatibility, e.g. whether
3424 // "LHS x; RHS x;" at global scope is legal.
Steve Naroff5fd659d2009-02-21 16:18:07 +00003425 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
3426 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
3427 if (LHSIface && RHSIface &&
3428 canAssignObjCInterfaces(LHSIface, RHSIface))
3429 return LHS;
3430
Eli Friedman3d815e72008-08-22 00:56:42 +00003431 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00003432 }
Steve Naroff14108da2009-07-10 23:34:53 +00003433 case Type::ObjCObjectPointer: {
3434 // FIXME: Incorporate tests from Sema::ObjCQualifiedIdTypesAreCompatible().
3435 if (LHS->isObjCQualifiedIdType() && RHS->isObjCQualifiedIdType())
3436 return QualType();
3437
3438 if (canAssignObjCInterfaces(LHS->getAsObjCObjectPointerType(),
3439 RHS->getAsObjCObjectPointerType()))
3440 return LHS;
3441
Steve Naroffbc76dd02008-12-10 22:14:21 +00003442 return QualType();
Steve Naroff14108da2009-07-10 23:34:53 +00003443 }
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003444 case Type::FixedWidthInt:
3445 // Distinct fixed-width integers are not compatible.
3446 return QualType();
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003447 case Type::ExtQual:
3448 // FIXME: ExtQual types can be compatible even if they're not
3449 // identical!
3450 return QualType();
3451 // First attempt at an implementation, but I'm not really sure it's
3452 // right...
3453#if 0
3454 ExtQualType* LQual = cast<ExtQualType>(LHSCan);
3455 ExtQualType* RQual = cast<ExtQualType>(RHSCan);
3456 if (LQual->getAddressSpace() != RQual->getAddressSpace() ||
3457 LQual->getObjCGCAttr() != RQual->getObjCGCAttr())
3458 return QualType();
3459 QualType LHSBase, RHSBase, ResultType, ResCanUnqual;
3460 LHSBase = QualType(LQual->getBaseType(), 0);
3461 RHSBase = QualType(RQual->getBaseType(), 0);
3462 ResultType = mergeTypes(LHSBase, RHSBase);
3463 if (ResultType.isNull()) return QualType();
3464 ResCanUnqual = getCanonicalType(ResultType).getUnqualifiedType();
3465 if (LHSCan.getUnqualifiedType() == ResCanUnqual)
3466 return LHS;
3467 if (RHSCan.getUnqualifiedType() == ResCanUnqual)
3468 return RHS;
3469 ResultType = getAddrSpaceQualType(ResultType, LQual->getAddressSpace());
3470 ResultType = getObjCGCQualType(ResultType, LQual->getObjCGCAttr());
3471 ResultType.setCVRQualifiers(LHSCan.getCVRQualifiers());
3472 return ResultType;
3473#endif
Douglas Gregor7532dc62009-03-30 22:58:21 +00003474
3475 case Type::TemplateSpecialization:
3476 assert(false && "Dependent types have no size");
3477 break;
Steve Naroffec0550f2007-10-15 20:41:53 +00003478 }
Douglas Gregor72564e72009-02-26 23:50:07 +00003479
3480 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00003481}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00003482
Chris Lattner5426bf62008-04-07 07:01:58 +00003483//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00003484// Integer Predicates
3485//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00003486
Eli Friedmanad74a752008-06-28 06:23:08 +00003487unsigned ASTContext::getIntWidth(QualType T) {
3488 if (T == BoolTy)
3489 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00003490 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T)) {
3491 return FWIT->getWidth();
3492 }
3493 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00003494 return (unsigned)getTypeSize(T);
3495}
3496
3497QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
3498 assert(T->isSignedIntegerType() && "Unexpected type");
3499 if (const EnumType* ETy = T->getAsEnumType())
3500 T = ETy->getDecl()->getIntegerType();
3501 const BuiltinType* BTy = T->getAsBuiltinType();
3502 assert (BTy && "Unexpected signed integer type");
3503 switch (BTy->getKind()) {
3504 case BuiltinType::Char_S:
3505 case BuiltinType::SChar:
3506 return UnsignedCharTy;
3507 case BuiltinType::Short:
3508 return UnsignedShortTy;
3509 case BuiltinType::Int:
3510 return UnsignedIntTy;
3511 case BuiltinType::Long:
3512 return UnsignedLongTy;
3513 case BuiltinType::LongLong:
3514 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00003515 case BuiltinType::Int128:
3516 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00003517 default:
3518 assert(0 && "Unexpected signed integer type");
3519 return QualType();
3520 }
3521}
3522
Douglas Gregor2cf26342009-04-09 22:27:44 +00003523ExternalASTSource::~ExternalASTSource() { }
3524
3525void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00003526
3527
3528//===----------------------------------------------------------------------===//
3529// Builtin Type Computation
3530//===----------------------------------------------------------------------===//
3531
3532/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
3533/// pointer over the consumed characters. This returns the resultant type.
3534static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
3535 ASTContext::GetBuiltinTypeError &Error,
3536 bool AllowTypeModifiers = true) {
3537 // Modifiers.
3538 int HowLong = 0;
3539 bool Signed = false, Unsigned = false;
3540
3541 // Read the modifiers first.
3542 bool Done = false;
3543 while (!Done) {
3544 switch (*Str++) {
3545 default: Done = true; --Str; break;
3546 case 'S':
3547 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
3548 assert(!Signed && "Can't use 'S' modifier multiple times!");
3549 Signed = true;
3550 break;
3551 case 'U':
3552 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
3553 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
3554 Unsigned = true;
3555 break;
3556 case 'L':
3557 assert(HowLong <= 2 && "Can't have LLLL modifier");
3558 ++HowLong;
3559 break;
3560 }
3561 }
3562
3563 QualType Type;
3564
3565 // Read the base type.
3566 switch (*Str++) {
3567 default: assert(0 && "Unknown builtin type letter!");
3568 case 'v':
3569 assert(HowLong == 0 && !Signed && !Unsigned &&
3570 "Bad modifiers used with 'v'!");
3571 Type = Context.VoidTy;
3572 break;
3573 case 'f':
3574 assert(HowLong == 0 && !Signed && !Unsigned &&
3575 "Bad modifiers used with 'f'!");
3576 Type = Context.FloatTy;
3577 break;
3578 case 'd':
3579 assert(HowLong < 2 && !Signed && !Unsigned &&
3580 "Bad modifiers used with 'd'!");
3581 if (HowLong)
3582 Type = Context.LongDoubleTy;
3583 else
3584 Type = Context.DoubleTy;
3585 break;
3586 case 's':
3587 assert(HowLong == 0 && "Bad modifiers used with 's'!");
3588 if (Unsigned)
3589 Type = Context.UnsignedShortTy;
3590 else
3591 Type = Context.ShortTy;
3592 break;
3593 case 'i':
3594 if (HowLong == 3)
3595 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
3596 else if (HowLong == 2)
3597 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
3598 else if (HowLong == 1)
3599 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
3600 else
3601 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
3602 break;
3603 case 'c':
3604 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
3605 if (Signed)
3606 Type = Context.SignedCharTy;
3607 else if (Unsigned)
3608 Type = Context.UnsignedCharTy;
3609 else
3610 Type = Context.CharTy;
3611 break;
3612 case 'b': // boolean
3613 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
3614 Type = Context.BoolTy;
3615 break;
3616 case 'z': // size_t.
3617 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
3618 Type = Context.getSizeType();
3619 break;
3620 case 'F':
3621 Type = Context.getCFConstantStringType();
3622 break;
3623 case 'a':
3624 Type = Context.getBuiltinVaListType();
3625 assert(!Type.isNull() && "builtin va list type not initialized!");
3626 break;
3627 case 'A':
3628 // This is a "reference" to a va_list; however, what exactly
3629 // this means depends on how va_list is defined. There are two
3630 // different kinds of va_list: ones passed by value, and ones
3631 // passed by reference. An example of a by-value va_list is
3632 // x86, where va_list is a char*. An example of by-ref va_list
3633 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
3634 // we want this argument to be a char*&; for x86-64, we want
3635 // it to be a __va_list_tag*.
3636 Type = Context.getBuiltinVaListType();
3637 assert(!Type.isNull() && "builtin va list type not initialized!");
3638 if (Type->isArrayType()) {
3639 Type = Context.getArrayDecayedType(Type);
3640 } else {
3641 Type = Context.getLValueReferenceType(Type);
3642 }
3643 break;
3644 case 'V': {
3645 char *End;
3646
3647 unsigned NumElements = strtoul(Str, &End, 10);
3648 assert(End != Str && "Missing vector size");
3649
3650 Str = End;
3651
3652 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
3653 Type = Context.getVectorType(ElementType, NumElements);
3654 break;
3655 }
3656 case 'P': {
Douglas Gregorc29f77b2009-07-07 16:35:42 +00003657 Type = Context.getFILEType();
3658 if (Type.isNull()) {
Chris Lattner86df27b2009-06-14 00:45:47 +00003659 Error = ASTContext::GE_Missing_FILE;
3660 return QualType();
Douglas Gregorc29f77b2009-07-07 16:35:42 +00003661 } else {
3662 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00003663 }
3664 }
3665 }
3666
3667 if (!AllowTypeModifiers)
3668 return Type;
3669
3670 Done = false;
3671 while (!Done) {
3672 switch (*Str++) {
3673 default: Done = true; --Str; break;
3674 case '*':
3675 Type = Context.getPointerType(Type);
3676 break;
3677 case '&':
3678 Type = Context.getLValueReferenceType(Type);
3679 break;
3680 // FIXME: There's no way to have a built-in with an rvalue ref arg.
3681 case 'C':
3682 Type = Type.getQualifiedType(QualType::Const);
3683 break;
3684 }
3685 }
3686
3687 return Type;
3688}
3689
3690/// GetBuiltinType - Return the type for the specified builtin.
3691QualType ASTContext::GetBuiltinType(unsigned id,
3692 GetBuiltinTypeError &Error) {
3693 const char *TypeStr = BuiltinInfo.GetTypeString(id);
3694
3695 llvm::SmallVector<QualType, 8> ArgTypes;
3696
3697 Error = GE_None;
3698 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
3699 if (Error != GE_None)
3700 return QualType();
3701 while (TypeStr[0] && TypeStr[0] != '.') {
3702 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
3703 if (Error != GE_None)
3704 return QualType();
3705
3706 // Do array -> pointer decay. The builtin should use the decayed type.
3707 if (Ty->isArrayType())
3708 Ty = getArrayDecayedType(Ty);
3709
3710 ArgTypes.push_back(Ty);
3711 }
3712
3713 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
3714 "'.' should only occur at end of builtin type list!");
3715
3716 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
3717 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
3718 return getFunctionNoProtoType(ResType);
3719 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
3720 TypeStr[0] == '.', 0);
3721}