blob: 4490e9a3a9c06809c9d34f3834acef97963e44c3 [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.
Eli Friedmanab22c432009-07-22 20:29:16 +0000911 // Note that we can't save a reference to the entry because this function
912 // is recursive.
913 const ASTRecordLayout *Entry = ASTRecordLayouts[D];
Chris Lattner464175b2007-07-18 17:52:12 +0000914 if (Entry) return *Entry;
Eli Friedman4bd998b2008-05-30 09:31:38 +0000915
Anders Carlsson29445a02009-07-18 21:19:52 +0000916 const ASTRecordLayout *NewEntry =
917 ASTRecordLayoutBuilder::ComputeLayout(*this, D);
Eli Friedmanab22c432009-07-22 20:29:16 +0000918 ASTRecordLayouts[D] = NewEntry;
Anders Carlsson29445a02009-07-18 21:19:52 +0000919
Chris Lattner5d2a6302007-07-18 18:26:58 +0000920 return *NewEntry;
Chris Lattner464175b2007-07-18 17:52:12 +0000921}
922
Chris Lattnera7674d82007-07-13 22:13:22 +0000923//===----------------------------------------------------------------------===//
924// Type creation/memoization methods
925//===----------------------------------------------------------------------===//
926
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000927QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerf52ab252008-04-06 22:59:24 +0000928 QualType CanT = getCanonicalType(T);
929 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +0000930 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +0000931
932 // If we are composing extended qualifiers together, merge together into one
933 // ExtQualType node.
934 unsigned CVRQuals = T.getCVRQualifiers();
935 QualType::GCAttrTypes GCAttr = QualType::GCNone;
936 Type *TypeNode = T.getTypePtr();
Chris Lattnerf46699c2008-02-20 20:55:12 +0000937
Chris Lattnerb7d25532009-02-18 22:53:11 +0000938 if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
939 // If this type already has an address space specified, it cannot get
940 // another one.
941 assert(EQT->getAddressSpace() == 0 &&
942 "Type cannot be in multiple addr spaces!");
943 GCAttr = EQT->getObjCGCAttr();
944 TypeNode = EQT->getBaseType();
945 }
Chris Lattnerf46699c2008-02-20 20:55:12 +0000946
Chris Lattnerb7d25532009-02-18 22:53:11 +0000947 // Check if we've already instantiated this type.
Christopher Lambebb97e92008-02-04 02:31:56 +0000948 llvm::FoldingSetNodeID ID;
Chris Lattnerb7d25532009-02-18 22:53:11 +0000949 ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
Christopher Lambebb97e92008-02-04 02:31:56 +0000950 void *InsertPos = 0;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000951 if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattnerb7d25532009-02-18 22:53:11 +0000952 return QualType(EXTQy, CVRQuals);
953
Christopher Lambebb97e92008-02-04 02:31:56 +0000954 // If the base type isn't canonical, this won't be a canonical type either,
955 // so fill in the canonical type field.
956 QualType Canonical;
Chris Lattnerb7d25532009-02-18 22:53:11 +0000957 if (!TypeNode->isCanonical()) {
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000958 Canonical = getAddrSpaceQualType(CanT, AddressSpace);
Christopher Lambebb97e92008-02-04 02:31:56 +0000959
Chris Lattnerb7d25532009-02-18 22:53:11 +0000960 // Update InsertPos, the previous call could have invalidated it.
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000961 ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +0000962 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Christopher Lambebb97e92008-02-04 02:31:56 +0000963 }
Chris Lattnerb7d25532009-02-18 22:53:11 +0000964 ExtQualType *New =
965 new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000966 ExtQualTypes.InsertNode(New, InsertPos);
Christopher Lambebb97e92008-02-04 02:31:56 +0000967 Types.push_back(New);
Chris Lattnerb7d25532009-02-18 22:53:11 +0000968 return QualType(New, CVRQuals);
Christopher Lambebb97e92008-02-04 02:31:56 +0000969}
970
Chris Lattnerb7d25532009-02-18 22:53:11 +0000971QualType ASTContext::getObjCGCQualType(QualType T,
972 QualType::GCAttrTypes GCAttr) {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000973 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +0000974 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000975 return T;
976
Fariborz Jahanian4027cd12009-06-03 17:15:17 +0000977 if (T->isPointerType()) {
Ted Kremenek35366a62009-07-17 17:50:17 +0000978 QualType Pointee = T->getAsPointerType()->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +0000979 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +0000980 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
981 return getPointerType(ResultType);
982 }
983 }
Chris Lattnerb7d25532009-02-18 22:53:11 +0000984 // If we are composing extended qualifiers together, merge together into one
985 // ExtQualType node.
986 unsigned CVRQuals = T.getCVRQualifiers();
987 Type *TypeNode = T.getTypePtr();
988 unsigned AddressSpace = 0;
989
990 if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
991 // If this type already has an address space specified, it cannot get
992 // another one.
993 assert(EQT->getObjCGCAttr() == QualType::GCNone &&
994 "Type cannot be in multiple addr spaces!");
995 AddressSpace = EQT->getAddressSpace();
996 TypeNode = EQT->getBaseType();
997 }
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000998
999 // Check if we've already instantiated an gc qual'd type of this type.
1000 llvm::FoldingSetNodeID ID;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001001 ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001002 void *InsertPos = 0;
1003 if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattnerb7d25532009-02-18 22:53:11 +00001004 return QualType(EXTQy, CVRQuals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001005
1006 // If the base type isn't canonical, this won't be a canonical type either,
1007 // so fill in the canonical type field.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00001008 // FIXME: Isn't this also not canonical if the base type is a array
1009 // or pointer type? I can't find any documentation for objc_gc, though...
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001010 QualType Canonical;
1011 if (!T->isCanonical()) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00001012 Canonical = getObjCGCQualType(CanT, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001013
Chris Lattnerb7d25532009-02-18 22:53:11 +00001014 // Update InsertPos, the previous call could have invalidated it.
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001015 ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
1016 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1017 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00001018 ExtQualType *New =
1019 new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001020 ExtQualTypes.InsertNode(New, InsertPos);
1021 Types.push_back(New);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001022 return QualType(New, CVRQuals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001023}
Chris Lattnera7674d82007-07-13 22:13:22 +00001024
Reid Spencer5f016e22007-07-11 17:01:13 +00001025/// getComplexType - Return the uniqued reference to the type for a complex
1026/// number with the specified element type.
1027QualType ASTContext::getComplexType(QualType T) {
1028 // Unique pointers, to guarantee there is only one pointer of a particular
1029 // structure.
1030 llvm::FoldingSetNodeID ID;
1031 ComplexType::Profile(ID, T);
1032
1033 void *InsertPos = 0;
1034 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1035 return QualType(CT, 0);
1036
1037 // If the pointee type isn't canonical, this won't be a canonical type either,
1038 // so fill in the canonical type field.
1039 QualType Canonical;
1040 if (!T->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001041 Canonical = getComplexType(getCanonicalType(T));
Reid Spencer5f016e22007-07-11 17:01:13 +00001042
1043 // Get the new insert position for the node we care about.
1044 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001045 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001046 }
Steve Narofff83820b2009-01-27 22:08:43 +00001047 ComplexType *New = new (*this,8) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001048 Types.push_back(New);
1049 ComplexTypes.InsertNode(New, InsertPos);
1050 return QualType(New, 0);
1051}
1052
Eli Friedmanf98aba32009-02-13 02:31:07 +00001053QualType ASTContext::getFixedWidthIntType(unsigned Width, bool Signed) {
1054 llvm::DenseMap<unsigned, FixedWidthIntType*> &Map = Signed ?
1055 SignedFixedWidthIntTypes : UnsignedFixedWidthIntTypes;
1056 FixedWidthIntType *&Entry = Map[Width];
1057 if (!Entry)
1058 Entry = new FixedWidthIntType(Width, Signed);
1059 return QualType(Entry, 0);
1060}
Reid Spencer5f016e22007-07-11 17:01:13 +00001061
1062/// getPointerType - Return the uniqued reference to the type for a pointer to
1063/// the specified type.
1064QualType ASTContext::getPointerType(QualType T) {
1065 // Unique pointers, to guarantee there is only one pointer of a particular
1066 // structure.
1067 llvm::FoldingSetNodeID ID;
1068 PointerType::Profile(ID, T);
1069
1070 void *InsertPos = 0;
1071 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1072 return QualType(PT, 0);
1073
1074 // If the pointee type isn't canonical, this won't be a canonical type either,
1075 // so fill in the canonical type field.
1076 QualType Canonical;
1077 if (!T->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001078 Canonical = getPointerType(getCanonicalType(T));
Reid Spencer5f016e22007-07-11 17:01:13 +00001079
1080 // Get the new insert position for the node we care about.
1081 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001082 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001083 }
Steve Narofff83820b2009-01-27 22:08:43 +00001084 PointerType *New = new (*this,8) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001085 Types.push_back(New);
1086 PointerTypes.InsertNode(New, InsertPos);
1087 return QualType(New, 0);
1088}
1089
Steve Naroff5618bd42008-08-27 16:04:49 +00001090/// getBlockPointerType - Return the uniqued reference to the type for
1091/// a pointer to the specified block.
1092QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff296e8d52008-08-28 19:20:44 +00001093 assert(T->isFunctionType() && "block of function types only");
1094 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001095 // structure.
1096 llvm::FoldingSetNodeID ID;
1097 BlockPointerType::Profile(ID, T);
1098
1099 void *InsertPos = 0;
1100 if (BlockPointerType *PT =
1101 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1102 return QualType(PT, 0);
1103
Steve Naroff296e8d52008-08-28 19:20:44 +00001104 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001105 // type either so fill in the canonical type field.
1106 QualType Canonical;
1107 if (!T->isCanonical()) {
1108 Canonical = getBlockPointerType(getCanonicalType(T));
1109
1110 // Get the new insert position for the node we care about.
1111 BlockPointerType *NewIP =
1112 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001113 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001114 }
Steve Narofff83820b2009-01-27 22:08:43 +00001115 BlockPointerType *New = new (*this,8) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001116 Types.push_back(New);
1117 BlockPointerTypes.InsertNode(New, InsertPos);
1118 return QualType(New, 0);
1119}
1120
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001121/// getLValueReferenceType - Return the uniqued reference to the type for an
1122/// lvalue reference to the specified type.
1123QualType ASTContext::getLValueReferenceType(QualType T) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001124 // Unique pointers, to guarantee there is only one pointer of a particular
1125 // structure.
1126 llvm::FoldingSetNodeID ID;
1127 ReferenceType::Profile(ID, T);
1128
1129 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001130 if (LValueReferenceType *RT =
1131 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001132 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001133
Reid Spencer5f016e22007-07-11 17:01:13 +00001134 // If the referencee type isn't canonical, this won't be a canonical type
1135 // either, so fill in the canonical type field.
1136 QualType Canonical;
1137 if (!T->isCanonical()) {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001138 Canonical = getLValueReferenceType(getCanonicalType(T));
1139
Reid Spencer5f016e22007-07-11 17:01:13 +00001140 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001141 LValueReferenceType *NewIP =
1142 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001143 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001144 }
1145
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001146 LValueReferenceType *New = new (*this,8) LValueReferenceType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001147 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001148 LValueReferenceTypes.InsertNode(New, InsertPos);
1149 return QualType(New, 0);
1150}
1151
1152/// getRValueReferenceType - Return the uniqued reference to the type for an
1153/// rvalue reference to the specified type.
1154QualType ASTContext::getRValueReferenceType(QualType T) {
1155 // Unique pointers, to guarantee there is only one pointer of a particular
1156 // structure.
1157 llvm::FoldingSetNodeID ID;
1158 ReferenceType::Profile(ID, T);
1159
1160 void *InsertPos = 0;
1161 if (RValueReferenceType *RT =
1162 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1163 return QualType(RT, 0);
1164
1165 // If the referencee type isn't canonical, this won't be a canonical type
1166 // either, so fill in the canonical type field.
1167 QualType Canonical;
1168 if (!T->isCanonical()) {
1169 Canonical = getRValueReferenceType(getCanonicalType(T));
1170
1171 // Get the new insert position for the node we care about.
1172 RValueReferenceType *NewIP =
1173 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1174 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1175 }
1176
1177 RValueReferenceType *New = new (*this,8) RValueReferenceType(T, Canonical);
1178 Types.push_back(New);
1179 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001180 return QualType(New, 0);
1181}
1182
Sebastian Redlf30208a2009-01-24 21:16:55 +00001183/// getMemberPointerType - Return the uniqued reference to the type for a
1184/// member pointer to the specified type, in the specified class.
1185QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls)
1186{
1187 // Unique pointers, to guarantee there is only one pointer of a particular
1188 // structure.
1189 llvm::FoldingSetNodeID ID;
1190 MemberPointerType::Profile(ID, T, Cls);
1191
1192 void *InsertPos = 0;
1193 if (MemberPointerType *PT =
1194 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1195 return QualType(PT, 0);
1196
1197 // If the pointee or class type isn't canonical, this won't be a canonical
1198 // type either, so fill in the canonical type field.
1199 QualType Canonical;
1200 if (!T->isCanonical()) {
1201 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1202
1203 // Get the new insert position for the node we care about.
1204 MemberPointerType *NewIP =
1205 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1206 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1207 }
Steve Narofff83820b2009-01-27 22:08:43 +00001208 MemberPointerType *New = new (*this,8) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001209 Types.push_back(New);
1210 MemberPointerTypes.InsertNode(New, InsertPos);
1211 return QualType(New, 0);
1212}
1213
Steve Narofffb22d962007-08-30 01:06:46 +00001214/// getConstantArrayType - Return the unique reference to the type for an
1215/// array of the specified element type.
1216QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001217 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001218 ArrayType::ArraySizeModifier ASM,
1219 unsigned EltTypeQuals) {
Eli Friedman587cbdf2009-05-29 20:17:55 +00001220 assert((EltTy->isDependentType() || EltTy->isConstantSizeType()) &&
1221 "Constant array of VLAs is illegal!");
1222
Chris Lattner38aeec72009-05-13 04:12:56 +00001223 // Convert the array size into a canonical width matching the pointer size for
1224 // the target.
1225 llvm::APInt ArySize(ArySizeIn);
1226 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1227
Reid Spencer5f016e22007-07-11 17:01:13 +00001228 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001229 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001230
1231 void *InsertPos = 0;
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001232 if (ConstantArrayType *ATP =
1233 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001234 return QualType(ATP, 0);
1235
1236 // If the element type isn't canonical, this won't be a canonical type either,
1237 // so fill in the canonical type field.
1238 QualType Canonical;
1239 if (!EltTy->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001240 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroffc9406122007-08-30 18:10:14 +00001241 ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001242 // Get the new insert position for the node we care about.
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001243 ConstantArrayType *NewIP =
1244 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001245 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001246 }
1247
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001248 ConstantArrayType *New =
Steve Narofff83820b2009-01-27 22:08:43 +00001249 new(*this,8)ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001250 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001251 Types.push_back(New);
1252 return QualType(New, 0);
1253}
1254
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001255/// getConstantArrayWithExprType - Return a reference to the type for
1256/// an array of the specified element type.
1257QualType
1258ASTContext::getConstantArrayWithExprType(QualType EltTy,
1259 const llvm::APInt &ArySizeIn,
1260 Expr *ArySizeExpr,
1261 ArrayType::ArraySizeModifier ASM,
1262 unsigned EltTypeQuals,
1263 SourceRange Brackets) {
1264 // Convert the array size into a canonical width matching the pointer
1265 // size for the target.
1266 llvm::APInt ArySize(ArySizeIn);
1267 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1268
1269 // Compute the canonical ConstantArrayType.
1270 QualType Canonical = getConstantArrayType(getCanonicalType(EltTy),
1271 ArySize, ASM, EltTypeQuals);
1272 // Since we don't unique expressions, it isn't possible to unique VLA's
1273 // that have an expression provided for their size.
1274 ConstantArrayWithExprType *New =
1275 new(*this,8)ConstantArrayWithExprType(EltTy, Canonical,
1276 ArySize, ArySizeExpr,
1277 ASM, EltTypeQuals, Brackets);
1278 Types.push_back(New);
1279 return QualType(New, 0);
1280}
1281
1282/// getConstantArrayWithoutExprType - Return a reference to the type for
1283/// an array of the specified element type.
1284QualType
1285ASTContext::getConstantArrayWithoutExprType(QualType EltTy,
1286 const llvm::APInt &ArySizeIn,
1287 ArrayType::ArraySizeModifier ASM,
1288 unsigned EltTypeQuals) {
1289 // Convert the array size into a canonical width matching the pointer
1290 // size for the target.
1291 llvm::APInt ArySize(ArySizeIn);
1292 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1293
1294 // Compute the canonical ConstantArrayType.
1295 QualType Canonical = getConstantArrayType(getCanonicalType(EltTy),
1296 ArySize, ASM, EltTypeQuals);
1297 ConstantArrayWithoutExprType *New =
1298 new(*this,8)ConstantArrayWithoutExprType(EltTy, Canonical,
1299 ArySize, ASM, EltTypeQuals);
1300 Types.push_back(New);
1301 return QualType(New, 0);
1302}
1303
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001304/// getVariableArrayType - Returns a non-unique reference to the type for a
1305/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001306QualType ASTContext::getVariableArrayType(QualType EltTy,
1307 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001308 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001309 unsigned EltTypeQuals,
1310 SourceRange Brackets) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001311 // Since we don't unique expressions, it isn't possible to unique VLA's
1312 // that have an expression provided for their size.
1313
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001314 VariableArrayType *New =
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001315 new(*this,8)VariableArrayType(EltTy, QualType(),
1316 NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001317
1318 VariableArrayTypes.push_back(New);
1319 Types.push_back(New);
1320 return QualType(New, 0);
1321}
1322
Douglas Gregor898574e2008-12-05 23:32:09 +00001323/// getDependentSizedArrayType - Returns a non-unique reference to
1324/// the type for a dependently-sized array of the specified element
1325/// type. FIXME: We will need these to be uniqued, or at least
1326/// comparable, at some point.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001327QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1328 Expr *NumElts,
Douglas Gregor898574e2008-12-05 23:32:09 +00001329 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001330 unsigned EltTypeQuals,
1331 SourceRange Brackets) {
Douglas Gregor898574e2008-12-05 23:32:09 +00001332 assert((NumElts->isTypeDependent() || NumElts->isValueDependent()) &&
1333 "Size must be type- or value-dependent!");
1334
1335 // Since we don't unique expressions, it isn't possible to unique
1336 // dependently-sized array types.
1337
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001338 DependentSizedArrayType *New =
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001339 new (*this,8) DependentSizedArrayType(EltTy, QualType(),
1340 NumElts, ASM, EltTypeQuals,
1341 Brackets);
Douglas Gregor898574e2008-12-05 23:32:09 +00001342
1343 DependentSizedArrayTypes.push_back(New);
1344 Types.push_back(New);
1345 return QualType(New, 0);
1346}
1347
Eli Friedmanc5773c42008-02-15 18:16:39 +00001348QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1349 ArrayType::ArraySizeModifier ASM,
1350 unsigned EltTypeQuals) {
1351 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001352 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001353
1354 void *InsertPos = 0;
1355 if (IncompleteArrayType *ATP =
1356 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1357 return QualType(ATP, 0);
1358
1359 // If the element type isn't canonical, this won't be a canonical type
1360 // either, so fill in the canonical type field.
1361 QualType Canonical;
1362
1363 if (!EltTy->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001364 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001365 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001366
1367 // Get the new insert position for the node we care about.
1368 IncompleteArrayType *NewIP =
1369 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001370 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001371 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001372
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001373 IncompleteArrayType *New
1374 = new (*this,8) IncompleteArrayType(EltTy, Canonical,
1375 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001376
1377 IncompleteArrayTypes.InsertNode(New, InsertPos);
1378 Types.push_back(New);
1379 return QualType(New, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001380}
1381
Steve Naroff73322922007-07-18 18:00:27 +00001382/// getVectorType - Return the unique reference to a vector type of
1383/// the specified element type and size. VectorType must be a built-in type.
1384QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001385 BuiltinType *baseType;
1386
Chris Lattnerf52ab252008-04-06 22:59:24 +00001387 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff73322922007-07-18 18:00:27 +00001388 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Reid Spencer5f016e22007-07-11 17:01:13 +00001389
1390 // Check if we've already instantiated a vector of this type.
1391 llvm::FoldingSetNodeID ID;
Steve Naroff73322922007-07-18 18:00:27 +00001392 VectorType::Profile(ID, vecType, NumElts, Type::Vector);
Reid Spencer5f016e22007-07-11 17:01:13 +00001393 void *InsertPos = 0;
1394 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1395 return QualType(VTP, 0);
1396
1397 // If the element type isn't canonical, this won't be a canonical type either,
1398 // so fill in the canonical type field.
1399 QualType Canonical;
1400 if (!vecType->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001401 Canonical = getVectorType(getCanonicalType(vecType), NumElts);
Reid Spencer5f016e22007-07-11 17:01:13 +00001402
1403 // Get the new insert position for the node we care about.
1404 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001405 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001406 }
Steve Narofff83820b2009-01-27 22:08:43 +00001407 VectorType *New = new (*this,8) VectorType(vecType, NumElts, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001408 VectorTypes.InsertNode(New, InsertPos);
1409 Types.push_back(New);
1410 return QualType(New, 0);
1411}
1412
Nate Begeman213541a2008-04-18 23:10:10 +00001413/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001414/// the specified element type and size. VectorType must be a built-in type.
Nate Begeman213541a2008-04-18 23:10:10 +00001415QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff73322922007-07-18 18:00:27 +00001416 BuiltinType *baseType;
1417
Chris Lattnerf52ab252008-04-06 22:59:24 +00001418 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begeman213541a2008-04-18 23:10:10 +00001419 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Steve Naroff73322922007-07-18 18:00:27 +00001420
1421 // Check if we've already instantiated a vector of this type.
1422 llvm::FoldingSetNodeID ID;
Nate Begeman213541a2008-04-18 23:10:10 +00001423 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector);
Steve Naroff73322922007-07-18 18:00:27 +00001424 void *InsertPos = 0;
1425 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1426 return QualType(VTP, 0);
1427
1428 // If the element type isn't canonical, this won't be a canonical type either,
1429 // so fill in the canonical type field.
1430 QualType Canonical;
1431 if (!vecType->isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001432 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Steve Naroff73322922007-07-18 18:00:27 +00001433
1434 // Get the new insert position for the node we care about.
1435 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001436 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001437 }
Steve Narofff83820b2009-01-27 22:08:43 +00001438 ExtVectorType *New = new (*this,8) ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001439 VectorTypes.InsertNode(New, InsertPos);
1440 Types.push_back(New);
1441 return QualType(New, 0);
1442}
1443
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001444QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
1445 Expr *SizeExpr,
1446 SourceLocation AttrLoc) {
1447 DependentSizedExtVectorType *New =
1448 new (*this,8) DependentSizedExtVectorType(vecType, QualType(),
1449 SizeExpr, AttrLoc);
1450
1451 DependentSizedExtVectorTypes.push_back(New);
1452 Types.push_back(New);
1453 return QualType(New, 0);
1454}
1455
Douglas Gregor72564e72009-02-26 23:50:07 +00001456/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001457///
Douglas Gregor72564e72009-02-26 23:50:07 +00001458QualType ASTContext::getFunctionNoProtoType(QualType ResultTy) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001459 // Unique functions, to guarantee there is only one function of a particular
1460 // structure.
1461 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001462 FunctionNoProtoType::Profile(ID, ResultTy);
Reid Spencer5f016e22007-07-11 17:01:13 +00001463
1464 void *InsertPos = 0;
Douglas Gregor72564e72009-02-26 23:50:07 +00001465 if (FunctionNoProtoType *FT =
1466 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001467 return QualType(FT, 0);
1468
1469 QualType Canonical;
1470 if (!ResultTy->isCanonical()) {
Douglas Gregor72564e72009-02-26 23:50:07 +00001471 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy));
Reid Spencer5f016e22007-07-11 17:01:13 +00001472
1473 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001474 FunctionNoProtoType *NewIP =
1475 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001476 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001477 }
1478
Douglas Gregor72564e72009-02-26 23:50:07 +00001479 FunctionNoProtoType *New =new(*this,8)FunctionNoProtoType(ResultTy,Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001480 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001481 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001482 return QualType(New, 0);
1483}
1484
1485/// getFunctionType - Return a normal function type with a typed argument
1486/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner61710852008-10-05 17:34:18 +00001487QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001488 unsigned NumArgs, bool isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001489 unsigned TypeQuals, bool hasExceptionSpec,
1490 bool hasAnyExceptionSpec, unsigned NumExs,
1491 const QualType *ExArray) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001492 // Unique functions, to guarantee there is only one function of a particular
1493 // structure.
1494 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001495 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001496 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
1497 NumExs, ExArray);
Reid Spencer5f016e22007-07-11 17:01:13 +00001498
1499 void *InsertPos = 0;
Douglas Gregor72564e72009-02-26 23:50:07 +00001500 if (FunctionProtoType *FTP =
1501 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001502 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001503
1504 // Determine whether the type being created is already canonical or not.
Reid Spencer5f016e22007-07-11 17:01:13 +00001505 bool isCanonical = ResultTy->isCanonical();
Sebastian Redl465226e2009-05-27 22:11:52 +00001506 if (hasExceptionSpec)
1507 isCanonical = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001508 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
1509 if (!ArgArray[i]->isCanonical())
1510 isCanonical = false;
1511
1512 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001513 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001514 QualType Canonical;
1515 if (!isCanonical) {
1516 llvm::SmallVector<QualType, 16> CanonicalArgs;
1517 CanonicalArgs.reserve(NumArgs);
1518 for (unsigned i = 0; i != NumArgs; ++i)
Chris Lattnerf52ab252008-04-06 22:59:24 +00001519 CanonicalArgs.push_back(getCanonicalType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001520
Chris Lattnerf52ab252008-04-06 22:59:24 +00001521 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001522 CanonicalArgs.data(), NumArgs,
Sebastian Redlbfa2fcb2009-05-06 23:27:55 +00001523 isVariadic, TypeQuals);
Sebastian Redl465226e2009-05-27 22:11:52 +00001524
Reid Spencer5f016e22007-07-11 17:01:13 +00001525 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001526 FunctionProtoType *NewIP =
1527 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001528 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001529 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001530
Douglas Gregor72564e72009-02-26 23:50:07 +00001531 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001532 // for two variable size arrays (for parameter and exception types) at the
1533 // end of them.
Douglas Gregor72564e72009-02-26 23:50:07 +00001534 FunctionProtoType *FTP =
Sebastian Redl465226e2009-05-27 22:11:52 +00001535 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1536 NumArgs*sizeof(QualType) +
1537 NumExs*sizeof(QualType), 8);
Douglas Gregor72564e72009-02-26 23:50:07 +00001538 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001539 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
1540 ExArray, NumExs, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001541 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001542 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001543 return QualType(FTP, 0);
1544}
1545
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001546/// getTypeDeclType - Return the unique reference to the type for the
1547/// specified type declaration.
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001548QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001549 assert(Decl && "Passed null for Decl param");
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001550 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1551
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001552 if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001553 return getTypedefType(Typedef);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001554 else if (isa<TemplateTypeParmDecl>(Decl)) {
1555 assert(false && "Template type parameter types are always available.");
1556 } else if (ObjCInterfaceDecl *ObjCInterface = dyn_cast<ObjCInterfaceDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001557 return getObjCInterfaceType(ObjCInterface);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001558
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001559 if (RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001560 if (PrevDecl)
1561 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001562 else
1563 Decl->TypeForDecl = new (*this,8) RecordType(Record);
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001564 }
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001565 else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
1566 if (PrevDecl)
1567 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001568 else
1569 Decl->TypeForDecl = new (*this,8) EnumType(Enum);
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001570 }
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001571 else
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001572 assert(false && "TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001573
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001574 if (!PrevDecl) Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001575 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001576}
1577
Reid Spencer5f016e22007-07-11 17:01:13 +00001578/// getTypedefType - Return the unique reference to the type for the
1579/// specified typename decl.
1580QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
1581 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1582
Chris Lattnerf52ab252008-04-06 22:59:24 +00001583 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
Douglas Gregor72564e72009-02-26 23:50:07 +00001584 Decl->TypeForDecl = new(*this,8) TypedefType(Type::Typedef, Decl, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001585 Types.push_back(Decl->TypeForDecl);
1586 return QualType(Decl->TypeForDecl, 0);
1587}
1588
Douglas Gregorfab9d672009-02-05 23:33:38 +00001589/// \brief Retrieve the template type parameter type for a template
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001590/// parameter or parameter pack with the given depth, index, and (optionally)
1591/// name.
Douglas Gregorfab9d672009-02-05 23:33:38 +00001592QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001593 bool ParameterPack,
Douglas Gregorfab9d672009-02-05 23:33:38 +00001594 IdentifierInfo *Name) {
1595 llvm::FoldingSetNodeID ID;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001596 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001597 void *InsertPos = 0;
1598 TemplateTypeParmType *TypeParm
1599 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1600
1601 if (TypeParm)
1602 return QualType(TypeParm, 0);
1603
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001604 if (Name) {
1605 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
1606 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, ParameterPack,
1607 Name, Canon);
1608 } else
1609 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001610
1611 Types.push_back(TypeParm);
1612 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1613
1614 return QualType(TypeParm, 0);
1615}
1616
Douglas Gregor55f6b142009-02-09 18:46:07 +00001617QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00001618ASTContext::getTemplateSpecializationType(TemplateName Template,
1619 const TemplateArgument *Args,
1620 unsigned NumArgs,
1621 QualType Canon) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001622 if (!Canon.isNull())
1623 Canon = getCanonicalType(Canon);
Douglas Gregorfc705b82009-02-26 22:19:44 +00001624
Douglas Gregor55f6b142009-02-09 18:46:07 +00001625 llvm::FoldingSetNodeID ID;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001626 TemplateSpecializationType::Profile(ID, Template, Args, NumArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001627
Douglas Gregor55f6b142009-02-09 18:46:07 +00001628 void *InsertPos = 0;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001629 TemplateSpecializationType *Spec
1630 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001631
1632 if (Spec)
1633 return QualType(Spec, 0);
1634
Douglas Gregor7532dc62009-03-30 22:58:21 +00001635 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00001636 sizeof(TemplateArgument) * NumArgs),
1637 8);
Douglas Gregor7532dc62009-03-30 22:58:21 +00001638 Spec = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, Canon);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001639 Types.push_back(Spec);
Douglas Gregor7532dc62009-03-30 22:58:21 +00001640 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001641
1642 return QualType(Spec, 0);
1643}
1644
Douglas Gregore4e5b052009-03-19 00:18:19 +00001645QualType
Douglas Gregorab452ba2009-03-26 23:50:42 +00001646ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
Douglas Gregore4e5b052009-03-19 00:18:19 +00001647 QualType NamedType) {
1648 llvm::FoldingSetNodeID ID;
Douglas Gregorab452ba2009-03-26 23:50:42 +00001649 QualifiedNameType::Profile(ID, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001650
1651 void *InsertPos = 0;
1652 QualifiedNameType *T
1653 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
1654 if (T)
1655 return QualType(T, 0);
1656
Douglas Gregorab452ba2009-03-26 23:50:42 +00001657 T = new (*this) QualifiedNameType(NNS, NamedType,
1658 getCanonicalType(NamedType));
Douglas Gregore4e5b052009-03-19 00:18:19 +00001659 Types.push_back(T);
1660 QualifiedNameTypes.InsertNode(T, InsertPos);
1661 return QualType(T, 0);
1662}
1663
Douglas Gregord57959a2009-03-27 23:10:48 +00001664QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1665 const IdentifierInfo *Name,
1666 QualType Canon) {
1667 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1668
1669 if (Canon.isNull()) {
1670 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1671 if (CanonNNS != NNS)
1672 Canon = getTypenameType(CanonNNS, Name);
1673 }
1674
1675 llvm::FoldingSetNodeID ID;
1676 TypenameType::Profile(ID, NNS, Name);
1677
1678 void *InsertPos = 0;
1679 TypenameType *T
1680 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1681 if (T)
1682 return QualType(T, 0);
1683
1684 T = new (*this) TypenameType(NNS, Name, Canon);
1685 Types.push_back(T);
1686 TypenameTypes.InsertNode(T, InsertPos);
1687 return QualType(T, 0);
1688}
1689
Douglas Gregor17343172009-04-01 00:28:59 +00001690QualType
1691ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1692 const TemplateSpecializationType *TemplateId,
1693 QualType Canon) {
1694 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1695
1696 if (Canon.isNull()) {
1697 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1698 QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
1699 if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
1700 const TemplateSpecializationType *CanonTemplateId
1701 = CanonType->getAsTemplateSpecializationType();
1702 assert(CanonTemplateId &&
1703 "Canonical type must also be a template specialization type");
1704 Canon = getTypenameType(CanonNNS, CanonTemplateId);
1705 }
1706 }
1707
1708 llvm::FoldingSetNodeID ID;
1709 TypenameType::Profile(ID, NNS, TemplateId);
1710
1711 void *InsertPos = 0;
1712 TypenameType *T
1713 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1714 if (T)
1715 return QualType(T, 0);
1716
1717 T = new (*this) TypenameType(NNS, TemplateId, Canon);
1718 Types.push_back(T);
1719 TypenameTypes.InsertNode(T, InsertPos);
1720 return QualType(T, 0);
1721}
1722
Chris Lattner88cb27a2008-04-07 04:56:42 +00001723/// CmpProtocolNames - Comparison predicate for sorting protocols
1724/// alphabetically.
1725static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
1726 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001727 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00001728}
1729
1730static void SortAndUniqueProtocols(ObjCProtocolDecl **&Protocols,
1731 unsigned &NumProtocols) {
1732 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
1733
1734 // Sort protocols, keyed by name.
1735 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
1736
1737 // Remove duplicates.
1738 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
1739 NumProtocols = ProtocolsEnd-Protocols;
1740}
1741
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001742/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
1743/// the given interface decl and the conforming protocol list.
Steve Naroff14108da2009-07-10 23:34:53 +00001744QualType ASTContext::getObjCObjectPointerType(QualType InterfaceT,
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001745 ObjCProtocolDecl **Protocols,
1746 unsigned NumProtocols) {
1747 // Sort the protocol list alphabetically to canonicalize it.
1748 if (NumProtocols)
1749 SortAndUniqueProtocols(Protocols, NumProtocols);
1750
1751 llvm::FoldingSetNodeID ID;
Steve Naroff14108da2009-07-10 23:34:53 +00001752 ObjCObjectPointerType::Profile(ID, InterfaceT, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001753
1754 void *InsertPos = 0;
1755 if (ObjCObjectPointerType *QT =
1756 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1757 return QualType(QT, 0);
1758
1759 // No Match;
1760 ObjCObjectPointerType *QType =
Steve Naroff14108da2009-07-10 23:34:53 +00001761 new (*this,8) ObjCObjectPointerType(InterfaceT, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001762
1763 Types.push_back(QType);
1764 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
1765 return QualType(QType, 0);
1766}
Chris Lattner88cb27a2008-04-07 04:56:42 +00001767
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001768/// getObjCInterfaceType - Return the unique reference to the type for the
1769/// specified ObjC interface decl. The list of protocols is optional.
1770QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001771 ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001772 if (NumProtocols)
1773 // Sort the protocol list alphabetically to canonicalize it.
1774 SortAndUniqueProtocols(Protocols, NumProtocols);
Chris Lattner88cb27a2008-04-07 04:56:42 +00001775
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001776 llvm::FoldingSetNodeID ID;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001777 ObjCInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001778
1779 void *InsertPos = 0;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001780 if (ObjCInterfaceType *QT =
1781 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001782 return QualType(QT, 0);
1783
1784 // No Match;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001785 ObjCInterfaceType *QType =
1786 new (*this,8) ObjCInterfaceType(const_cast<ObjCInterfaceDecl*>(Decl),
1787 Protocols, NumProtocols);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001788 Types.push_back(QType);
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001789 ObjCInterfaceTypes.InsertNode(QType, InsertPos);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001790 return QualType(QType, 0);
1791}
1792
Douglas Gregor72564e72009-02-26 23:50:07 +00001793/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
1794/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00001795/// multiple declarations that refer to "typeof(x)" all contain different
1796/// DeclRefExpr's. This doesn't effect the type checker, since it operates
1797/// on canonical type's (which are always unique).
Douglas Gregor72564e72009-02-26 23:50:07 +00001798QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00001799 TypeOfExprType *toe;
1800 if (tofExpr->isTypeDependent())
1801 toe = new (*this, 8) TypeOfExprType(tofExpr);
1802 else {
1803 QualType Canonical = getCanonicalType(tofExpr->getType());
1804 toe = new (*this,8) TypeOfExprType(tofExpr, Canonical);
1805 }
Steve Naroff9752f252007-08-01 18:02:17 +00001806 Types.push_back(toe);
1807 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00001808}
1809
Steve Naroff9752f252007-08-01 18:02:17 +00001810/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
1811/// TypeOfType AST's. The only motivation to unique these nodes would be
1812/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
1813/// an issue. This doesn't effect the type checker, since it operates
1814/// on canonical type's (which are always unique).
Steve Naroffd1861fd2007-07-31 12:34:36 +00001815QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001816 QualType Canonical = getCanonicalType(tofType);
Steve Narofff83820b2009-01-27 22:08:43 +00001817 TypeOfType *tot = new (*this,8) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00001818 Types.push_back(tot);
1819 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00001820}
1821
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00001822/// getDecltypeForExpr - Given an expr, will return the decltype for that
1823/// expression, according to the rules in C++0x [dcl.type.simple]p4
1824static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00001825 if (e->isTypeDependent())
1826 return Context.DependentTy;
1827
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00001828 // If e is an id expression or a class member access, decltype(e) is defined
1829 // as the type of the entity named by e.
1830 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
1831 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
1832 return VD->getType();
1833 }
1834 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
1835 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
1836 return FD->getType();
1837 }
1838 // If e is a function call or an invocation of an overloaded operator,
1839 // (parentheses around e are ignored), decltype(e) is defined as the
1840 // return type of that function.
1841 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
1842 return CE->getCallReturnType();
1843
1844 QualType T = e->getType();
1845
1846 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
1847 // defined as T&, otherwise decltype(e) is defined as T.
1848 if (e->isLvalue(Context) == Expr::LV_Valid)
1849 T = Context.getLValueReferenceType(T);
1850
1851 return T;
1852}
1853
Anders Carlsson395b4752009-06-24 19:06:50 +00001854/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
1855/// DecltypeType AST's. The only motivation to unique these nodes would be
1856/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
1857/// an issue. This doesn't effect the type checker, since it operates
1858/// on canonical type's (which are always unique).
1859QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00001860 DecltypeType *dt;
1861 if (e->isTypeDependent()) // FIXME: canonicalize the expression
Anders Carlsson563a03b2009-07-10 19:20:26 +00001862 dt = new (*this, 8) DecltypeType(e, DependentTy);
Douglas Gregordd0257c2009-07-08 00:03:05 +00001863 else {
1864 QualType T = getDecltypeForExpr(e, *this);
Anders Carlsson563a03b2009-07-10 19:20:26 +00001865 dt = new (*this, 8) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00001866 }
Anders Carlsson395b4752009-06-24 19:06:50 +00001867 Types.push_back(dt);
1868 return QualType(dt, 0);
1869}
1870
Reid Spencer5f016e22007-07-11 17:01:13 +00001871/// getTagDeclType - Return the unique reference to the type for the
1872/// specified TagDecl (struct/union/class/enum) decl.
1873QualType ASTContext::getTagDeclType(TagDecl *Decl) {
Ted Kremenekd778f882007-11-26 21:16:01 +00001874 assert (Decl);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001875 return getTypeDeclType(Decl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001876}
1877
1878/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
1879/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
1880/// needs to agree with the definition in <stddef.h>.
1881QualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00001882 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00001883}
1884
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00001885/// getSignedWCharType - Return the type of "signed wchar_t".
1886/// Used when in C++, as a GCC extension.
1887QualType ASTContext::getSignedWCharType() const {
1888 // FIXME: derive from "Target" ?
1889 return WCharTy;
1890}
1891
1892/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
1893/// Used when in C++, as a GCC extension.
1894QualType ASTContext::getUnsignedWCharType() const {
1895 // FIXME: derive from "Target" ?
1896 return UnsignedIntTy;
1897}
1898
Chris Lattner8b9023b2007-07-13 03:05:23 +00001899/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
1900/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
1901QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00001902 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00001903}
1904
Chris Lattnere6327742008-04-02 05:18:44 +00001905//===----------------------------------------------------------------------===//
1906// Type Operators
1907//===----------------------------------------------------------------------===//
1908
Chris Lattner77c96472008-04-06 22:41:35 +00001909/// getCanonicalType - Return the canonical (structural) type corresponding to
1910/// the specified potentially non-canonical type. The non-canonical version
1911/// of a type may have many "decorated" versions of types. Decorators can
1912/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
1913/// to be free of any of these, allowing two canonical types to be compared
1914/// for exact equality with a simple pointer comparison.
1915QualType ASTContext::getCanonicalType(QualType T) {
1916 QualType CanType = T.getTypePtr()->getCanonicalTypeInternal();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001917
1918 // If the result has type qualifiers, make sure to canonicalize them as well.
1919 unsigned TypeQuals = T.getCVRQualifiers() | CanType.getCVRQualifiers();
1920 if (TypeQuals == 0) return CanType;
1921
1922 // If the type qualifiers are on an array type, get the canonical type of the
1923 // array with the qualifiers applied to the element type.
1924 ArrayType *AT = dyn_cast<ArrayType>(CanType);
1925 if (!AT)
1926 return CanType.getQualifiedType(TypeQuals);
1927
1928 // Get the canonical version of the element with the extra qualifiers on it.
1929 // This can recursively sink qualifiers through multiple levels of arrays.
1930 QualType NewEltTy=AT->getElementType().getWithAdditionalQualifiers(TypeQuals);
1931 NewEltTy = getCanonicalType(NewEltTy);
1932
1933 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
1934 return getConstantArrayType(NewEltTy, CAT->getSize(),CAT->getSizeModifier(),
1935 CAT->getIndexTypeQualifier());
1936 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
1937 return getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
1938 IAT->getIndexTypeQualifier());
1939
Douglas Gregor898574e2008-12-05 23:32:09 +00001940 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001941 return getDependentSizedArrayType(NewEltTy,
1942 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00001943 DSAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001944 DSAT->getIndexTypeQualifier(),
1945 DSAT->getBracketsRange());
Douglas Gregor898574e2008-12-05 23:32:09 +00001946
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001947 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001948 return getVariableArrayType(NewEltTy,
1949 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001950 VAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001951 VAT->getIndexTypeQualifier(),
1952 VAT->getBracketsRange());
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001953}
1954
Douglas Gregor25a3ef72009-05-07 06:41:52 +00001955TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
1956 // If this template name refers to a template, the canonical
1957 // template name merely stores the template itself.
1958 if (TemplateDecl *Template = Name.getAsTemplateDecl())
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001959 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor25a3ef72009-05-07 06:41:52 +00001960
1961 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
1962 assert(DTN && "Non-dependent template names must refer to template decls.");
1963 return DTN->CanonicalTemplateName;
1964}
1965
Douglas Gregord57959a2009-03-27 23:10:48 +00001966NestedNameSpecifier *
1967ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
1968 if (!NNS)
1969 return 0;
1970
1971 switch (NNS->getKind()) {
1972 case NestedNameSpecifier::Identifier:
1973 // Canonicalize the prefix but keep the identifier the same.
1974 return NestedNameSpecifier::Create(*this,
1975 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
1976 NNS->getAsIdentifier());
1977
1978 case NestedNameSpecifier::Namespace:
1979 // A namespace is canonical; build a nested-name-specifier with
1980 // this namespace and no prefix.
1981 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
1982
1983 case NestedNameSpecifier::TypeSpec:
1984 case NestedNameSpecifier::TypeSpecWithTemplate: {
1985 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
1986 NestedNameSpecifier *Prefix = 0;
1987
1988 // FIXME: This isn't the right check!
1989 if (T->isDependentType())
1990 Prefix = getCanonicalNestedNameSpecifier(NNS->getPrefix());
1991
1992 return NestedNameSpecifier::Create(*this, Prefix,
1993 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
1994 T.getTypePtr());
1995 }
1996
1997 case NestedNameSpecifier::Global:
1998 // The global specifier is canonical and unique.
1999 return NNS;
2000 }
2001
2002 // Required to silence a GCC warning
2003 return 0;
2004}
2005
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002006
2007const ArrayType *ASTContext::getAsArrayType(QualType T) {
2008 // Handle the non-qualified case efficiently.
2009 if (T.getCVRQualifiers() == 0) {
2010 // Handle the common positive case fast.
2011 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2012 return AT;
2013 }
2014
2015 // Handle the common negative case fast, ignoring CVR qualifiers.
2016 QualType CType = T->getCanonicalTypeInternal();
2017
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002018 // Make sure to look through type qualifiers (like ExtQuals) for the negative
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002019 // test.
2020 if (!isa<ArrayType>(CType) &&
2021 !isa<ArrayType>(CType.getUnqualifiedType()))
2022 return 0;
2023
2024 // Apply any CVR qualifiers from the array type to the element type. This
2025 // implements C99 6.7.3p8: "If the specification of an array type includes
2026 // any type qualifiers, the element type is so qualified, not the array type."
2027
2028 // If we get here, we either have type qualifiers on the type, or we have
2029 // sugar such as a typedef in the way. If we have type qualifiers on the type
2030 // we must propagate them down into the elemeng type.
2031 unsigned CVRQuals = T.getCVRQualifiers();
2032 unsigned AddrSpace = 0;
2033 Type *Ty = T.getTypePtr();
2034
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002035 // Rip through ExtQualType's and typedefs to get to a concrete type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002036 while (1) {
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002037 if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(Ty)) {
2038 AddrSpace = EXTQT->getAddressSpace();
2039 Ty = EXTQT->getBaseType();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002040 } else {
2041 T = Ty->getDesugaredType();
2042 if (T.getTypePtr() == Ty && T.getCVRQualifiers() == 0)
2043 break;
2044 CVRQuals |= T.getCVRQualifiers();
2045 Ty = T.getTypePtr();
2046 }
2047 }
2048
2049 // If we have a simple case, just return now.
2050 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
2051 if (ATy == 0 || (AddrSpace == 0 && CVRQuals == 0))
2052 return ATy;
2053
2054 // Otherwise, we have an array and we have qualifiers on it. Push the
2055 // qualifiers into the array element type and return a new array type.
2056 // Get the canonical version of the element with the extra qualifiers on it.
2057 // This can recursively sink qualifiers through multiple levels of arrays.
2058 QualType NewEltTy = ATy->getElementType();
2059 if (AddrSpace)
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002060 NewEltTy = getAddrSpaceQualType(NewEltTy, AddrSpace);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002061 NewEltTy = NewEltTy.getWithAdditionalQualifiers(CVRQuals);
2062
2063 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2064 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2065 CAT->getSizeModifier(),
2066 CAT->getIndexTypeQualifier()));
2067 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2068 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2069 IAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002070 IAT->getIndexTypeQualifier()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002071
Douglas Gregor898574e2008-12-05 23:32:09 +00002072 if (const DependentSizedArrayType *DSAT
2073 = dyn_cast<DependentSizedArrayType>(ATy))
2074 return cast<ArrayType>(
2075 getDependentSizedArrayType(NewEltTy,
2076 DSAT->getSizeExpr(),
2077 DSAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002078 DSAT->getIndexTypeQualifier(),
2079 DSAT->getBracketsRange()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002080
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002081 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002082 return cast<ArrayType>(getVariableArrayType(NewEltTy,
2083 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002084 VAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002085 VAT->getIndexTypeQualifier(),
2086 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00002087}
2088
2089
Chris Lattnere6327742008-04-02 05:18:44 +00002090/// getArrayDecayedType - Return the properly qualified result of decaying the
2091/// specified array type to a pointer. This operation is non-trivial when
2092/// handling typedefs etc. The canonical type of "T" must be an array type,
2093/// this returns a pointer to a properly qualified element of the array.
2094///
2095/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2096QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002097 // Get the element type with 'getAsArrayType' so that we don't lose any
2098 // typedefs in the element type of the array. This also handles propagation
2099 // of type qualifiers from the array type into the element type if present
2100 // (C99 6.7.3p8).
2101 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2102 assert(PrettyArrayType && "Not an array type!");
Chris Lattnere6327742008-04-02 05:18:44 +00002103
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002104 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00002105
2106 // int x[restrict 4] -> int *restrict
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002107 return PtrTy.getQualifiedType(PrettyArrayType->getIndexTypeQualifier());
Chris Lattnere6327742008-04-02 05:18:44 +00002108}
2109
Daniel Dunbard786f6a2009-01-05 22:14:37 +00002110QualType ASTContext::getBaseElementType(const VariableArrayType *VAT) {
Anders Carlsson6183a992008-12-21 03:44:36 +00002111 QualType ElemTy = VAT->getElementType();
2112
2113 if (const VariableArrayType *VAT = getAsVariableArrayType(ElemTy))
2114 return getBaseElementType(VAT);
2115
2116 return ElemTy;
2117}
2118
Reid Spencer5f016e22007-07-11 17:01:13 +00002119/// getFloatingRank - Return a relative rank for floating point types.
2120/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00002121static FloatingRank getFloatingRank(QualType T) {
Christopher Lambebb97e92008-02-04 02:31:56 +00002122 if (const ComplexType *CT = T->getAsComplexType())
Reid Spencer5f016e22007-07-11 17:01:13 +00002123 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00002124
Daniel Dunbard786f6a2009-01-05 22:14:37 +00002125 assert(T->getAsBuiltinType() && "getFloatingRank(): not a floating type");
Christopher Lambebb97e92008-02-04 02:31:56 +00002126 switch (T->getAsBuiltinType()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00002127 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002128 case BuiltinType::Float: return FloatRank;
2129 case BuiltinType::Double: return DoubleRank;
2130 case BuiltinType::LongDouble: return LongDoubleRank;
2131 }
2132}
2133
Steve Naroff716c7302007-08-27 01:41:48 +00002134/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2135/// point or a complex type (based on typeDomain/typeSize).
2136/// 'typeDomain' is a real floating point or complex type.
2137/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00002138QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2139 QualType Domain) const {
2140 FloatingRank EltRank = getFloatingRank(Size);
2141 if (Domain->isComplexType()) {
2142 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00002143 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00002144 case FloatRank: return FloatComplexTy;
2145 case DoubleRank: return DoubleComplexTy;
2146 case LongDoubleRank: return LongDoubleComplexTy;
2147 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002148 }
Chris Lattner1361b112008-04-06 23:58:54 +00002149
2150 assert(Domain->isRealFloatingType() && "Unknown domain!");
2151 switch (EltRank) {
2152 default: assert(0 && "getFloatingRank(): illegal value for rank");
2153 case FloatRank: return FloatTy;
2154 case DoubleRank: return DoubleTy;
2155 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00002156 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002157}
2158
Chris Lattner7cfeb082008-04-06 23:55:33 +00002159/// getFloatingTypeOrder - Compare the rank of the two specified floating
2160/// point types, ignoring the domain of the type (i.e. 'double' ==
2161/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
2162/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00002163int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2164 FloatingRank LHSR = getFloatingRank(LHS);
2165 FloatingRank RHSR = getFloatingRank(RHS);
2166
2167 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002168 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00002169 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002170 return 1;
2171 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002172}
2173
Chris Lattnerf52ab252008-04-06 22:59:24 +00002174/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2175/// routine will assert if passed a built-in type that isn't an integer or enum,
2176/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00002177unsigned ASTContext::getIntegerRank(Type *T) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002178 assert(T->isCanonical() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00002179 if (EnumType* ET = dyn_cast<EnumType>(T))
2180 T = ET->getDecl()->getIntegerType().getTypePtr();
2181
Eli Friedmana3426752009-07-05 23:44:27 +00002182 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2183 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2184
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002185 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2186 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2187
2188 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2189 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2190
Eli Friedmanf98aba32009-02-13 02:31:07 +00002191 // There are two things which impact the integer rank: the width, and
2192 // the ordering of builtins. The builtin ordering is encoded in the
2193 // bottom three bits; the width is encoded in the bits above that.
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002194 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T))
Eli Friedmanf98aba32009-02-13 02:31:07 +00002195 return FWIT->getWidth() << 3;
Eli Friedmanf98aba32009-02-13 02:31:07 +00002196
Chris Lattnerf52ab252008-04-06 22:59:24 +00002197 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00002198 default: assert(0 && "getIntegerRank(): not a built-in integer");
2199 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002200 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002201 case BuiltinType::Char_S:
2202 case BuiltinType::Char_U:
2203 case BuiltinType::SChar:
2204 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002205 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002206 case BuiltinType::Short:
2207 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002208 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002209 case BuiltinType::Int:
2210 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002211 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002212 case BuiltinType::Long:
2213 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002214 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002215 case BuiltinType::LongLong:
2216 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002217 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00002218 case BuiltinType::Int128:
2219 case BuiltinType::UInt128:
2220 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00002221 }
2222}
2223
Chris Lattner7cfeb082008-04-06 23:55:33 +00002224/// getIntegerTypeOrder - Returns the highest ranked integer type:
2225/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
2226/// LHS < RHS, return -1.
2227int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002228 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2229 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00002230 if (LHSC == RHSC) return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00002231
Chris Lattnerf52ab252008-04-06 22:59:24 +00002232 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2233 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002234
Chris Lattner7cfeb082008-04-06 23:55:33 +00002235 unsigned LHSRank = getIntegerRank(LHSC);
2236 unsigned RHSRank = getIntegerRank(RHSC);
Reid Spencer5f016e22007-07-11 17:01:13 +00002237
Chris Lattner7cfeb082008-04-06 23:55:33 +00002238 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2239 if (LHSRank == RHSRank) return 0;
2240 return LHSRank > RHSRank ? 1 : -1;
2241 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002242
Chris Lattner7cfeb082008-04-06 23:55:33 +00002243 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2244 if (LHSUnsigned) {
2245 // If the unsigned [LHS] type is larger, return it.
2246 if (LHSRank >= RHSRank)
2247 return 1;
2248
2249 // If the signed type can represent all values of the unsigned type, it
2250 // wins. Because we are dealing with 2's complement and types that are
2251 // powers of two larger than each other, this is always safe.
2252 return -1;
2253 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00002254
Chris Lattner7cfeb082008-04-06 23:55:33 +00002255 // If the unsigned [RHS] type is larger, return it.
2256 if (RHSRank >= LHSRank)
2257 return -1;
2258
2259 // If the signed type can represent all values of the unsigned type, it
2260 // wins. Because we are dealing with 2's complement and types that are
2261 // powers of two larger than each other, this is always safe.
2262 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002263}
Anders Carlsson71993dd2007-08-17 05:31:46 +00002264
2265// getCFConstantStringType - Return the type used for constant CFStrings.
2266QualType ASTContext::getCFConstantStringType() {
2267 if (!CFConstantStringTypeDecl) {
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002268 CFConstantStringTypeDecl =
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002269 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002270 &Idents.get("NSConstantString"));
Anders Carlssonf06273f2007-11-19 00:25:30 +00002271 QualType FieldTypes[4];
Anders Carlsson71993dd2007-08-17 05:31:46 +00002272
2273 // const int *isa;
2274 FieldTypes[0] = getPointerType(IntTy.getQualifiedType(QualType::Const));
Anders Carlssonf06273f2007-11-19 00:25:30 +00002275 // int flags;
2276 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00002277 // const char *str;
Anders Carlssonf06273f2007-11-19 00:25:30 +00002278 FieldTypes[2] = getPointerType(CharTy.getQualifiedType(QualType::Const));
Anders Carlsson71993dd2007-08-17 05:31:46 +00002279 // long length;
Anders Carlssonf06273f2007-11-19 00:25:30 +00002280 FieldTypes[3] = LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002281
Anders Carlsson71993dd2007-08-17 05:31:46 +00002282 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002283 for (unsigned i = 0; i < 4; ++i) {
2284 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
2285 SourceLocation(), 0,
2286 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002287 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002288 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002289 }
2290
2291 CFConstantStringTypeDecl->completeDefinition(*this);
Anders Carlsson71993dd2007-08-17 05:31:46 +00002292 }
2293
2294 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00002295}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002296
Douglas Gregor319ac892009-04-23 22:29:11 +00002297void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek35366a62009-07-17 17:50:17 +00002298 const RecordType *Rec = T->getAsRecordType();
Douglas Gregor319ac892009-04-23 22:29:11 +00002299 assert(Rec && "Invalid CFConstantStringType");
2300 CFConstantStringTypeDecl = Rec->getDecl();
2301}
2302
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002303QualType ASTContext::getObjCFastEnumerationStateType()
2304{
2305 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00002306 ObjCFastEnumerationStateTypeDecl =
2307 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2308 &Idents.get("__objcFastEnumerationState"));
2309
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002310 QualType FieldTypes[] = {
2311 UnsignedLongTy,
Steve Naroffde2e22d2009-07-15 18:40:39 +00002312 getPointerType(ObjCIdTypedefType),
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002313 getPointerType(UnsignedLongTy),
2314 getConstantArrayType(UnsignedLongTy,
2315 llvm::APInt(32, 5), ArrayType::Normal, 0)
2316 };
2317
Douglas Gregor44b43212008-12-11 16:49:14 +00002318 for (size_t i = 0; i < 4; ++i) {
2319 FieldDecl *Field = FieldDecl::Create(*this,
2320 ObjCFastEnumerationStateTypeDecl,
2321 SourceLocation(), 0,
2322 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002323 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002324 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002325 }
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002326
Douglas Gregor44b43212008-12-11 16:49:14 +00002327 ObjCFastEnumerationStateTypeDecl->completeDefinition(*this);
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002328 }
2329
2330 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2331}
2332
Douglas Gregor319ac892009-04-23 22:29:11 +00002333void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenek35366a62009-07-17 17:50:17 +00002334 const RecordType *Rec = T->getAsRecordType();
Douglas Gregor319ac892009-04-23 22:29:11 +00002335 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
2336 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
2337}
2338
Anders Carlssone8c49532007-10-29 06:33:42 +00002339// This returns true if a type has been typedefed to BOOL:
2340// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00002341static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00002342 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00002343 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
2344 return II->isStr("BOOL");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002345
2346 return false;
2347}
2348
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002349/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002350/// purpose.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002351int ASTContext::getObjCEncodingTypeSize(QualType type) {
Chris Lattner98be4942008-03-05 18:54:05 +00002352 uint64_t sz = getTypeSize(type);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002353
2354 // Make all integer and enum types at least as large as an int
2355 if (sz > 0 && type->isIntegralType())
Chris Lattner98be4942008-03-05 18:54:05 +00002356 sz = std::max(sz, getTypeSize(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002357 // Treat arrays as pointers, since that's how they're passed in.
2358 else if (type->isArrayType())
Chris Lattner98be4942008-03-05 18:54:05 +00002359 sz = getTypeSize(VoidPtrTy);
2360 return sz / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002361}
2362
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002363/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002364/// declaration.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002365void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00002366 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002367 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002368 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002369 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002370 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002371 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002372 // Compute size of all parameters.
2373 // Start with computing size of a pointer in number of bytes.
2374 // FIXME: There might(should) be a better way of doing this computation!
2375 SourceLocation Loc;
Chris Lattner98be4942008-03-05 18:54:05 +00002376 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002377 // The first two arguments (self and _cmd) are pointers; account for
2378 // their size.
2379 int ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00002380 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2381 E = Decl->param_end(); PI != E; ++PI) {
2382 QualType PType = (*PI)->getType();
2383 int sz = getObjCEncodingTypeSize(PType);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002384 assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002385 ParmOffset += sz;
2386 }
2387 S += llvm::utostr(ParmOffset);
2388 S += "@0:";
2389 S += llvm::utostr(PtrSize);
2390
2391 // Argument types.
2392 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00002393 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2394 E = Decl->param_end(); PI != E; ++PI) {
2395 ParmVarDecl *PVDecl = *PI;
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00002396 QualType PType = PVDecl->getOriginalType();
2397 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00002398 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
2399 // Use array's original type only if it has known number of
2400 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00002401 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00002402 PType = PVDecl->getType();
2403 } else if (PType->isFunctionType())
2404 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002405 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002406 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00002407 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002408 getObjCEncodingForType(PType, S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002409 S += llvm::utostr(ParmOffset);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002410 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002411 }
2412}
2413
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002414/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00002415/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002416/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
2417/// NULL when getting encodings for protocol properties.
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00002418/// Property attributes are stored as a comma-delimited C string. The simple
2419/// attributes readonly and bycopy are encoded as single characters. The
2420/// parametrized attributes, getter=name, setter=name, and ivar=name, are
2421/// encoded as single characters, followed by an identifier. Property types
2422/// are also encoded as a parametrized attribute. The characters used to encode
2423/// these attributes are defined by the following enumeration:
2424/// @code
2425/// enum PropertyAttributes {
2426/// kPropertyReadOnly = 'R', // property is read-only.
2427/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
2428/// kPropertyByref = '&', // property is a reference to the value last assigned
2429/// kPropertyDynamic = 'D', // property is dynamic
2430/// kPropertyGetter = 'G', // followed by getter selector name
2431/// kPropertySetter = 'S', // followed by setter selector name
2432/// kPropertyInstanceVariable = 'V' // followed by instance variable name
2433/// kPropertyType = 't' // followed by old-style type encoding.
2434/// kPropertyWeak = 'W' // 'weak' property
2435/// kPropertyStrong = 'P' // property GC'able
2436/// kPropertyNonAtomic = 'N' // property non-atomic
2437/// };
2438/// @endcode
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002439void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
2440 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00002441 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002442 // Collect information from the property implementation decl(s).
2443 bool Dynamic = false;
2444 ObjCPropertyImplDecl *SynthesizePID = 0;
2445
2446 // FIXME: Duplicated code due to poor abstraction.
2447 if (Container) {
2448 if (const ObjCCategoryImplDecl *CID =
2449 dyn_cast<ObjCCategoryImplDecl>(Container)) {
2450 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002451 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00002452 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002453 ObjCPropertyImplDecl *PID = *i;
2454 if (PID->getPropertyDecl() == PD) {
2455 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2456 Dynamic = true;
2457 } else {
2458 SynthesizePID = PID;
2459 }
2460 }
2461 }
2462 } else {
Chris Lattner61710852008-10-05 17:34:18 +00002463 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002464 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002465 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00002466 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002467 ObjCPropertyImplDecl *PID = *i;
2468 if (PID->getPropertyDecl() == PD) {
2469 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2470 Dynamic = true;
2471 } else {
2472 SynthesizePID = PID;
2473 }
2474 }
2475 }
2476 }
2477 }
2478
2479 // FIXME: This is not very efficient.
2480 S = "T";
2481
2482 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002483 // GCC has some special rules regarding encoding of properties which
2484 // closely resembles encoding of ivars.
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002485 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002486 true /* outermost type */,
2487 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002488
2489 if (PD->isReadOnly()) {
2490 S += ",R";
2491 } else {
2492 switch (PD->getSetterKind()) {
2493 case ObjCPropertyDecl::Assign: break;
2494 case ObjCPropertyDecl::Copy: S += ",C"; break;
2495 case ObjCPropertyDecl::Retain: S += ",&"; break;
2496 }
2497 }
2498
2499 // It really isn't clear at all what this means, since properties
2500 // are "dynamic by default".
2501 if (Dynamic)
2502 S += ",D";
2503
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002504 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
2505 S += ",N";
2506
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002507 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
2508 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002509 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002510 }
2511
2512 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
2513 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002514 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002515 }
2516
2517 if (SynthesizePID) {
2518 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
2519 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00002520 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002521 }
2522
2523 // FIXME: OBJCGC: weak & strong
2524}
2525
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002526/// getLegacyIntegralTypeEncoding -
2527/// Another legacy compatibility encoding: 32-bit longs are encoded as
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002528/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002529/// 'i' or 'I' instead if encoding a struct field, or a pointer!
2530///
2531void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00002532 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002533 if (const BuiltinType *BT = PointeeTy->getAsBuiltinType()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002534 if (BT->getKind() == BuiltinType::ULong &&
2535 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002536 PointeeTy = UnsignedIntTy;
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002537 else
2538 if (BT->getKind() == BuiltinType::Long &&
2539 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002540 PointeeTy = IntTy;
2541 }
2542 }
2543}
2544
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002545void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002546 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002547 // We follow the behavior of gcc, expanding structures which are
2548 // directly pointed to, and expanding embedded structures. Note that
2549 // these rules are sufficient to prevent recursive encoding of the
2550 // same type.
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00002551 getObjCEncodingForTypeImpl(T, S, true, true, Field,
2552 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002553}
2554
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002555static void EncodeBitField(const ASTContext *Context, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002556 const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002557 const Expr *E = FD->getBitWidth();
2558 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
2559 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Eli Friedman9a901bb2009-04-26 19:19:15 +00002560 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002561 S += 'b';
2562 S += llvm::utostr(N);
2563}
2564
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002565void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
2566 bool ExpandPointedToStructures,
2567 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002568 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002569 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002570 bool EncodingProperty) {
Anders Carlssone8c49532007-10-29 06:33:42 +00002571 if (const BuiltinType *BT = T->getAsBuiltinType()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002572 if (FD && FD->isBitField())
2573 return EncodeBitField(this, S, FD);
2574 char encoding;
2575 switch (BT->getKind()) {
2576 default: assert(0 && "Unhandled builtin type kind");
2577 case BuiltinType::Void: encoding = 'v'; break;
2578 case BuiltinType::Bool: encoding = 'B'; break;
2579 case BuiltinType::Char_U:
2580 case BuiltinType::UChar: encoding = 'C'; break;
2581 case BuiltinType::UShort: encoding = 'S'; break;
2582 case BuiltinType::UInt: encoding = 'I'; break;
2583 case BuiltinType::ULong:
Fariborz Jahanian72696e12009-02-11 22:31:45 +00002584 encoding =
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002585 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
Fariborz Jahanian72696e12009-02-11 22:31:45 +00002586 break;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002587 case BuiltinType::UInt128: encoding = 'T'; break;
2588 case BuiltinType::ULongLong: encoding = 'Q'; break;
2589 case BuiltinType::Char_S:
2590 case BuiltinType::SChar: encoding = 'c'; break;
2591 case BuiltinType::Short: encoding = 's'; break;
2592 case BuiltinType::Int: encoding = 'i'; break;
2593 case BuiltinType::Long:
2594 encoding =
2595 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
2596 break;
2597 case BuiltinType::LongLong: encoding = 'q'; break;
2598 case BuiltinType::Int128: encoding = 't'; break;
2599 case BuiltinType::Float: encoding = 'f'; break;
2600 case BuiltinType::Double: encoding = 'd'; break;
2601 case BuiltinType::LongDouble: encoding = 'd'; break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002602 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002603
2604 S += encoding;
2605 return;
2606 }
2607
2608 if (const ComplexType *CT = T->getAsComplexType()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00002609 S += 'j';
2610 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
2611 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002612 return;
2613 }
2614
Ted Kremenek35366a62009-07-17 17:50:17 +00002615 if (const PointerType *PT = T->getAsPointerType()) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002616 QualType PointeeTy = PT->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002617 bool isReadOnly = false;
2618 // For historical/compatibility reasons, the read-only qualifier of the
2619 // pointee gets emitted _before_ the '^'. The read-only qualifier of
2620 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
2621 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00002622 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002623 if (OutermostType && T.isConstQualified()) {
2624 isReadOnly = true;
2625 S += 'r';
2626 }
2627 }
2628 else if (OutermostType) {
2629 QualType P = PointeeTy;
Ted Kremenek35366a62009-07-17 17:50:17 +00002630 while (P->getAsPointerType())
2631 P = P->getAsPointerType()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002632 if (P.isConstQualified()) {
2633 isReadOnly = true;
2634 S += 'r';
2635 }
2636 }
2637 if (isReadOnly) {
2638 // Another legacy compatibility encoding. Some ObjC qualifier and type
2639 // combinations need to be rearranged.
2640 // Rewrite "in const" from "nr" to "rn"
2641 const char * s = S.c_str();
2642 int len = S.length();
2643 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
2644 std::string replace = "rn";
2645 S.replace(S.end()-2, S.end(), replace);
2646 }
2647 }
Steve Naroff14108da2009-07-10 23:34:53 +00002648 if (isObjCSelType(PointeeTy)) {
Anders Carlsson8baaca52007-10-31 02:53:19 +00002649 S += ':';
2650 return;
Fariborz Jahanianc2939bc2007-10-30 17:06:23 +00002651 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002652
2653 if (PointeeTy->isCharType()) {
2654 // char pointer types should be encoded as '*' unless it is a
2655 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00002656 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002657 S += '*';
2658 return;
2659 }
Steve Naroff9533a7f2009-07-22 17:14:51 +00002660 } else if (const RecordType *RTy = PointeeTy->getAsRecordType()) {
2661 // GCC binary compat: Need to convert "struct objc_class *" to "#".
2662 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
2663 S += '#';
2664 return;
2665 }
2666 // GCC binary compat: Need to convert "struct objc_object *" to "@".
2667 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
2668 S += '@';
2669 return;
2670 }
2671 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002672 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002673 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002674 getLegacyIntegralTypeEncoding(PointeeTy);
2675
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002676 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002677 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002678 return;
2679 }
2680
2681 if (const ArrayType *AT =
2682 // Ignore type qualifiers etc.
2683 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00002684 if (isa<IncompleteArrayType>(AT)) {
2685 // Incomplete arrays are encoded as a pointer to the array element.
2686 S += '^';
2687
2688 getObjCEncodingForTypeImpl(AT->getElementType(), S,
2689 false, ExpandStructures, FD);
2690 } else {
2691 S += '[';
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002692
Anders Carlsson559a8332009-02-22 01:38:57 +00002693 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
2694 S += llvm::utostr(CAT->getSize().getZExtValue());
2695 else {
2696 //Variable length arrays are encoded as a regular array with 0 elements.
2697 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
2698 S += '0';
2699 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002700
Anders Carlsson559a8332009-02-22 01:38:57 +00002701 getObjCEncodingForTypeImpl(AT->getElementType(), S,
2702 false, ExpandStructures, FD);
2703 S += ']';
2704 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002705 return;
2706 }
2707
2708 if (T->getAsFunctionType()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00002709 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002710 return;
2711 }
2712
Ted Kremenek35366a62009-07-17 17:50:17 +00002713 if (const RecordType *RTy = T->getAsRecordType()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002714 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002715 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00002716 // Anonymous structures print as '?'
2717 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
2718 S += II->getName();
2719 } else {
2720 S += '?';
2721 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002722 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002723 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002724 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
2725 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00002726 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002727 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002728 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00002729 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002730 S += '"';
2731 }
2732
2733 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002734 if (Field->isBitField()) {
2735 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
2736 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002737 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002738 QualType qt = Field->getType();
2739 getLegacyIntegralTypeEncoding(qt);
2740 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002741 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002742 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002743 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00002744 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002745 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002746 return;
2747 }
2748
2749 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002750 if (FD && FD->isBitField())
2751 EncodeBitField(this, S, FD);
2752 else
2753 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002754 return;
2755 }
2756
2757 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00002758 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002759 return;
2760 }
2761
2762 if (T->isObjCInterfaceType()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002763 // @encode(class_name)
2764 ObjCInterfaceDecl *OI = T->getAsObjCInterfaceType()->getDecl();
2765 S += '{';
2766 const IdentifierInfo *II = OI->getIdentifier();
2767 S += II->getName();
2768 S += '=';
Chris Lattnerf1690852009-03-31 08:48:01 +00002769 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002770 CollectObjCIvars(OI, RecFields);
Chris Lattnerf1690852009-03-31 08:48:01 +00002771 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002772 if (RecFields[i]->isBitField())
2773 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2774 RecFields[i]);
2775 else
2776 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2777 FD);
2778 }
2779 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002780 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002781 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002782
2783 if (const ObjCObjectPointerType *OPT = T->getAsObjCObjectPointerType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002784 if (OPT->isObjCIdType()) {
2785 S += '@';
2786 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002787 }
2788
2789 if (OPT->isObjCClassType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002790 S += '#';
2791 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002792 }
2793
2794 if (OPT->isObjCQualifiedIdType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002795 getObjCEncodingForTypeImpl(getObjCIdType(), S,
2796 ExpandPointedToStructures,
2797 ExpandStructures, FD);
2798 if (FD || EncodingProperty) {
2799 // Note that we do extended encoding of protocol qualifer list
2800 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00002801 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00002802 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2803 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00002804 S += '<';
2805 S += (*I)->getNameAsString();
2806 S += '>';
2807 }
2808 S += '"';
2809 }
2810 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002811 }
2812
2813 QualType PointeeTy = OPT->getPointeeType();
2814 if (!EncodingProperty &&
2815 isa<TypedefType>(PointeeTy.getTypePtr())) {
2816 // Another historical/compatibility reason.
2817 // We encode the underlying type which comes out as
2818 // {...};
2819 S += '^';
2820 getObjCEncodingForTypeImpl(PointeeTy, S,
2821 false, ExpandPointedToStructures,
2822 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00002823 return;
2824 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002825
2826 S += '@';
2827 if (FD || EncodingProperty) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002828 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00002829 S += OPT->getInterfaceDecl()->getNameAsCString();
2830 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2831 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002832 S += '<';
2833 S += (*I)->getNameAsString();
2834 S += '>';
2835 }
2836 S += '"';
2837 }
2838 return;
2839 }
2840
2841 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002842}
2843
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002844void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002845 std::string& S) const {
2846 if (QT & Decl::OBJC_TQ_In)
2847 S += 'n';
2848 if (QT & Decl::OBJC_TQ_Inout)
2849 S += 'N';
2850 if (QT & Decl::OBJC_TQ_Out)
2851 S += 'o';
2852 if (QT & Decl::OBJC_TQ_Bycopy)
2853 S += 'O';
2854 if (QT & Decl::OBJC_TQ_Byref)
2855 S += 'R';
2856 if (QT & Decl::OBJC_TQ_Oneway)
2857 S += 'V';
2858}
2859
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002860void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002861 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
2862
2863 BuiltinVaListType = T;
2864}
2865
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002866void ASTContext::setObjCIdType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00002867 ObjCIdTypedefType = T;
Steve Naroff7e219e42007-10-15 14:41:52 +00002868}
2869
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002870void ASTContext::setObjCSelType(QualType T) {
Douglas Gregor319ac892009-04-23 22:29:11 +00002871 ObjCSelType = T;
2872
2873 const TypedefType *TT = T->getAsTypedefType();
2874 if (!TT)
2875 return;
2876 TypedefDecl *TD = TT->getDecl();
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002877
2878 // typedef struct objc_selector *SEL;
Ted Kremenek35366a62009-07-17 17:50:17 +00002879 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00002880 if (!ptr)
2881 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002882 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00002883 if (!rec)
2884 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002885 SelStructType = rec;
2886}
2887
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002888void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002889 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00002890}
2891
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002892void ASTContext::setObjCClassType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00002893 ObjCClassTypedefType = T;
Anders Carlsson8baaca52007-10-31 02:53:19 +00002894}
2895
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002896void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
2897 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00002898 "'NSConstantString' type already set!");
2899
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002900 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00002901}
2902
Douglas Gregor7532dc62009-03-30 22:58:21 +00002903/// \brief Retrieve the template name that represents a qualified
2904/// template name such as \c std::vector.
2905TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
2906 bool TemplateKeyword,
2907 TemplateDecl *Template) {
2908 llvm::FoldingSetNodeID ID;
2909 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
2910
2911 void *InsertPos = 0;
2912 QualifiedTemplateName *QTN =
2913 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
2914 if (!QTN) {
2915 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
2916 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
2917 }
2918
2919 return TemplateName(QTN);
2920}
2921
2922/// \brief Retrieve the template name that represents a dependent
2923/// template name such as \c MetaFun::template apply.
2924TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
2925 const IdentifierInfo *Name) {
2926 assert(NNS->isDependent() && "Nested name specifier must be dependent");
2927
2928 llvm::FoldingSetNodeID ID;
2929 DependentTemplateName::Profile(ID, NNS, Name);
2930
2931 void *InsertPos = 0;
2932 DependentTemplateName *QTN =
2933 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
2934
2935 if (QTN)
2936 return TemplateName(QTN);
2937
2938 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2939 if (CanonNNS == NNS) {
2940 QTN = new (*this,4) DependentTemplateName(NNS, Name);
2941 } else {
2942 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
2943 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
2944 }
2945
2946 DependentTemplateNames.InsertNode(QTN, InsertPos);
2947 return TemplateName(QTN);
2948}
2949
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002950/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00002951/// TargetInfo, produce the corresponding type. The unsigned @p Type
2952/// is actually a value of type @c TargetInfo::IntType.
2953QualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002954 switch (Type) {
2955 case TargetInfo::NoInt: return QualType();
2956 case TargetInfo::SignedShort: return ShortTy;
2957 case TargetInfo::UnsignedShort: return UnsignedShortTy;
2958 case TargetInfo::SignedInt: return IntTy;
2959 case TargetInfo::UnsignedInt: return UnsignedIntTy;
2960 case TargetInfo::SignedLong: return LongTy;
2961 case TargetInfo::UnsignedLong: return UnsignedLongTy;
2962 case TargetInfo::SignedLongLong: return LongLongTy;
2963 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
2964 }
2965
2966 assert(false && "Unhandled TargetInfo::IntType value");
Daniel Dunbarb3ac5432008-11-11 01:16:00 +00002967 return QualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002968}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00002969
2970//===----------------------------------------------------------------------===//
2971// Type Predicates.
2972//===----------------------------------------------------------------------===//
2973
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00002974/// isObjCNSObjectType - Return true if this is an NSObject object using
2975/// NSObject attribute on a c-style pointer type.
2976/// FIXME - Make it work directly on types.
Steve Narofff4954562009-07-16 15:41:00 +00002977/// FIXME: Move to Type.
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00002978///
2979bool ASTContext::isObjCNSObjectType(QualType Ty) const {
2980 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
2981 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00002982 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00002983 return true;
2984 }
2985 return false;
2986}
2987
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00002988/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
2989/// garbage collection attribute.
2990///
2991QualType::GCAttrTypes ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
Chris Lattnerb7d25532009-02-18 22:53:11 +00002992 QualType::GCAttrTypes GCAttrs = QualType::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00002993 if (getLangOptions().ObjC1 &&
2994 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00002995 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00002996 // Default behavious under objective-c's gc is for objective-c pointers
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00002997 // (or pointers to them) be treated as though they were declared
2998 // as __strong.
2999 if (GCAttrs == QualType::GCNone) {
Steve Narofff4954562009-07-16 15:41:00 +00003000 if (Ty->isObjCObjectPointerType())
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003001 GCAttrs = QualType::Strong;
3002 else if (Ty->isPointerType())
Ted Kremenek35366a62009-07-17 17:50:17 +00003003 return getObjCGCAttrKind(Ty->getAsPointerType()->getPointeeType());
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003004 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00003005 // Non-pointers have none gc'able attribute regardless of the attribute
3006 // set on them.
Steve Narofff4954562009-07-16 15:41:00 +00003007 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
Fariborz Jahanianc2112182009-04-11 00:00:54 +00003008 return QualType::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003009 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00003010 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003011}
3012
Chris Lattner6ac46a42008-04-07 06:51:04 +00003013//===----------------------------------------------------------------------===//
3014// Type Compatibility Testing
3015//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00003016
Chris Lattner6ac46a42008-04-07 06:51:04 +00003017/// areCompatVectorTypes - Return true if the two specified vector types are
3018/// compatible.
3019static bool areCompatVectorTypes(const VectorType *LHS,
3020 const VectorType *RHS) {
3021 assert(LHS->isCanonical() && RHS->isCanonical());
3022 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00003023 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00003024}
3025
Eli Friedman3d815e72008-08-22 00:56:42 +00003026/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00003027/// compatible for assignment from RHS to LHS. This handles validation of any
3028/// protocol qualifiers on the LHS or RHS.
3029///
Steve Naroff14108da2009-07-10 23:34:53 +00003030/// FIXME: Move the following to ObjCObjectPointerType/ObjCInterfaceType.
3031bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
3032 const ObjCObjectPointerType *RHSOPT) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003033 // If either type represents the built-in 'id' or 'Class' types, return true.
3034 if (LHSOPT->isObjCBuiltinType() || RHSOPT->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00003035 return true;
3036
3037 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
3038 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
Steve Naroffde2e22d2009-07-15 18:40:39 +00003039 if (!LHS || !RHS) {
3040 // We have qualified builtin types.
3041 // Both the right and left sides have qualifiers.
3042 for (ObjCObjectPointerType::qual_iterator I = LHSOPT->qual_begin(),
3043 E = LHSOPT->qual_end(); I != E; ++I) {
3044 bool RHSImplementsProtocol = false;
3045
3046 // when comparing an id<P> on lhs with a static type on rhs,
3047 // see if static class implements all of id's protocols, directly or
3048 // through its super class and categories.
3049 for (ObjCObjectPointerType::qual_iterator J = RHSOPT->qual_begin(),
3050 E = RHSOPT->qual_end(); J != E; ++J) {
Steve Naroff8f167562009-07-16 16:21:02 +00003051 if ((*J)->lookupProtocolNamed((*I)->getIdentifier())) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003052 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00003053 break;
3054 }
Steve Naroffde2e22d2009-07-15 18:40:39 +00003055 }
3056 if (!RHSImplementsProtocol)
3057 return false;
3058 }
3059 // The RHS implements all protocols listed on the LHS.
3060 return true;
3061 }
Steve Naroff14108da2009-07-10 23:34:53 +00003062 return canAssignObjCInterfaces(LHS, RHS);
3063}
3064
Eli Friedman3d815e72008-08-22 00:56:42 +00003065bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
3066 const ObjCInterfaceType *RHS) {
Chris Lattner6ac46a42008-04-07 06:51:04 +00003067 // Verify that the base decls are compatible: the RHS must be a subclass of
3068 // the LHS.
3069 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
3070 return false;
3071
3072 // RHS must have a superset of the protocols in the LHS. If the LHS is not
3073 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00003074 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00003075 return true;
3076
3077 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
3078 // isn't a superset.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00003079 if (RHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00003080 return true; // FIXME: should return false!
3081
Steve Naroffc15cb2a2009-07-18 15:33:26 +00003082 for (ObjCInterfaceType::qual_iterator LHSPI = LHS->qual_begin(),
3083 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003084 LHSPI != LHSPE; LHSPI++) {
3085 bool RHSImplementsProtocol = false;
3086
3087 // If the RHS doesn't implement the protocol on the left, the types
3088 // are incompatible.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00003089 for (ObjCInterfaceType::qual_iterator RHSPI = RHS->qual_begin(),
3090 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00003091 RHSPI != RHSPE; RHSPI++) {
3092 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003093 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00003094 break;
3095 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003096 }
3097 // FIXME: For better diagnostics, consider passing back the protocol name.
3098 if (!RHSImplementsProtocol)
3099 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00003100 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003101 // The RHS implements all protocols listed on the LHS.
3102 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00003103}
3104
Steve Naroff389bf462009-02-12 17:52:19 +00003105bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
3106 // get the "pointed to" types
Steve Naroff14108da2009-07-10 23:34:53 +00003107 const ObjCObjectPointerType *LHSOPT = LHS->getAsObjCObjectPointerType();
3108 const ObjCObjectPointerType *RHSOPT = RHS->getAsObjCObjectPointerType();
Steve Naroff389bf462009-02-12 17:52:19 +00003109
Steve Naroff14108da2009-07-10 23:34:53 +00003110 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00003111 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00003112
3113 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
3114 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00003115}
3116
Steve Naroffec0550f2007-10-15 20:41:53 +00003117/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
3118/// both shall have the identically qualified version of a compatible type.
3119/// C99 6.2.7p1: Two types have compatible types if their types are the
3120/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman3d815e72008-08-22 00:56:42 +00003121bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
3122 return !mergeTypes(LHS, RHS).isNull();
3123}
3124
3125QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
3126 const FunctionType *lbase = lhs->getAsFunctionType();
3127 const FunctionType *rbase = rhs->getAsFunctionType();
Douglas Gregor72564e72009-02-26 23:50:07 +00003128 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
3129 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00003130 bool allLTypes = true;
3131 bool allRTypes = true;
3132
3133 // Check return type
3134 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
3135 if (retType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00003136 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
3137 allLTypes = false;
3138 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
3139 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00003140
3141 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00003142 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
3143 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00003144 unsigned lproto_nargs = lproto->getNumArgs();
3145 unsigned rproto_nargs = rproto->getNumArgs();
3146
3147 // Compatible functions must have the same number of arguments
3148 if (lproto_nargs != rproto_nargs)
3149 return QualType();
3150
3151 // Variadic and non-variadic functions aren't compatible
3152 if (lproto->isVariadic() != rproto->isVariadic())
3153 return QualType();
3154
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003155 if (lproto->getTypeQuals() != rproto->getTypeQuals())
3156 return QualType();
3157
Eli Friedman3d815e72008-08-22 00:56:42 +00003158 // Check argument compatibility
3159 llvm::SmallVector<QualType, 10> types;
3160 for (unsigned i = 0; i < lproto_nargs; i++) {
3161 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
3162 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
3163 QualType argtype = mergeTypes(largtype, rargtype);
3164 if (argtype.isNull()) return QualType();
3165 types.push_back(argtype);
Chris Lattner61710852008-10-05 17:34:18 +00003166 if (getCanonicalType(argtype) != getCanonicalType(largtype))
3167 allLTypes = false;
3168 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
3169 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00003170 }
3171 if (allLTypes) return lhs;
3172 if (allRTypes) return rhs;
3173 return getFunctionType(retType, types.begin(), types.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003174 lproto->isVariadic(), lproto->getTypeQuals());
Eli Friedman3d815e72008-08-22 00:56:42 +00003175 }
3176
3177 if (lproto) allRTypes = false;
3178 if (rproto) allLTypes = false;
3179
Douglas Gregor72564e72009-02-26 23:50:07 +00003180 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00003181 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00003182 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00003183 if (proto->isVariadic()) return QualType();
3184 // Check that the types are compatible with the types that
3185 // would result from default argument promotions (C99 6.7.5.3p15).
3186 // The only types actually affected are promotable integer
3187 // types and floats, which would be passed as a different
3188 // type depending on whether the prototype is visible.
3189 unsigned proto_nargs = proto->getNumArgs();
3190 for (unsigned i = 0; i < proto_nargs; ++i) {
3191 QualType argTy = proto->getArgType(i);
3192 if (argTy->isPromotableIntegerType() ||
3193 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
3194 return QualType();
3195 }
3196
3197 if (allLTypes) return lhs;
3198 if (allRTypes) return rhs;
3199 return getFunctionType(retType, proto->arg_type_begin(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003200 proto->getNumArgs(), lproto->isVariadic(),
3201 lproto->getTypeQuals());
Eli Friedman3d815e72008-08-22 00:56:42 +00003202 }
3203
3204 if (allLTypes) return lhs;
3205 if (allRTypes) return rhs;
Douglas Gregor72564e72009-02-26 23:50:07 +00003206 return getFunctionNoProtoType(retType);
Eli Friedman3d815e72008-08-22 00:56:42 +00003207}
3208
3209QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
Bill Wendling43d69752007-12-03 07:33:35 +00003210 // C++ [expr]: If an expression initially has the type "reference to T", the
3211 // type is adjusted to "T" prior to any further analysis, the expression
3212 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003213 // expression is an lvalue unless the reference is an rvalue reference and
3214 // the expression is a function call (possibly inside parentheses).
Eli Friedman3d815e72008-08-22 00:56:42 +00003215 // FIXME: C++ shouldn't be going through here! The rules are different
3216 // enough that they should be handled separately.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003217 // FIXME: Merging of lvalue and rvalue references is incorrect. C++ *really*
3218 // shouldn't be going through here!
Ted Kremenek35366a62009-07-17 17:50:17 +00003219 if (const ReferenceType *RT = LHS->getAsReferenceType())
Chris Lattnerc4e40592008-04-07 04:07:56 +00003220 LHS = RT->getPointeeType();
Ted Kremenek35366a62009-07-17 17:50:17 +00003221 if (const ReferenceType *RT = RHS->getAsReferenceType())
Chris Lattnerc4e40592008-04-07 04:07:56 +00003222 RHS = RT->getPointeeType();
Chris Lattnerf3692dc2008-04-07 05:37:56 +00003223
Eli Friedman3d815e72008-08-22 00:56:42 +00003224 QualType LHSCan = getCanonicalType(LHS),
3225 RHSCan = getCanonicalType(RHS);
3226
3227 // If two types are identical, they are compatible.
3228 if (LHSCan == RHSCan)
3229 return LHS;
3230
3231 // If the qualifiers are different, the types aren't compatible
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003232 // Note that we handle extended qualifiers later, in the
3233 // case for ExtQualType.
3234 if (LHSCan.getCVRQualifiers() != RHSCan.getCVRQualifiers())
Eli Friedman3d815e72008-08-22 00:56:42 +00003235 return QualType();
3236
Eli Friedman852d63b2009-06-01 01:22:52 +00003237 Type::TypeClass LHSClass = LHSCan->getTypeClass();
3238 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00003239
Chris Lattner1adb8832008-01-14 05:45:46 +00003240 // We want to consider the two function types to be the same for these
3241 // comparisons, just force one to the other.
3242 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
3243 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00003244
Eli Friedman07d25872009-06-02 05:28:56 +00003245 // Strip off objc_gc attributes off the top level so they can be merged.
3246 // This is a complete mess, but the attribute itself doesn't make much sense.
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003247 if (RHSClass == Type::ExtQual) {
Eli Friedman07d25872009-06-02 05:28:56 +00003248 QualType::GCAttrTypes GCAttr = RHSCan.getObjCGCAttr();
3249 if (GCAttr != QualType::GCNone) {
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003250 QualType::GCAttrTypes GCLHSAttr = LHSCan.getObjCGCAttr();
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003251 // __weak attribute must appear on both declarations.
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003252 // __strong attribue is redundant if other decl is an objective-c
3253 // object pointer (or decorated with __strong attribute); otherwise
3254 // issue error.
3255 if ((GCAttr == QualType::Weak && GCLHSAttr != GCAttr) ||
3256 (GCAttr == QualType::Strong && GCLHSAttr != GCAttr &&
Steve Naroff14108da2009-07-10 23:34:53 +00003257 !LHSCan->isObjCObjectPointerType()))
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003258 return QualType();
3259
Eli Friedman07d25872009-06-02 05:28:56 +00003260 RHS = QualType(cast<ExtQualType>(RHS.getDesugaredType())->getBaseType(),
3261 RHS.getCVRQualifiers());
3262 QualType Result = mergeTypes(LHS, RHS);
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003263 if (!Result.isNull()) {
3264 if (Result.getObjCGCAttr() == QualType::GCNone)
3265 Result = getObjCGCQualType(Result, GCAttr);
3266 else if (Result.getObjCGCAttr() != GCAttr)
3267 Result = QualType();
3268 }
Eli Friedman07d25872009-06-02 05:28:56 +00003269 return Result;
3270 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003271 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003272 if (LHSClass == Type::ExtQual) {
Eli Friedman07d25872009-06-02 05:28:56 +00003273 QualType::GCAttrTypes GCAttr = LHSCan.getObjCGCAttr();
3274 if (GCAttr != QualType::GCNone) {
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003275 QualType::GCAttrTypes GCRHSAttr = RHSCan.getObjCGCAttr();
3276 // __weak attribute must appear on both declarations. __strong
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003277 // __strong attribue is redundant if other decl is an objective-c
3278 // object pointer (or decorated with __strong attribute); otherwise
3279 // issue error.
3280 if ((GCAttr == QualType::Weak && GCRHSAttr != GCAttr) ||
3281 (GCAttr == QualType::Strong && GCRHSAttr != GCAttr &&
Steve Naroff14108da2009-07-10 23:34:53 +00003282 !RHSCan->isObjCObjectPointerType()))
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003283 return QualType();
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003284
Eli Friedman07d25872009-06-02 05:28:56 +00003285 LHS = QualType(cast<ExtQualType>(LHS.getDesugaredType())->getBaseType(),
3286 LHS.getCVRQualifiers());
3287 QualType Result = mergeTypes(LHS, RHS);
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003288 if (!Result.isNull()) {
3289 if (Result.getObjCGCAttr() == QualType::GCNone)
3290 Result = getObjCGCQualType(Result, GCAttr);
3291 else if (Result.getObjCGCAttr() != GCAttr)
3292 Result = QualType();
3293 }
Eli Friedman354e53d2009-06-02 07:45:37 +00003294 return Result;
Eli Friedman07d25872009-06-02 05:28:56 +00003295 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003296 }
3297
Eli Friedman4c721d32008-02-12 08:23:06 +00003298 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00003299 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
3300 LHSClass = Type::ConstantArray;
3301 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
3302 RHSClass = Type::ConstantArray;
Steve Naroffec0550f2007-10-15 20:41:53 +00003303
Nate Begeman213541a2008-04-18 23:10:10 +00003304 // Canonicalize ExtVector -> Vector.
3305 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
3306 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Chris Lattnera36a61f2008-04-07 05:43:21 +00003307
3308 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00003309 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00003310 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
3311 // a signed integer type, or an unsigned integer type.
Eli Friedman3d815e72008-08-22 00:56:42 +00003312 if (const EnumType* ETy = LHS->getAsEnumType()) {
3313 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
3314 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00003315 }
Eli Friedman3d815e72008-08-22 00:56:42 +00003316 if (const EnumType* ETy = RHS->getAsEnumType()) {
3317 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
3318 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00003319 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003320
Eli Friedman3d815e72008-08-22 00:56:42 +00003321 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00003322 }
Eli Friedman3d815e72008-08-22 00:56:42 +00003323
Steve Naroff4a746782008-01-09 22:43:08 +00003324 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00003325 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00003326#define TYPE(Class, Base)
3327#define ABSTRACT_TYPE(Class, Base)
3328#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3329#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3330#include "clang/AST/TypeNodes.def"
3331 assert(false && "Non-canonical and dependent types shouldn't get here");
3332 return QualType();
3333
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003334 case Type::LValueReference:
3335 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00003336 case Type::MemberPointer:
3337 assert(false && "C++ should never be in mergeTypes");
3338 return QualType();
3339
3340 case Type::IncompleteArray:
3341 case Type::VariableArray:
3342 case Type::FunctionProto:
3343 case Type::ExtVector:
Douglas Gregor72564e72009-02-26 23:50:07 +00003344 assert(false && "Types are eliminated above");
3345 return QualType();
3346
Chris Lattner1adb8832008-01-14 05:45:46 +00003347 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00003348 {
3349 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek35366a62009-07-17 17:50:17 +00003350 QualType LHSPointee = LHS->getAsPointerType()->getPointeeType();
3351 QualType RHSPointee = RHS->getAsPointerType()->getPointeeType();
Eli Friedman3d815e72008-08-22 00:56:42 +00003352 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
3353 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00003354 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00003355 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00003356 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00003357 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00003358 return getPointerType(ResultType);
3359 }
Steve Naroffc0febd52008-12-10 17:49:55 +00003360 case Type::BlockPointer:
3361 {
3362 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek35366a62009-07-17 17:50:17 +00003363 QualType LHSPointee = LHS->getAsBlockPointerType()->getPointeeType();
3364 QualType RHSPointee = RHS->getAsBlockPointerType()->getPointeeType();
Steve Naroffc0febd52008-12-10 17:49:55 +00003365 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
3366 if (ResultType.isNull()) return QualType();
3367 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
3368 return LHS;
3369 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
3370 return RHS;
3371 return getBlockPointerType(ResultType);
3372 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003373 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00003374 {
3375 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
3376 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
3377 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
3378 return QualType();
3379
3380 QualType LHSElem = getAsArrayType(LHS)->getElementType();
3381 QualType RHSElem = getAsArrayType(RHS)->getElementType();
3382 QualType ResultType = mergeTypes(LHSElem, RHSElem);
3383 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00003384 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3385 return LHS;
3386 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3387 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00003388 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
3389 ArrayType::ArraySizeModifier(), 0);
3390 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
3391 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00003392 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
3393 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00003394 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3395 return LHS;
3396 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3397 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00003398 if (LVAT) {
3399 // FIXME: This isn't correct! But tricky to implement because
3400 // the array's size has to be the size of LHS, but the type
3401 // has to be different.
3402 return LHS;
3403 }
3404 if (RVAT) {
3405 // FIXME: This isn't correct! But tricky to implement because
3406 // the array's size has to be the size of RHS, but the type
3407 // has to be different.
3408 return RHS;
3409 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00003410 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
3411 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003412 return getIncompleteArrayType(ResultType,
3413 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00003414 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003415 case Type::FunctionNoProto:
Eli Friedman3d815e72008-08-22 00:56:42 +00003416 return mergeFunctionTypes(LHS, RHS);
Douglas Gregor72564e72009-02-26 23:50:07 +00003417 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00003418 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00003419 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00003420 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00003421 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00003422 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00003423 case Type::Complex:
3424 // Distinct complex types are incompatible.
3425 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00003426 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003427 // FIXME: The merged type should be an ExtVector!
Eli Friedman3d815e72008-08-22 00:56:42 +00003428 if (areCompatVectorTypes(LHS->getAsVectorType(), RHS->getAsVectorType()))
3429 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00003430 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00003431 case Type::ObjCInterface: {
Steve Naroff5fd659d2009-02-21 16:18:07 +00003432 // Check if the interfaces are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003433 // FIXME: This should be type compatibility, e.g. whether
3434 // "LHS x; RHS x;" at global scope is legal.
Steve Naroff5fd659d2009-02-21 16:18:07 +00003435 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
3436 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
3437 if (LHSIface && RHSIface &&
3438 canAssignObjCInterfaces(LHSIface, RHSIface))
3439 return LHS;
3440
Eli Friedman3d815e72008-08-22 00:56:42 +00003441 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00003442 }
Steve Naroff14108da2009-07-10 23:34:53 +00003443 case Type::ObjCObjectPointer: {
3444 // FIXME: Incorporate tests from Sema::ObjCQualifiedIdTypesAreCompatible().
3445 if (LHS->isObjCQualifiedIdType() && RHS->isObjCQualifiedIdType())
3446 return QualType();
3447
3448 if (canAssignObjCInterfaces(LHS->getAsObjCObjectPointerType(),
3449 RHS->getAsObjCObjectPointerType()))
3450 return LHS;
3451
Steve Naroffbc76dd02008-12-10 22:14:21 +00003452 return QualType();
Steve Naroff14108da2009-07-10 23:34:53 +00003453 }
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003454 case Type::FixedWidthInt:
3455 // Distinct fixed-width integers are not compatible.
3456 return QualType();
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003457 case Type::ExtQual:
3458 // FIXME: ExtQual types can be compatible even if they're not
3459 // identical!
3460 return QualType();
3461 // First attempt at an implementation, but I'm not really sure it's
3462 // right...
3463#if 0
3464 ExtQualType* LQual = cast<ExtQualType>(LHSCan);
3465 ExtQualType* RQual = cast<ExtQualType>(RHSCan);
3466 if (LQual->getAddressSpace() != RQual->getAddressSpace() ||
3467 LQual->getObjCGCAttr() != RQual->getObjCGCAttr())
3468 return QualType();
3469 QualType LHSBase, RHSBase, ResultType, ResCanUnqual;
3470 LHSBase = QualType(LQual->getBaseType(), 0);
3471 RHSBase = QualType(RQual->getBaseType(), 0);
3472 ResultType = mergeTypes(LHSBase, RHSBase);
3473 if (ResultType.isNull()) return QualType();
3474 ResCanUnqual = getCanonicalType(ResultType).getUnqualifiedType();
3475 if (LHSCan.getUnqualifiedType() == ResCanUnqual)
3476 return LHS;
3477 if (RHSCan.getUnqualifiedType() == ResCanUnqual)
3478 return RHS;
3479 ResultType = getAddrSpaceQualType(ResultType, LQual->getAddressSpace());
3480 ResultType = getObjCGCQualType(ResultType, LQual->getObjCGCAttr());
3481 ResultType.setCVRQualifiers(LHSCan.getCVRQualifiers());
3482 return ResultType;
3483#endif
Douglas Gregor7532dc62009-03-30 22:58:21 +00003484
3485 case Type::TemplateSpecialization:
3486 assert(false && "Dependent types have no size");
3487 break;
Steve Naroffec0550f2007-10-15 20:41:53 +00003488 }
Douglas Gregor72564e72009-02-26 23:50:07 +00003489
3490 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00003491}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00003492
Chris Lattner5426bf62008-04-07 07:01:58 +00003493//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00003494// Integer Predicates
3495//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00003496
Eli Friedmanad74a752008-06-28 06:23:08 +00003497unsigned ASTContext::getIntWidth(QualType T) {
3498 if (T == BoolTy)
3499 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00003500 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T)) {
3501 return FWIT->getWidth();
3502 }
3503 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00003504 return (unsigned)getTypeSize(T);
3505}
3506
3507QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
3508 assert(T->isSignedIntegerType() && "Unexpected type");
3509 if (const EnumType* ETy = T->getAsEnumType())
3510 T = ETy->getDecl()->getIntegerType();
3511 const BuiltinType* BTy = T->getAsBuiltinType();
3512 assert (BTy && "Unexpected signed integer type");
3513 switch (BTy->getKind()) {
3514 case BuiltinType::Char_S:
3515 case BuiltinType::SChar:
3516 return UnsignedCharTy;
3517 case BuiltinType::Short:
3518 return UnsignedShortTy;
3519 case BuiltinType::Int:
3520 return UnsignedIntTy;
3521 case BuiltinType::Long:
3522 return UnsignedLongTy;
3523 case BuiltinType::LongLong:
3524 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00003525 case BuiltinType::Int128:
3526 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00003527 default:
3528 assert(0 && "Unexpected signed integer type");
3529 return QualType();
3530 }
3531}
3532
Douglas Gregor2cf26342009-04-09 22:27:44 +00003533ExternalASTSource::~ExternalASTSource() { }
3534
3535void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00003536
3537
3538//===----------------------------------------------------------------------===//
3539// Builtin Type Computation
3540//===----------------------------------------------------------------------===//
3541
3542/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
3543/// pointer over the consumed characters. This returns the resultant type.
3544static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
3545 ASTContext::GetBuiltinTypeError &Error,
3546 bool AllowTypeModifiers = true) {
3547 // Modifiers.
3548 int HowLong = 0;
3549 bool Signed = false, Unsigned = false;
3550
3551 // Read the modifiers first.
3552 bool Done = false;
3553 while (!Done) {
3554 switch (*Str++) {
3555 default: Done = true; --Str; break;
3556 case 'S':
3557 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
3558 assert(!Signed && "Can't use 'S' modifier multiple times!");
3559 Signed = true;
3560 break;
3561 case 'U':
3562 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
3563 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
3564 Unsigned = true;
3565 break;
3566 case 'L':
3567 assert(HowLong <= 2 && "Can't have LLLL modifier");
3568 ++HowLong;
3569 break;
3570 }
3571 }
3572
3573 QualType Type;
3574
3575 // Read the base type.
3576 switch (*Str++) {
3577 default: assert(0 && "Unknown builtin type letter!");
3578 case 'v':
3579 assert(HowLong == 0 && !Signed && !Unsigned &&
3580 "Bad modifiers used with 'v'!");
3581 Type = Context.VoidTy;
3582 break;
3583 case 'f':
3584 assert(HowLong == 0 && !Signed && !Unsigned &&
3585 "Bad modifiers used with 'f'!");
3586 Type = Context.FloatTy;
3587 break;
3588 case 'd':
3589 assert(HowLong < 2 && !Signed && !Unsigned &&
3590 "Bad modifiers used with 'd'!");
3591 if (HowLong)
3592 Type = Context.LongDoubleTy;
3593 else
3594 Type = Context.DoubleTy;
3595 break;
3596 case 's':
3597 assert(HowLong == 0 && "Bad modifiers used with 's'!");
3598 if (Unsigned)
3599 Type = Context.UnsignedShortTy;
3600 else
3601 Type = Context.ShortTy;
3602 break;
3603 case 'i':
3604 if (HowLong == 3)
3605 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
3606 else if (HowLong == 2)
3607 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
3608 else if (HowLong == 1)
3609 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
3610 else
3611 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
3612 break;
3613 case 'c':
3614 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
3615 if (Signed)
3616 Type = Context.SignedCharTy;
3617 else if (Unsigned)
3618 Type = Context.UnsignedCharTy;
3619 else
3620 Type = Context.CharTy;
3621 break;
3622 case 'b': // boolean
3623 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
3624 Type = Context.BoolTy;
3625 break;
3626 case 'z': // size_t.
3627 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
3628 Type = Context.getSizeType();
3629 break;
3630 case 'F':
3631 Type = Context.getCFConstantStringType();
3632 break;
3633 case 'a':
3634 Type = Context.getBuiltinVaListType();
3635 assert(!Type.isNull() && "builtin va list type not initialized!");
3636 break;
3637 case 'A':
3638 // This is a "reference" to a va_list; however, what exactly
3639 // this means depends on how va_list is defined. There are two
3640 // different kinds of va_list: ones passed by value, and ones
3641 // passed by reference. An example of a by-value va_list is
3642 // x86, where va_list is a char*. An example of by-ref va_list
3643 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
3644 // we want this argument to be a char*&; for x86-64, we want
3645 // it to be a __va_list_tag*.
3646 Type = Context.getBuiltinVaListType();
3647 assert(!Type.isNull() && "builtin va list type not initialized!");
3648 if (Type->isArrayType()) {
3649 Type = Context.getArrayDecayedType(Type);
3650 } else {
3651 Type = Context.getLValueReferenceType(Type);
3652 }
3653 break;
3654 case 'V': {
3655 char *End;
3656
3657 unsigned NumElements = strtoul(Str, &End, 10);
3658 assert(End != Str && "Missing vector size");
3659
3660 Str = End;
3661
3662 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
3663 Type = Context.getVectorType(ElementType, NumElements);
3664 break;
3665 }
3666 case 'P': {
Douglas Gregorc29f77b2009-07-07 16:35:42 +00003667 Type = Context.getFILEType();
3668 if (Type.isNull()) {
Chris Lattner86df27b2009-06-14 00:45:47 +00003669 Error = ASTContext::GE_Missing_FILE;
3670 return QualType();
Douglas Gregorc29f77b2009-07-07 16:35:42 +00003671 } else {
3672 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00003673 }
3674 }
3675 }
3676
3677 if (!AllowTypeModifiers)
3678 return Type;
3679
3680 Done = false;
3681 while (!Done) {
3682 switch (*Str++) {
3683 default: Done = true; --Str; break;
3684 case '*':
3685 Type = Context.getPointerType(Type);
3686 break;
3687 case '&':
3688 Type = Context.getLValueReferenceType(Type);
3689 break;
3690 // FIXME: There's no way to have a built-in with an rvalue ref arg.
3691 case 'C':
3692 Type = Type.getQualifiedType(QualType::Const);
3693 break;
3694 }
3695 }
3696
3697 return Type;
3698}
3699
3700/// GetBuiltinType - Return the type for the specified builtin.
3701QualType ASTContext::GetBuiltinType(unsigned id,
3702 GetBuiltinTypeError &Error) {
3703 const char *TypeStr = BuiltinInfo.GetTypeString(id);
3704
3705 llvm::SmallVector<QualType, 8> ArgTypes;
3706
3707 Error = GE_None;
3708 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
3709 if (Error != GE_None)
3710 return QualType();
3711 while (TypeStr[0] && TypeStr[0] != '.') {
3712 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
3713 if (Error != GE_None)
3714 return QualType();
3715
3716 // Do array -> pointer decay. The builtin should use the decayed type.
3717 if (Ty->isArrayType())
3718 Ty = getArrayDecayedType(Ty);
3719
3720 ArgTypes.push_back(Ty);
3721 }
3722
3723 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
3724 "'.' should only occur at end of builtin type list!");
3725
3726 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
3727 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
3728 return getFunctionNoProtoType(ResType);
3729 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
3730 TypeStr[0] == '.', 0);
3731}