blob: 8a1f601603d5cee5f79a258d359b8361798b5785 [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"
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +000018#include "clang/AST/TypeLoc.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000019#include "clang/AST/Expr.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000020#include "clang/AST/ExternalASTSource.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000021#include "clang/AST/RecordLayout.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000022#include "clang/Basic/Builtins.h"
Chris Lattnera9376d42009-03-28 03:45:20 +000023#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000024#include "clang/Basic/TargetInfo.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000025#include "llvm/ADT/StringExtras.h"
Nate Begeman6fe7c8a2009-01-18 06:42:49 +000026#include "llvm/Support/MathExtras.h"
Chris Lattner557c5b12009-03-28 04:27:18 +000027#include "llvm/Support/MemoryBuffer.h"
Anders Carlsson29445a02009-07-18 21:19:52 +000028#include "RecordLayoutBuilder.h"
29
Reid Spencer5f016e22007-07-11 17:01:13 +000030using namespace clang;
31
32enum FloatingRank {
33 FloatRank, DoubleRank, LongDoubleRank
34};
35
Chris Lattner61710852008-10-05 17:34:18 +000036ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
37 TargetInfo &t,
Daniel Dunbare91593e2008-08-11 04:54:23 +000038 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +000039 Builtin::Context &builtins,
40 bool FreeMem, unsigned size_reserve) :
Douglas Gregorab452ba2009-03-26 23:50:42 +000041 GlobalNestedNameSpecifier(0), CFConstantStringTypeDecl(0),
Mike Stump782fa302009-07-28 02:25:19 +000042 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
43 sigjmp_bufDecl(0), SourceMgr(SM), LangOpts(LOpts),
Douglas Gregor2e222532009-07-02 17:08:52 +000044 LoadedExternalComments(false), FreeMemory(FreeMem), Target(t),
45 Idents(idents), Selectors(sels),
Chris Lattnere4f21422009-06-30 01:26:17 +000046 BuiltinInfo(builtins), ExternalSource(0), PrintingPolicy(LOpts) {
David Chisnall0f436562009-08-17 16:35:33 +000047 ObjCIdRedefinitionType = QualType();
48 ObjCClassRedefinitionType = QualType();
Daniel Dunbare91593e2008-08-11 04:54:23 +000049 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +000050 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff14108da2009-07-10 23:34:53 +000051 InitBuiltinTypes();
Daniel Dunbare91593e2008-08-11 04:54:23 +000052}
53
Reid Spencer5f016e22007-07-11 17:01:13 +000054ASTContext::~ASTContext() {
55 // Deallocate all the types.
56 while (!Types.empty()) {
Ted Kremenek4b05b1d2008-05-21 16:38:54 +000057 Types.back()->Destroy(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +000058 Types.pop_back();
59 }
Eli Friedmanb26153c2008-05-27 03:08:09 +000060
Nuno Lopesb74668e2008-12-17 22:30:25 +000061 {
62 llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
63 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end();
64 while (I != E) {
65 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
66 delete R;
67 }
68 }
69
70 {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +000071 llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>::iterator
72 I = ObjCLayouts.begin(), E = ObjCLayouts.end();
Nuno Lopesb74668e2008-12-17 22:30:25 +000073 while (I != E) {
74 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
75 delete R;
76 }
77 }
78
Douglas Gregorab452ba2009-03-26 23:50:42 +000079 // Destroy nested-name-specifiers.
Douglas Gregor1ae0afa2009-03-27 23:54:10 +000080 for (llvm::FoldingSet<NestedNameSpecifier>::iterator
81 NNS = NestedNameSpecifiers.begin(),
82 NNSEnd = NestedNameSpecifiers.end();
Douglas Gregore7dcd782009-03-27 23:25:45 +000083 NNS != NNSEnd;
Douglas Gregor1ae0afa2009-03-27 23:54:10 +000084 /* Increment in loop */)
85 (*NNS++).Destroy(*this);
Douglas Gregorab452ba2009-03-26 23:50:42 +000086
87 if (GlobalNestedNameSpecifier)
88 GlobalNestedNameSpecifier->Destroy(*this);
89
Eli Friedmanb26153c2008-05-27 03:08:09 +000090 TUDecl->Destroy(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +000091}
92
Douglas Gregor2cf26342009-04-09 22:27:44 +000093void
94ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
95 ExternalSource.reset(Source.take());
96}
97
Reid Spencer5f016e22007-07-11 17:01:13 +000098void ASTContext::PrintStats() const {
99 fprintf(stderr, "*** AST Context Stats:\n");
100 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000101
Douglas Gregordbe833d2009-05-26 14:40:08 +0000102 unsigned counts[] = {
103#define TYPE(Name, Parent) 0,
104#define ABSTRACT_TYPE(Name, Parent)
105#include "clang/AST/TypeNodes.def"
106 0 // Extra
107 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000108
Reid Spencer5f016e22007-07-11 17:01:13 +0000109 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
110 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000111 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000112 }
113
Douglas Gregordbe833d2009-05-26 14:40:08 +0000114 unsigned Idx = 0;
115 unsigned TotalBytes = 0;
116#define TYPE(Name, Parent) \
117 if (counts[Idx]) \
118 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
119 TotalBytes += counts[Idx] * sizeof(Name##Type); \
120 ++Idx;
121#define ABSTRACT_TYPE(Name, Parent)
122#include "clang/AST/TypeNodes.def"
123
124 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregor2cf26342009-04-09 22:27:44 +0000125
126 if (ExternalSource.get()) {
127 fprintf(stderr, "\n");
128 ExternalSource->PrintStats();
129 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000130}
131
132
133void ASTContext::InitBuiltinType(QualType &R, BuiltinType::Kind K) {
Steve Narofff83820b2009-01-27 22:08:43 +0000134 Types.push_back((R = QualType(new (*this,8) BuiltinType(K),0)).getTypePtr());
Reid Spencer5f016e22007-07-11 17:01:13 +0000135}
136
Reid Spencer5f016e22007-07-11 17:01:13 +0000137void ASTContext::InitBuiltinTypes() {
138 assert(VoidTy.isNull() && "Context reinitialized?");
139
140 // C99 6.2.5p19.
141 InitBuiltinType(VoidTy, BuiltinType::Void);
142
143 // C99 6.2.5p2.
144 InitBuiltinType(BoolTy, BuiltinType::Bool);
145 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000146 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000147 InitBuiltinType(CharTy, BuiltinType::Char_S);
148 else
149 InitBuiltinType(CharTy, BuiltinType::Char_U);
150 // C99 6.2.5p4.
151 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
152 InitBuiltinType(ShortTy, BuiltinType::Short);
153 InitBuiltinType(IntTy, BuiltinType::Int);
154 InitBuiltinType(LongTy, BuiltinType::Long);
155 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
156
157 // C99 6.2.5p6.
158 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
159 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
160 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
161 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
162 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
163
164 // C99 6.2.5p10.
165 InitBuiltinType(FloatTy, BuiltinType::Float);
166 InitBuiltinType(DoubleTy, BuiltinType::Double);
167 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000168
Chris Lattner2df9ced2009-04-30 02:43:43 +0000169 // GNU extension, 128-bit integers.
170 InitBuiltinType(Int128Ty, BuiltinType::Int128);
171 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
172
Chris Lattner3a250322009-02-26 23:43:47 +0000173 if (LangOpts.CPlusPlus) // C++ 3.9.1p5
174 InitBuiltinType(WCharTy, BuiltinType::WChar);
175 else // C99
176 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000177
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000178 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
179 InitBuiltinType(Char16Ty, BuiltinType::Char16);
180 else // C99
181 Char16Ty = getFromTargetType(Target.getChar16Type());
182
183 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
184 InitBuiltinType(Char32Ty, BuiltinType::Char32);
185 else // C99
186 Char32Ty = getFromTargetType(Target.getChar32Type());
187
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000188 // Placeholder type for functions.
Douglas Gregor898574e2008-12-05 23:32:09 +0000189 InitBuiltinType(OverloadTy, BuiltinType::Overload);
190
191 // Placeholder type for type-dependent expressions whose type is
192 // completely unknown. No code should ever check a type against
193 // DependentTy and users should never see it; however, it is here to
194 // help diagnose failures to properly check for type-dependent
195 // expressions.
196 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000197
Anders Carlssone89d1592009-06-26 18:41:36 +0000198 // Placeholder type for C++0x auto declarations whose real type has
199 // not yet been deduced.
200 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
201
Reid Spencer5f016e22007-07-11 17:01:13 +0000202 // C99 6.2.5p11.
203 FloatComplexTy = getComplexType(FloatTy);
204 DoubleComplexTy = getComplexType(DoubleTy);
205 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000206
Steve Naroff7e219e42007-10-15 14:41:52 +0000207 BuiltinVaListType = QualType();
Anders Carlsson8baaca52007-10-31 02:53:19 +0000208
Steve Naroffde2e22d2009-07-15 18:40:39 +0000209 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
210 ObjCIdTypedefType = QualType();
211 ObjCClassTypedefType = QualType();
212
213 // Builtin types for 'id' and 'Class'.
214 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
215 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Steve Naroff14108da2009-07-10 23:34:53 +0000216
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000217 ObjCConstantStringType = QualType();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000218
219 // void * type
220 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000221
222 // nullptr type (C++0x 2.14.7)
223 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000224}
225
Douglas Gregor7caa6822009-07-24 20:34:43 +0000226VarDecl *ASTContext::getInstantiatedFromStaticDataMember(VarDecl *Var) {
227 assert(Var->isStaticDataMember() && "Not a static data member");
228 llvm::DenseMap<VarDecl *, VarDecl *>::iterator Pos
229 = InstantiatedFromStaticDataMember.find(Var);
230 if (Pos == InstantiatedFromStaticDataMember.end())
231 return 0;
232
233 return Pos->second;
234}
235
236void
237ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl) {
238 assert(Inst->isStaticDataMember() && "Not a static data member");
239 assert(Tmpl->isStaticDataMember() && "Not a static data member");
240 assert(!InstantiatedFromStaticDataMember[Inst] &&
241 "Already noted what static data member was instantiated from");
242 InstantiatedFromStaticDataMember[Inst] = Tmpl;
243}
244
Douglas Gregor2e222532009-07-02 17:08:52 +0000245namespace {
246 class BeforeInTranslationUnit
247 : std::binary_function<SourceRange, SourceRange, bool> {
248 SourceManager *SourceMgr;
249
250 public:
251 explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { }
252
253 bool operator()(SourceRange X, SourceRange Y) {
254 return SourceMgr->isBeforeInTranslationUnit(X.getBegin(), Y.getBegin());
255 }
256 };
257}
258
259/// \brief Determine whether the given comment is a Doxygen-style comment.
260///
261/// \param Start the start of the comment text.
262///
263/// \param End the end of the comment text.
264///
265/// \param Member whether we want to check whether this is a member comment
266/// (which requires a < after the Doxygen-comment delimiter). Otherwise,
267/// we only return true when we find a non-member comment.
268static bool
269isDoxygenComment(SourceManager &SourceMgr, SourceRange Comment,
270 bool Member = false) {
271 const char *BufferStart
272 = SourceMgr.getBufferData(SourceMgr.getFileID(Comment.getBegin())).first;
273 const char *Start = BufferStart + SourceMgr.getFileOffset(Comment.getBegin());
274 const char* End = BufferStart + SourceMgr.getFileOffset(Comment.getEnd());
275
276 if (End - Start < 4)
277 return false;
278
279 assert(Start[0] == '/' && "Not a comment?");
280 if (Start[1] == '*' && !(Start[2] == '!' || Start[2] == '*'))
281 return false;
282 if (Start[1] == '/' && !(Start[2] == '!' || Start[2] == '/'))
283 return false;
284
285 return (Start[3] == '<') == Member;
286}
287
288/// \brief Retrieve the comment associated with the given declaration, if
289/// it has one.
290const char *ASTContext::getCommentForDecl(const Decl *D) {
291 if (!D)
292 return 0;
293
294 // Check whether we have cached a comment string for this declaration
295 // already.
296 llvm::DenseMap<const Decl *, std::string>::iterator Pos
297 = DeclComments.find(D);
298 if (Pos != DeclComments.end())
299 return Pos->second.c_str();
300
301 // If we have an external AST source and have not yet loaded comments from
302 // that source, do so now.
303 if (ExternalSource && !LoadedExternalComments) {
304 std::vector<SourceRange> LoadedComments;
305 ExternalSource->ReadComments(LoadedComments);
306
307 if (!LoadedComments.empty())
308 Comments.insert(Comments.begin(), LoadedComments.begin(),
309 LoadedComments.end());
310
311 LoadedExternalComments = true;
312 }
313
314 // If there are no comments anywhere, we won't find anything.
315 if (Comments.empty())
316 return 0;
317
318 // If the declaration doesn't map directly to a location in a file, we
319 // can't find the comment.
320 SourceLocation DeclStartLoc = D->getLocStart();
321 if (DeclStartLoc.isInvalid() || !DeclStartLoc.isFileID())
322 return 0;
323
324 // Find the comment that occurs just before this declaration.
325 std::vector<SourceRange>::iterator LastComment
326 = std::lower_bound(Comments.begin(), Comments.end(),
327 SourceRange(DeclStartLoc),
328 BeforeInTranslationUnit(&SourceMgr));
329
330 // Decompose the location for the start of the declaration and find the
331 // beginning of the file buffer.
332 std::pair<FileID, unsigned> DeclStartDecomp
333 = SourceMgr.getDecomposedLoc(DeclStartLoc);
334 const char *FileBufferStart
335 = SourceMgr.getBufferData(DeclStartDecomp.first).first;
336
337 // First check whether we have a comment for a member.
338 if (LastComment != Comments.end() &&
339 !isa<TagDecl>(D) && !isa<NamespaceDecl>(D) &&
340 isDoxygenComment(SourceMgr, *LastComment, true)) {
341 std::pair<FileID, unsigned> LastCommentEndDecomp
342 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
343 if (DeclStartDecomp.first == LastCommentEndDecomp.first &&
344 SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second)
345 == SourceMgr.getLineNumber(LastCommentEndDecomp.first,
346 LastCommentEndDecomp.second)) {
347 // The Doxygen member comment comes after the declaration starts and
348 // is on the same line and in the same file as the declaration. This
349 // is the comment we want.
350 std::string &Result = DeclComments[D];
351 Result.append(FileBufferStart +
352 SourceMgr.getFileOffset(LastComment->getBegin()),
353 FileBufferStart + LastCommentEndDecomp.second + 1);
354 return Result.c_str();
355 }
356 }
357
358 if (LastComment == Comments.begin())
359 return 0;
360 --LastComment;
361
362 // Decompose the end of the comment.
363 std::pair<FileID, unsigned> LastCommentEndDecomp
364 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
365
366 // If the comment and the declaration aren't in the same file, then they
367 // aren't related.
368 if (DeclStartDecomp.first != LastCommentEndDecomp.first)
369 return 0;
370
371 // Check that we actually have a Doxygen comment.
372 if (!isDoxygenComment(SourceMgr, *LastComment))
373 return 0;
374
375 // Compute the starting line for the declaration and for the end of the
376 // comment (this is expensive).
377 unsigned DeclStartLine
378 = SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second);
379 unsigned CommentEndLine
380 = SourceMgr.getLineNumber(LastCommentEndDecomp.first,
381 LastCommentEndDecomp.second);
382
383 // If the comment does not end on the line prior to the declaration, then
384 // the comment is not associated with the declaration at all.
385 if (CommentEndLine + 1 != DeclStartLine)
386 return 0;
387
388 // We have a comment, but there may be more comments on the previous lines.
389 // Keep looking so long as the comments are still Doxygen comments and are
390 // still adjacent.
391 unsigned ExpectedLine
392 = SourceMgr.getSpellingLineNumber(LastComment->getBegin()) - 1;
393 std::vector<SourceRange>::iterator FirstComment = LastComment;
394 while (FirstComment != Comments.begin()) {
395 // Look at the previous comment
396 --FirstComment;
397 std::pair<FileID, unsigned> Decomp
398 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
399
400 // If this previous comment is in a different file, we're done.
401 if (Decomp.first != DeclStartDecomp.first) {
402 ++FirstComment;
403 break;
404 }
405
406 // If this comment is not a Doxygen comment, we're done.
407 if (!isDoxygenComment(SourceMgr, *FirstComment)) {
408 ++FirstComment;
409 break;
410 }
411
412 // If the line number is not what we expected, we're done.
413 unsigned Line = SourceMgr.getLineNumber(Decomp.first, Decomp.second);
414 if (Line != ExpectedLine) {
415 ++FirstComment;
416 break;
417 }
418
419 // Set the next expected line number.
420 ExpectedLine
421 = SourceMgr.getSpellingLineNumber(FirstComment->getBegin()) - 1;
422 }
423
424 // The iterator range [FirstComment, LastComment] contains all of the
425 // BCPL comments that, together, are associated with this declaration.
426 // Form a single comment block string for this declaration that concatenates
427 // all of these comments.
428 std::string &Result = DeclComments[D];
429 while (FirstComment != LastComment) {
430 std::pair<FileID, unsigned> DecompStart
431 = SourceMgr.getDecomposedLoc(FirstComment->getBegin());
432 std::pair<FileID, unsigned> DecompEnd
433 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
434 Result.append(FileBufferStart + DecompStart.second,
435 FileBufferStart + DecompEnd.second + 1);
436 ++FirstComment;
437 }
438
439 // Append the last comment line.
440 Result.append(FileBufferStart +
441 SourceMgr.getFileOffset(LastComment->getBegin()),
442 FileBufferStart + LastCommentEndDecomp.second + 1);
443 return Result.c_str();
444}
445
Chris Lattner464175b2007-07-18 17:52:12 +0000446//===----------------------------------------------------------------------===//
447// Type Sizing and Analysis
448//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000449
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000450/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
451/// scalar floating point type.
452const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
453 const BuiltinType *BT = T->getAsBuiltinType();
454 assert(BT && "Not a floating point type!");
455 switch (BT->getKind()) {
456 default: assert(0 && "Not a floating point type!");
457 case BuiltinType::Float: return Target.getFloatFormat();
458 case BuiltinType::Double: return Target.getDoubleFormat();
459 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
460 }
461}
462
Chris Lattneraf707ab2009-01-24 21:53:27 +0000463/// getDeclAlign - Return a conservative estimate of the alignment of the
464/// specified decl. Note that bitfields do not have a valid alignment, so
465/// this method will assert on them.
Daniel Dunbarb7d08442009-02-17 22:16:19 +0000466unsigned ASTContext::getDeclAlignInBytes(const Decl *D) {
Eli Friedmandcdafb62009-02-22 02:56:25 +0000467 unsigned Align = Target.getCharWidth();
468
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000469 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
Eli Friedmandcdafb62009-02-22 02:56:25 +0000470 Align = std::max(Align, AA->getAlignment());
471
Chris Lattneraf707ab2009-01-24 21:53:27 +0000472 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
473 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000474 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000475 unsigned AS = RT->getPointeeType().getAddressSpace();
Anders Carlssonf0930232009-04-10 04:52:36 +0000476 Align = Target.getPointerAlign(AS);
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000477 } else if (!T->isIncompleteType() && !T->isFunctionType()) {
478 // Incomplete or function types default to 1.
Eli Friedmandcdafb62009-02-22 02:56:25 +0000479 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
480 T = cast<ArrayType>(T)->getElementType();
481
482 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
483 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000484 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000485
486 return Align / Target.getCharWidth();
Chris Lattneraf707ab2009-01-24 21:53:27 +0000487}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000488
Chris Lattnera7674d82007-07-13 22:13:22 +0000489/// getTypeSize - Return the size of the specified type, in bits. This method
490/// does not work on incomplete types.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000491std::pair<uint64_t, unsigned>
Daniel Dunbar1d751182008-11-08 05:48:37 +0000492ASTContext::getTypeInfo(const Type *T) {
Mike Stump5e301002009-02-27 18:32:39 +0000493 uint64_t Width=0;
494 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000495 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000496#define TYPE(Class, Base)
497#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000498#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000499#define DEPENDENT_TYPE(Class, Base) case Type::Class:
500#include "clang/AST/TypeNodes.def"
Douglas Gregor18857642009-04-30 17:32:17 +0000501 assert(false && "Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000502 break;
503
Chris Lattner692233e2007-07-13 22:27:08 +0000504 case Type::FunctionNoProto:
505 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000506 // GCC extension: alignof(function) = 32 bits
507 Width = 0;
508 Align = 32;
509 break;
510
Douglas Gregor72564e72009-02-26 23:50:07 +0000511 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000512 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000513 Width = 0;
514 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
515 break;
516
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +0000517 case Type::ConstantArrayWithExpr:
518 case Type::ConstantArrayWithoutExpr:
Steve Narofffb22d962007-08-30 01:06:46 +0000519 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000520 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Steve Narofffb22d962007-08-30 01:06:46 +0000521
Chris Lattner98be4942008-03-05 18:54:05 +0000522 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000523 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000524 Align = EltInfo.second;
525 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000526 }
Nate Begeman213541a2008-04-18 23:10:10 +0000527 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000528 case Type::Vector: {
529 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000530 getTypeInfo(cast<VectorType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000531 Width = EltInfo.first*cast<VectorType>(T)->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000532 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000533 // If the alignment is not a power of 2, round up to the next power of 2.
534 // This happens for non-power-of-2 length vectors.
535 // FIXME: this should probably be a target property.
536 Align = 1 << llvm::Log2_32_Ceil(Align);
Chris Lattner030d8842007-07-19 22:06:24 +0000537 break;
538 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000539
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000540 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000541 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000542 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000543 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000544 // GCC extension: alignof(void) = 8 bits.
545 Width = 0;
546 Align = 8;
547 break;
548
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000549 case BuiltinType::Bool:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000550 Width = Target.getBoolWidth();
551 Align = Target.getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000552 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000553 case BuiltinType::Char_S:
554 case BuiltinType::Char_U:
555 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000556 case BuiltinType::SChar:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000557 Width = Target.getCharWidth();
558 Align = Target.getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000559 break;
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000560 case BuiltinType::WChar:
561 Width = Target.getWCharWidth();
562 Align = Target.getWCharAlign();
563 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000564 case BuiltinType::Char16:
565 Width = Target.getChar16Width();
566 Align = Target.getChar16Align();
567 break;
568 case BuiltinType::Char32:
569 Width = Target.getChar32Width();
570 Align = Target.getChar32Align();
571 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000572 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000573 case BuiltinType::Short:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000574 Width = Target.getShortWidth();
575 Align = Target.getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000576 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000577 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000578 case BuiltinType::Int:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000579 Width = Target.getIntWidth();
580 Align = Target.getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000581 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000582 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000583 case BuiltinType::Long:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000584 Width = Target.getLongWidth();
585 Align = Target.getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000586 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000587 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000588 case BuiltinType::LongLong:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000589 Width = Target.getLongLongWidth();
590 Align = Target.getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000591 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000592 case BuiltinType::Int128:
593 case BuiltinType::UInt128:
594 Width = 128;
595 Align = 128; // int128_t is 128-bit aligned on all targets.
596 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000597 case BuiltinType::Float:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000598 Width = Target.getFloatWidth();
599 Align = Target.getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000600 break;
601 case BuiltinType::Double:
Chris Lattner5426bf62008-04-07 07:01:58 +0000602 Width = Target.getDoubleWidth();
603 Align = Target.getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000604 break;
605 case BuiltinType::LongDouble:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000606 Width = Target.getLongDoubleWidth();
607 Align = Target.getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000608 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000609 case BuiltinType::NullPtr:
610 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
611 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000612 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000613 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000614 break;
Eli Friedmanf98aba32009-02-13 02:31:07 +0000615 case Type::FixedWidthInt:
616 // FIXME: This isn't precisely correct; the width/alignment should depend
617 // on the available types for the target
618 Width = cast<FixedWidthIntType>(T)->getWidth();
Chris Lattner736166b2009-02-15 21:20:13 +0000619 Width = std::max(llvm::NextPowerOf2(Width - 1), (uint64_t)8);
Eli Friedmanf98aba32009-02-13 02:31:07 +0000620 Align = Width;
621 break;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000622 case Type::ExtQual:
Chris Lattner98be4942008-03-05 18:54:05 +0000623 // FIXME: Pointers into different addr spaces could have different sizes and
624 // alignment requirements: getPointerInfo should take an AddrSpace.
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000625 return getTypeInfo(QualType(cast<ExtQualType>(T)->getBaseType(), 0));
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000626 case Type::ObjCObjectPointer:
Chris Lattner5426bf62008-04-07 07:01:58 +0000627 Width = Target.getPointerWidth(0);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000628 Align = Target.getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000629 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000630 case Type::BlockPointer: {
631 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
632 Width = Target.getPointerWidth(AS);
633 Align = Target.getPointerAlign(AS);
634 break;
635 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000636 case Type::Pointer: {
637 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner5426bf62008-04-07 07:01:58 +0000638 Width = Target.getPointerWidth(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000639 Align = Target.getPointerAlign(AS);
640 break;
641 }
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000642 case Type::LValueReference:
643 case Type::RValueReference:
Chris Lattner7ab2ed82007-07-13 22:16:13 +0000644 // "When applied to a reference or a reference type, the result is the size
Chris Lattner5d2a6302007-07-18 18:26:58 +0000645 // of the referenced type." C++98 5.3.3p2: expr.sizeof.
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000646 // FIXME: This is wrong for struct layout: a reference in a struct has
647 // pointer size.
Chris Lattnerbdcd6372008-04-02 17:35:06 +0000648 return getTypeInfo(cast<ReferenceType>(T)->getPointeeType());
Sebastian Redlf30208a2009-01-24 21:16:55 +0000649 case Type::MemberPointer: {
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000650 // FIXME: This is ABI dependent. We use the Itanium C++ ABI.
651 // http://www.codesourcery.com/public/cxx-abi/abi.html#member-pointers
652 // If we ever want to support other ABIs this needs to be abstracted.
653
Sebastian Redlf30208a2009-01-24 21:16:55 +0000654 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000655 std::pair<uint64_t, unsigned> PtrDiffInfo =
656 getTypeInfo(getPointerDiffType());
657 Width = PtrDiffInfo.first;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000658 if (Pointee->isFunctionType())
659 Width *= 2;
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000660 Align = PtrDiffInfo.second;
661 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000662 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000663 case Type::Complex: {
664 // Complex types have the same alignment as their elements, but twice the
665 // size.
666 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000667 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000668 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000669 Align = EltInfo.second;
670 break;
671 }
Devang Patel44a3dde2008-06-04 21:54:36 +0000672 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000673 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000674 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
675 Width = Layout.getSize();
676 Align = Layout.getAlignment();
677 break;
678 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000679 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000680 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000681 const TagType *TT = cast<TagType>(T);
682
683 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner8389eab2008-08-09 21:35:13 +0000684 Width = 1;
685 Align = 1;
686 break;
687 }
688
Daniel Dunbar1d751182008-11-08 05:48:37 +0000689 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000690 return getTypeInfo(ET->getDecl()->getIntegerType());
691
Daniel Dunbar1d751182008-11-08 05:48:37 +0000692 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000693 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
694 Width = Layout.getSize();
695 Align = Layout.getAlignment();
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000696 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000697 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000698
Douglas Gregor18857642009-04-30 17:32:17 +0000699 case Type::Typedef: {
700 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000701 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
Douglas Gregor18857642009-04-30 17:32:17 +0000702 Align = Aligned->getAlignment();
703 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
704 } else
705 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregor7532dc62009-03-30 22:58:21 +0000706 break;
Chris Lattner71763312008-04-06 22:05:18 +0000707 }
Douglas Gregor18857642009-04-30 17:32:17 +0000708
709 case Type::TypeOfExpr:
710 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
711 .getTypePtr());
712
713 case Type::TypeOf:
714 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
715
Anders Carlsson395b4752009-06-24 19:06:50 +0000716 case Type::Decltype:
717 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
718 .getTypePtr());
719
Douglas Gregor18857642009-04-30 17:32:17 +0000720 case Type::QualifiedName:
721 return getTypeInfo(cast<QualifiedNameType>(T)->getNamedType().getTypePtr());
722
723 case Type::TemplateSpecialization:
724 assert(getCanonicalType(T) != T &&
725 "Cannot request the size of a dependent type");
726 // FIXME: this is likely to be wrong once we support template
727 // aliases, since a template alias could refer to a typedef that
728 // has an __aligned__ attribute on it.
729 return getTypeInfo(getCanonicalType(T));
730 }
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000731
Chris Lattner464175b2007-07-18 17:52:12 +0000732 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000733 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +0000734}
735
Chris Lattner34ebde42009-01-27 18:08:34 +0000736/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
737/// type for the current target in bits. This can be different than the ABI
738/// alignment in cases where it is beneficial for performance to overalign
739/// a data type.
740unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
741 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +0000742
743 // Double and long long should be naturally aligned if possible.
744 if (const ComplexType* CT = T->getAsComplexType())
745 T = CT->getElementType().getTypePtr();
746 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
747 T->isSpecificBuiltinType(BuiltinType::LongLong))
748 return std::max(ABIAlign, (unsigned)getTypeSize(T));
749
Chris Lattner34ebde42009-01-27 18:08:34 +0000750 return ABIAlign;
751}
752
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000753static void CollectLocalObjCIvars(ASTContext *Ctx,
754 const ObjCInterfaceDecl *OI,
755 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000756 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
757 E = OI->ivar_end(); I != E; ++I) {
Chris Lattnerf1690852009-03-31 08:48:01 +0000758 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000759 if (!IVDecl->isInvalidDecl())
760 Fields.push_back(cast<FieldDecl>(IVDecl));
761 }
762}
763
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000764void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
765 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
766 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
767 CollectObjCIvars(SuperClass, Fields);
768 CollectLocalObjCIvars(this, OI, Fields);
769}
770
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000771/// ShallowCollectObjCIvars -
772/// Collect all ivars, including those synthesized, in the current class.
773///
774void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
775 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars,
776 bool CollectSynthesized) {
777 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
778 E = OI->ivar_end(); I != E; ++I) {
779 Ivars.push_back(*I);
780 }
781 if (CollectSynthesized)
782 CollectSynthesizedIvars(OI, Ivars);
783}
784
Fariborz Jahanian98200742009-05-12 18:14:29 +0000785void ASTContext::CollectProtocolSynthesizedIvars(const ObjCProtocolDecl *PD,
786 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000787 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
788 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian98200742009-05-12 18:14:29 +0000789 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
790 Ivars.push_back(Ivar);
791
792 // Also look into nested protocols.
793 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
794 E = PD->protocol_end(); P != E; ++P)
795 CollectProtocolSynthesizedIvars(*P, Ivars);
796}
797
798/// CollectSynthesizedIvars -
799/// This routine collect synthesized ivars for the designated class.
800///
801void ASTContext::CollectSynthesizedIvars(const ObjCInterfaceDecl *OI,
802 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000803 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
804 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian98200742009-05-12 18:14:29 +0000805 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
806 Ivars.push_back(Ivar);
807 }
808 // Also look into interface's protocol list for properties declared
809 // in the protocol and whose ivars are synthesized.
810 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
811 PE = OI->protocol_end(); P != PE; ++P) {
812 ObjCProtocolDecl *PD = (*P);
813 CollectProtocolSynthesizedIvars(PD, Ivars);
814 }
815}
816
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000817unsigned ASTContext::CountProtocolSynthesizedIvars(const ObjCProtocolDecl *PD) {
818 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000819 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
820 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000821 if ((*I)->getPropertyIvarDecl())
822 ++count;
823
824 // Also look into nested protocols.
825 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
826 E = PD->protocol_end(); P != E; ++P)
827 count += CountProtocolSynthesizedIvars(*P);
828 return count;
829}
830
831unsigned ASTContext::CountSynthesizedIvars(const ObjCInterfaceDecl *OI)
832{
833 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000834 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
835 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000836 if ((*I)->getPropertyIvarDecl())
837 ++count;
838 }
839 // Also look into interface's protocol list for properties declared
840 // in the protocol and whose ivars are synthesized.
841 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
842 PE = OI->protocol_end(); P != PE; ++P) {
843 ObjCProtocolDecl *PD = (*P);
844 count += CountProtocolSynthesizedIvars(PD);
845 }
846 return count;
847}
848
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +0000849/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
850ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
851 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
852 I = ObjCImpls.find(D);
853 if (I != ObjCImpls.end())
854 return cast<ObjCImplementationDecl>(I->second);
855 return 0;
856}
857/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
858ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
859 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
860 I = ObjCImpls.find(D);
861 if (I != ObjCImpls.end())
862 return cast<ObjCCategoryImplDecl>(I->second);
863 return 0;
864}
865
866/// \brief Set the implementation of ObjCInterfaceDecl.
867void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
868 ObjCImplementationDecl *ImplD) {
869 assert(IFaceD && ImplD && "Passed null params");
870 ObjCImpls[IFaceD] = ImplD;
871}
872/// \brief Set the implementation of ObjCCategoryDecl.
873void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
874 ObjCCategoryImplDecl *ImplD) {
875 assert(CatD && ImplD && "Passed null params");
876 ObjCImpls[CatD] = ImplD;
877}
878
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +0000879/// \brief Allocate an uninitialized DeclaratorInfo.
880///
881/// The caller should initialize the memory held by DeclaratorInfo using
882/// the TypeLoc wrappers.
883///
884/// \param T the type that will be the basis for type source info. This type
885/// should refer to how the declarator was written in source code, not to
886/// what type semantic analysis resolved the declarator to.
887DeclaratorInfo *ASTContext::CreateDeclaratorInfo(QualType T) {
888 unsigned DataSize = TypeLoc::getFullDataSizeForType(T);
889 DeclaratorInfo *DInfo =
890 (DeclaratorInfo*)BumpAlloc.Allocate(sizeof(DeclaratorInfo) + DataSize, 8);
891 new (DInfo) DeclaratorInfo(T);
892 return DInfo;
893}
894
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000895/// getInterfaceLayoutImpl - Get or compute information about the
896/// layout of the given interface.
897///
898/// \param Impl - If given, also include the layout of the interface's
899/// implementation. This may differ by including synthesized ivars.
Devang Patel44a3dde2008-06-04 21:54:36 +0000900const ASTRecordLayout &
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000901ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
902 const ObjCImplementationDecl *Impl) {
Daniel Dunbar532d4da2009-05-03 13:15:50 +0000903 assert(!D->isForwardDecl() && "Invalid interface decl!");
904
Devang Patel44a3dde2008-06-04 21:54:36 +0000905 // Look up this layout, if already laid out, return what we have.
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000906 ObjCContainerDecl *Key =
907 Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
908 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
909 return *Entry;
Devang Patel44a3dde2008-06-04 21:54:36 +0000910
Daniel Dunbar453addb2009-05-03 11:16:44 +0000911 // Add in synthesized ivar count if laying out an implementation.
912 if (Impl) {
Anders Carlsson29445a02009-07-18 21:19:52 +0000913 unsigned FieldCount = D->ivar_size();
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000914 unsigned SynthCount = CountSynthesizedIvars(D);
915 FieldCount += SynthCount;
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000916 // If there aren't any sythesized ivars then reuse the interface
Daniel Dunbar453addb2009-05-03 11:16:44 +0000917 // entry. Note we can't cache this because we simply free all
918 // entries later; however we shouldn't look up implementations
919 // frequently.
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000920 if (SynthCount == 0)
Daniel Dunbar453addb2009-05-03 11:16:44 +0000921 return getObjCLayout(D, 0);
922 }
923
Anders Carlsson29445a02009-07-18 21:19:52 +0000924 const ASTRecordLayout *NewEntry =
925 ASTRecordLayoutBuilder::ComputeLayout(*this, D, Impl);
926 ObjCLayouts[Key] = NewEntry;
927
Devang Patel44a3dde2008-06-04 21:54:36 +0000928 return *NewEntry;
929}
930
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000931const ASTRecordLayout &
932ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
933 return getObjCLayout(D, 0);
934}
935
936const ASTRecordLayout &
937ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
938 return getObjCLayout(D->getClassInterface(), D);
939}
940
Devang Patel88a981b2007-11-01 19:11:01 +0000941/// getASTRecordLayout - Get or compute information about the layout of the
Chris Lattner464175b2007-07-18 17:52:12 +0000942/// specified record (struct/union/class), which indicates its size and field
943/// position information.
Chris Lattner98be4942008-03-05 18:54:05 +0000944const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +0000945 D = D->getDefinition(*this);
946 assert(D && "Cannot get layout of forward declarations!");
Eli Friedman4bd998b2008-05-30 09:31:38 +0000947
Chris Lattner464175b2007-07-18 17:52:12 +0000948 // Look up this layout, if already laid out, return what we have.
Eli Friedmanab22c432009-07-22 20:29:16 +0000949 // Note that we can't save a reference to the entry because this function
950 // is recursive.
951 const ASTRecordLayout *Entry = ASTRecordLayouts[D];
Chris Lattner464175b2007-07-18 17:52:12 +0000952 if (Entry) return *Entry;
Eli Friedman4bd998b2008-05-30 09:31:38 +0000953
Anders Carlsson29445a02009-07-18 21:19:52 +0000954 const ASTRecordLayout *NewEntry =
955 ASTRecordLayoutBuilder::ComputeLayout(*this, D);
Eli Friedmanab22c432009-07-22 20:29:16 +0000956 ASTRecordLayouts[D] = NewEntry;
Anders Carlsson29445a02009-07-18 21:19:52 +0000957
Chris Lattner5d2a6302007-07-18 18:26:58 +0000958 return *NewEntry;
Chris Lattner464175b2007-07-18 17:52:12 +0000959}
960
Chris Lattnera7674d82007-07-13 22:13:22 +0000961//===----------------------------------------------------------------------===//
962// Type creation/memoization methods
963//===----------------------------------------------------------------------===//
964
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000965QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerf52ab252008-04-06 22:59:24 +0000966 QualType CanT = getCanonicalType(T);
967 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +0000968 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +0000969
970 // If we are composing extended qualifiers together, merge together into one
971 // ExtQualType node.
972 unsigned CVRQuals = T.getCVRQualifiers();
973 QualType::GCAttrTypes GCAttr = QualType::GCNone;
974 Type *TypeNode = T.getTypePtr();
Chris Lattnerf46699c2008-02-20 20:55:12 +0000975
Chris Lattnerb7d25532009-02-18 22:53:11 +0000976 if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
977 // If this type already has an address space specified, it cannot get
978 // another one.
979 assert(EQT->getAddressSpace() == 0 &&
980 "Type cannot be in multiple addr spaces!");
981 GCAttr = EQT->getObjCGCAttr();
982 TypeNode = EQT->getBaseType();
983 }
Chris Lattnerf46699c2008-02-20 20:55:12 +0000984
Chris Lattnerb7d25532009-02-18 22:53:11 +0000985 // Check if we've already instantiated this type.
Christopher Lambebb97e92008-02-04 02:31:56 +0000986 llvm::FoldingSetNodeID ID;
Mike Stump24556362009-07-25 21:26:53 +0000987 ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
Christopher Lambebb97e92008-02-04 02:31:56 +0000988 void *InsertPos = 0;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000989 if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattnerb7d25532009-02-18 22:53:11 +0000990 return QualType(EXTQy, CVRQuals);
991
Christopher Lambebb97e92008-02-04 02:31:56 +0000992 // If the base type isn't canonical, this won't be a canonical type either,
993 // so fill in the canonical type field.
994 QualType Canonical;
Chris Lattnerb7d25532009-02-18 22:53:11 +0000995 if (!TypeNode->isCanonical()) {
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000996 Canonical = getAddrSpaceQualType(CanT, AddressSpace);
Christopher Lambebb97e92008-02-04 02:31:56 +0000997
Chris Lattnerb7d25532009-02-18 22:53:11 +0000998 // Update InsertPos, the previous call could have invalidated it.
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000999 ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001000 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Christopher Lambebb97e92008-02-04 02:31:56 +00001001 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00001002 ExtQualType *New =
1003 new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001004 ExtQualTypes.InsertNode(New, InsertPos);
Christopher Lambebb97e92008-02-04 02:31:56 +00001005 Types.push_back(New);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001006 return QualType(New, CVRQuals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001007}
1008
Chris Lattnerb7d25532009-02-18 22:53:11 +00001009QualType ASTContext::getObjCGCQualType(QualType T,
1010 QualType::GCAttrTypes GCAttr) {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001011 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001012 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001013 return T;
1014
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001015 if (T->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001016 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001017 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001018 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1019 return getPointerType(ResultType);
1020 }
1021 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00001022 // If we are composing extended qualifiers together, merge together into one
1023 // ExtQualType node.
1024 unsigned CVRQuals = T.getCVRQualifiers();
1025 Type *TypeNode = T.getTypePtr();
1026 unsigned AddressSpace = 0;
1027
1028 if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
Mike Stump24556362009-07-25 21:26:53 +00001029 // If this type already has an ObjCGC specified, it cannot get
Chris Lattnerb7d25532009-02-18 22:53:11 +00001030 // another one.
1031 assert(EQT->getObjCGCAttr() == QualType::GCNone &&
Mike Stump24556362009-07-25 21:26:53 +00001032 "Type cannot have multiple ObjCGCs!");
Chris Lattnerb7d25532009-02-18 22:53:11 +00001033 AddressSpace = EQT->getAddressSpace();
1034 TypeNode = EQT->getBaseType();
1035 }
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001036
1037 // Check if we've already instantiated an gc qual'd type of this type.
1038 llvm::FoldingSetNodeID ID;
Mike Stump24556362009-07-25 21:26:53 +00001039 ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001040 void *InsertPos = 0;
1041 if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattnerb7d25532009-02-18 22:53:11 +00001042 return QualType(EXTQy, CVRQuals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001043
1044 // If the base type isn't canonical, this won't be a canonical type either,
1045 // so fill in the canonical type field.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00001046 // FIXME: Isn't this also not canonical if the base type is a array
1047 // or pointer type? I can't find any documentation for objc_gc, though...
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001048 QualType Canonical;
1049 if (!T->isCanonical()) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00001050 Canonical = getObjCGCQualType(CanT, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001051
Chris Lattnerb7d25532009-02-18 22:53:11 +00001052 // Update InsertPos, the previous call could have invalidated it.
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001053 ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
1054 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1055 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00001056 ExtQualType *New =
1057 new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001058 ExtQualTypes.InsertNode(New, InsertPos);
1059 Types.push_back(New);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001060 return QualType(New, CVRQuals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001061}
Chris Lattnera7674d82007-07-13 22:13:22 +00001062
Mike Stump24556362009-07-25 21:26:53 +00001063QualType ASTContext::getNoReturnType(QualType T) {
Mike Stump6dcbc292009-07-25 23:24:03 +00001064 QualifierSet qs;
1065 qs.strip(T);
Mike Stump24556362009-07-25 21:26:53 +00001066 if (T->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001067 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Mike Stump24556362009-07-25 21:26:53 +00001068 QualType ResultType = getNoReturnType(Pointee);
Mike Stump6dcbc292009-07-25 23:24:03 +00001069 ResultType = getPointerType(ResultType);
1070 ResultType.setCVRQualifiers(T.getCVRQualifiers());
1071 return qs.apply(ResultType, *this);
Mike Stump24556362009-07-25 21:26:53 +00001072 }
1073 if (T->isBlockPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001074 QualType Pointee = T->getAs<BlockPointerType>()->getPointeeType();
Mike Stump24556362009-07-25 21:26:53 +00001075 QualType ResultType = getNoReturnType(Pointee);
Mike Stump6dcbc292009-07-25 23:24:03 +00001076 ResultType = getBlockPointerType(ResultType);
1077 ResultType.setCVRQualifiers(T.getCVRQualifiers());
1078 return qs.apply(ResultType, *this);
Mike Stump24556362009-07-25 21:26:53 +00001079 }
1080 if (!T->isFunctionType())
1081 assert(0 && "can't noreturn qualify non-pointer to function or block type");
1082
Mike Stumpe24aea22009-07-27 22:25:19 +00001083 if (const FunctionNoProtoType *F = T->getAsFunctionNoProtoType()) {
Mike Stump24556362009-07-25 21:26:53 +00001084 return getFunctionNoProtoType(F->getResultType(), true);
1085 }
Mike Stumpe24aea22009-07-27 22:25:19 +00001086 const FunctionProtoType *F = T->getAsFunctionProtoType();
Mike Stump24556362009-07-25 21:26:53 +00001087 return getFunctionType(F->getResultType(), F->arg_type_begin(),
1088 F->getNumArgs(), F->isVariadic(), F->getTypeQuals(),
1089 F->hasExceptionSpec(), F->hasAnyExceptionSpec(),
1090 F->getNumExceptions(), F->exception_begin(), true);
1091}
1092
Reid Spencer5f016e22007-07-11 17:01:13 +00001093/// getComplexType - Return the uniqued reference to the type for a complex
1094/// number with the specified element type.
1095QualType ASTContext::getComplexType(QualType T) {
1096 // Unique pointers, to guarantee there is only one pointer of a particular
1097 // structure.
1098 llvm::FoldingSetNodeID ID;
1099 ComplexType::Profile(ID, T);
1100
1101 void *InsertPos = 0;
1102 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1103 return QualType(CT, 0);
1104
1105 // If the pointee type isn't canonical, this won't be a canonical type either,
1106 // so fill in the canonical type field.
1107 QualType Canonical;
1108 if (!T->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001109 Canonical = getComplexType(getCanonicalType(T));
Reid Spencer5f016e22007-07-11 17:01:13 +00001110
1111 // Get the new insert position for the node we care about.
1112 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001113 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001114 }
Steve Narofff83820b2009-01-27 22:08:43 +00001115 ComplexType *New = new (*this,8) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001116 Types.push_back(New);
1117 ComplexTypes.InsertNode(New, InsertPos);
1118 return QualType(New, 0);
1119}
1120
Eli Friedmanf98aba32009-02-13 02:31:07 +00001121QualType ASTContext::getFixedWidthIntType(unsigned Width, bool Signed) {
1122 llvm::DenseMap<unsigned, FixedWidthIntType*> &Map = Signed ?
1123 SignedFixedWidthIntTypes : UnsignedFixedWidthIntTypes;
1124 FixedWidthIntType *&Entry = Map[Width];
1125 if (!Entry)
1126 Entry = new FixedWidthIntType(Width, Signed);
1127 return QualType(Entry, 0);
1128}
Reid Spencer5f016e22007-07-11 17:01:13 +00001129
1130/// getPointerType - Return the uniqued reference to the type for a pointer to
1131/// the specified type.
1132QualType ASTContext::getPointerType(QualType T) {
1133 // Unique pointers, to guarantee there is only one pointer of a particular
1134 // structure.
1135 llvm::FoldingSetNodeID ID;
1136 PointerType::Profile(ID, T);
1137
1138 void *InsertPos = 0;
1139 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1140 return QualType(PT, 0);
1141
1142 // If the pointee type isn't canonical, this won't be a canonical type either,
1143 // so fill in the canonical type field.
1144 QualType Canonical;
1145 if (!T->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001146 Canonical = getPointerType(getCanonicalType(T));
Reid Spencer5f016e22007-07-11 17:01:13 +00001147
1148 // Get the new insert position for the node we care about.
1149 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001150 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001151 }
Steve Narofff83820b2009-01-27 22:08:43 +00001152 PointerType *New = new (*this,8) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001153 Types.push_back(New);
1154 PointerTypes.InsertNode(New, InsertPos);
1155 return QualType(New, 0);
1156}
1157
Steve Naroff5618bd42008-08-27 16:04:49 +00001158/// getBlockPointerType - Return the uniqued reference to the type for
1159/// a pointer to the specified block.
1160QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff296e8d52008-08-28 19:20:44 +00001161 assert(T->isFunctionType() && "block of function types only");
1162 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001163 // structure.
1164 llvm::FoldingSetNodeID ID;
1165 BlockPointerType::Profile(ID, T);
1166
1167 void *InsertPos = 0;
1168 if (BlockPointerType *PT =
1169 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1170 return QualType(PT, 0);
1171
Steve Naroff296e8d52008-08-28 19:20:44 +00001172 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001173 // type either so fill in the canonical type field.
1174 QualType Canonical;
1175 if (!T->isCanonical()) {
1176 Canonical = getBlockPointerType(getCanonicalType(T));
1177
1178 // Get the new insert position for the node we care about.
1179 BlockPointerType *NewIP =
1180 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001181 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001182 }
Steve Narofff83820b2009-01-27 22:08:43 +00001183 BlockPointerType *New = new (*this,8) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001184 Types.push_back(New);
1185 BlockPointerTypes.InsertNode(New, InsertPos);
1186 return QualType(New, 0);
1187}
1188
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001189/// getLValueReferenceType - Return the uniqued reference to the type for an
1190/// lvalue reference to the specified type.
1191QualType ASTContext::getLValueReferenceType(QualType T) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001192 // Unique pointers, to guarantee there is only one pointer of a particular
1193 // structure.
1194 llvm::FoldingSetNodeID ID;
1195 ReferenceType::Profile(ID, T);
1196
1197 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001198 if (LValueReferenceType *RT =
1199 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001200 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001201
Reid Spencer5f016e22007-07-11 17:01:13 +00001202 // If the referencee type isn't canonical, this won't be a canonical type
1203 // either, so fill in the canonical type field.
1204 QualType Canonical;
1205 if (!T->isCanonical()) {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001206 Canonical = getLValueReferenceType(getCanonicalType(T));
1207
Reid Spencer5f016e22007-07-11 17:01:13 +00001208 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001209 LValueReferenceType *NewIP =
1210 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001211 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001212 }
1213
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001214 LValueReferenceType *New = new (*this,8) LValueReferenceType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001215 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001216 LValueReferenceTypes.InsertNode(New, InsertPos);
1217 return QualType(New, 0);
1218}
1219
1220/// getRValueReferenceType - Return the uniqued reference to the type for an
1221/// rvalue reference to the specified type.
1222QualType ASTContext::getRValueReferenceType(QualType T) {
1223 // Unique pointers, to guarantee there is only one pointer of a particular
1224 // structure.
1225 llvm::FoldingSetNodeID ID;
1226 ReferenceType::Profile(ID, T);
1227
1228 void *InsertPos = 0;
1229 if (RValueReferenceType *RT =
1230 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1231 return QualType(RT, 0);
1232
1233 // If the referencee type isn't canonical, this won't be a canonical type
1234 // either, so fill in the canonical type field.
1235 QualType Canonical;
1236 if (!T->isCanonical()) {
1237 Canonical = getRValueReferenceType(getCanonicalType(T));
1238
1239 // Get the new insert position for the node we care about.
1240 RValueReferenceType *NewIP =
1241 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1242 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1243 }
1244
1245 RValueReferenceType *New = new (*this,8) RValueReferenceType(T, Canonical);
1246 Types.push_back(New);
1247 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001248 return QualType(New, 0);
1249}
1250
Sebastian Redlf30208a2009-01-24 21:16:55 +00001251/// getMemberPointerType - Return the uniqued reference to the type for a
1252/// member pointer to the specified type, in the specified class.
1253QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls)
1254{
1255 // Unique pointers, to guarantee there is only one pointer of a particular
1256 // structure.
1257 llvm::FoldingSetNodeID ID;
1258 MemberPointerType::Profile(ID, T, Cls);
1259
1260 void *InsertPos = 0;
1261 if (MemberPointerType *PT =
1262 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1263 return QualType(PT, 0);
1264
1265 // If the pointee or class type isn't canonical, this won't be a canonical
1266 // type either, so fill in the canonical type field.
1267 QualType Canonical;
1268 if (!T->isCanonical()) {
1269 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1270
1271 // Get the new insert position for the node we care about.
1272 MemberPointerType *NewIP =
1273 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1274 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1275 }
Steve Narofff83820b2009-01-27 22:08:43 +00001276 MemberPointerType *New = new (*this,8) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001277 Types.push_back(New);
1278 MemberPointerTypes.InsertNode(New, InsertPos);
1279 return QualType(New, 0);
1280}
1281
Steve Narofffb22d962007-08-30 01:06:46 +00001282/// getConstantArrayType - Return the unique reference to the type for an
1283/// array of the specified element type.
1284QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001285 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001286 ArrayType::ArraySizeModifier ASM,
1287 unsigned EltTypeQuals) {
Eli Friedman587cbdf2009-05-29 20:17:55 +00001288 assert((EltTy->isDependentType() || EltTy->isConstantSizeType()) &&
1289 "Constant array of VLAs is illegal!");
1290
Chris Lattner38aeec72009-05-13 04:12:56 +00001291 // Convert the array size into a canonical width matching the pointer size for
1292 // the target.
1293 llvm::APInt ArySize(ArySizeIn);
1294 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1295
Reid Spencer5f016e22007-07-11 17:01:13 +00001296 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001297 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001298
1299 void *InsertPos = 0;
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001300 if (ConstantArrayType *ATP =
1301 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001302 return QualType(ATP, 0);
1303
1304 // If the element type isn't canonical, this won't be a canonical type either,
1305 // so fill in the canonical type field.
1306 QualType Canonical;
1307 if (!EltTy->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001308 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroffc9406122007-08-30 18:10:14 +00001309 ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001310 // Get the new insert position for the node we care about.
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001311 ConstantArrayType *NewIP =
1312 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001313 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001314 }
1315
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001316 ConstantArrayType *New =
Steve Narofff83820b2009-01-27 22:08:43 +00001317 new(*this,8)ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001318 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001319 Types.push_back(New);
1320 return QualType(New, 0);
1321}
1322
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001323/// getConstantArrayWithExprType - Return a reference to the type for
1324/// an array of the specified element type.
1325QualType
1326ASTContext::getConstantArrayWithExprType(QualType EltTy,
1327 const llvm::APInt &ArySizeIn,
1328 Expr *ArySizeExpr,
1329 ArrayType::ArraySizeModifier ASM,
1330 unsigned EltTypeQuals,
1331 SourceRange Brackets) {
1332 // Convert the array size into a canonical width matching the pointer
1333 // size for the target.
1334 llvm::APInt ArySize(ArySizeIn);
1335 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1336
1337 // Compute the canonical ConstantArrayType.
1338 QualType Canonical = getConstantArrayType(getCanonicalType(EltTy),
1339 ArySize, ASM, EltTypeQuals);
1340 // Since we don't unique expressions, it isn't possible to unique VLA's
1341 // that have an expression provided for their size.
1342 ConstantArrayWithExprType *New =
1343 new(*this,8)ConstantArrayWithExprType(EltTy, Canonical,
1344 ArySize, ArySizeExpr,
1345 ASM, EltTypeQuals, Brackets);
1346 Types.push_back(New);
1347 return QualType(New, 0);
1348}
1349
1350/// getConstantArrayWithoutExprType - Return a reference to the type for
1351/// an array of the specified element type.
1352QualType
1353ASTContext::getConstantArrayWithoutExprType(QualType EltTy,
1354 const llvm::APInt &ArySizeIn,
1355 ArrayType::ArraySizeModifier ASM,
1356 unsigned EltTypeQuals) {
1357 // Convert the array size into a canonical width matching the pointer
1358 // size for the target.
1359 llvm::APInt ArySize(ArySizeIn);
1360 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1361
1362 // Compute the canonical ConstantArrayType.
1363 QualType Canonical = getConstantArrayType(getCanonicalType(EltTy),
1364 ArySize, ASM, EltTypeQuals);
1365 ConstantArrayWithoutExprType *New =
1366 new(*this,8)ConstantArrayWithoutExprType(EltTy, Canonical,
1367 ArySize, ASM, EltTypeQuals);
1368 Types.push_back(New);
1369 return QualType(New, 0);
1370}
1371
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001372/// getVariableArrayType - Returns a non-unique reference to the type for a
1373/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001374QualType ASTContext::getVariableArrayType(QualType EltTy,
1375 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001376 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001377 unsigned EltTypeQuals,
1378 SourceRange Brackets) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001379 // Since we don't unique expressions, it isn't possible to unique VLA's
1380 // that have an expression provided for their size.
1381
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001382 VariableArrayType *New =
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001383 new(*this,8)VariableArrayType(EltTy, QualType(),
1384 NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001385
1386 VariableArrayTypes.push_back(New);
1387 Types.push_back(New);
1388 return QualType(New, 0);
1389}
1390
Douglas Gregor898574e2008-12-05 23:32:09 +00001391/// getDependentSizedArrayType - Returns a non-unique reference to
1392/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001393/// type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001394QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1395 Expr *NumElts,
Douglas Gregor898574e2008-12-05 23:32:09 +00001396 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001397 unsigned EltTypeQuals,
1398 SourceRange Brackets) {
Douglas Gregor898574e2008-12-05 23:32:09 +00001399 assert((NumElts->isTypeDependent() || NumElts->isValueDependent()) &&
1400 "Size must be type- or value-dependent!");
1401
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001402 llvm::FoldingSetNodeID ID;
1403 DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
1404 EltTypeQuals, NumElts);
Douglas Gregor898574e2008-12-05 23:32:09 +00001405
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001406 void *InsertPos = 0;
1407 DependentSizedArrayType *Canon
1408 = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1409 DependentSizedArrayType *New;
1410 if (Canon) {
1411 // We already have a canonical version of this array type; use it as
1412 // the canonical type for a newly-built type.
1413 New = new (*this,8) DependentSizedArrayType(*this, EltTy,
1414 QualType(Canon, 0),
1415 NumElts, ASM, EltTypeQuals,
1416 Brackets);
1417 } else {
1418 QualType CanonEltTy = getCanonicalType(EltTy);
1419 if (CanonEltTy == EltTy) {
1420 New = new (*this,8) DependentSizedArrayType(*this, EltTy, QualType(),
1421 NumElts, ASM, EltTypeQuals,
1422 Brackets);
1423 DependentSizedArrayTypes.InsertNode(New, InsertPos);
1424 } else {
1425 QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1426 ASM, EltTypeQuals,
1427 SourceRange());
1428 New = new (*this,8) DependentSizedArrayType(*this, EltTy, Canon,
1429 NumElts, ASM, EltTypeQuals,
1430 Brackets);
1431 }
1432 }
1433
Douglas Gregor898574e2008-12-05 23:32:09 +00001434 Types.push_back(New);
1435 return QualType(New, 0);
1436}
1437
Eli Friedmanc5773c42008-02-15 18:16:39 +00001438QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1439 ArrayType::ArraySizeModifier ASM,
1440 unsigned EltTypeQuals) {
1441 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001442 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001443
1444 void *InsertPos = 0;
1445 if (IncompleteArrayType *ATP =
1446 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1447 return QualType(ATP, 0);
1448
1449 // If the element type isn't canonical, this won't be a canonical type
1450 // either, so fill in the canonical type field.
1451 QualType Canonical;
1452
1453 if (!EltTy->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001454 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001455 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001456
1457 // Get the new insert position for the node we care about.
1458 IncompleteArrayType *NewIP =
1459 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001460 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001461 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001462
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001463 IncompleteArrayType *New
1464 = new (*this,8) IncompleteArrayType(EltTy, Canonical,
1465 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001466
1467 IncompleteArrayTypes.InsertNode(New, InsertPos);
1468 Types.push_back(New);
1469 return QualType(New, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001470}
1471
Steve Naroff73322922007-07-18 18:00:27 +00001472/// getVectorType - Return the unique reference to a vector type of
1473/// the specified element type and size. VectorType must be a built-in type.
1474QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001475 BuiltinType *baseType;
1476
Chris Lattnerf52ab252008-04-06 22:59:24 +00001477 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff73322922007-07-18 18:00:27 +00001478 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Reid Spencer5f016e22007-07-11 17:01:13 +00001479
1480 // Check if we've already instantiated a vector of this type.
1481 llvm::FoldingSetNodeID ID;
Steve Naroff73322922007-07-18 18:00:27 +00001482 VectorType::Profile(ID, vecType, NumElts, Type::Vector);
Reid Spencer5f016e22007-07-11 17:01:13 +00001483 void *InsertPos = 0;
1484 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1485 return QualType(VTP, 0);
1486
1487 // If the element type isn't canonical, this won't be a canonical type either,
1488 // so fill in the canonical type field.
1489 QualType Canonical;
1490 if (!vecType->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001491 Canonical = getVectorType(getCanonicalType(vecType), NumElts);
Reid Spencer5f016e22007-07-11 17:01:13 +00001492
1493 // Get the new insert position for the node we care about.
1494 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001495 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001496 }
Steve Narofff83820b2009-01-27 22:08:43 +00001497 VectorType *New = new (*this,8) VectorType(vecType, NumElts, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001498 VectorTypes.InsertNode(New, InsertPos);
1499 Types.push_back(New);
1500 return QualType(New, 0);
1501}
1502
Nate Begeman213541a2008-04-18 23:10:10 +00001503/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001504/// the specified element type and size. VectorType must be a built-in type.
Nate Begeman213541a2008-04-18 23:10:10 +00001505QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff73322922007-07-18 18:00:27 +00001506 BuiltinType *baseType;
1507
Chris Lattnerf52ab252008-04-06 22:59:24 +00001508 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begeman213541a2008-04-18 23:10:10 +00001509 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Steve Naroff73322922007-07-18 18:00:27 +00001510
1511 // Check if we've already instantiated a vector of this type.
1512 llvm::FoldingSetNodeID ID;
Nate Begeman213541a2008-04-18 23:10:10 +00001513 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector);
Steve Naroff73322922007-07-18 18:00:27 +00001514 void *InsertPos = 0;
1515 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1516 return QualType(VTP, 0);
1517
1518 // If the element type isn't canonical, this won't be a canonical type either,
1519 // so fill in the canonical type field.
1520 QualType Canonical;
1521 if (!vecType->isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001522 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Steve Naroff73322922007-07-18 18:00:27 +00001523
1524 // Get the new insert position for the node we care about.
1525 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001526 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001527 }
Steve Narofff83820b2009-01-27 22:08:43 +00001528 ExtVectorType *New = new (*this,8) ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001529 VectorTypes.InsertNode(New, InsertPos);
1530 Types.push_back(New);
1531 return QualType(New, 0);
1532}
1533
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001534QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
1535 Expr *SizeExpr,
1536 SourceLocation AttrLoc) {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001537 llvm::FoldingSetNodeID ID;
1538 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
1539 SizeExpr);
1540
1541 void *InsertPos = 0;
1542 DependentSizedExtVectorType *Canon
1543 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1544 DependentSizedExtVectorType *New;
1545 if (Canon) {
1546 // We already have a canonical version of this array type; use it as
1547 // the canonical type for a newly-built type.
1548 New = new (*this,8) DependentSizedExtVectorType(*this, vecType,
1549 QualType(Canon, 0),
1550 SizeExpr, AttrLoc);
1551 } else {
1552 QualType CanonVecTy = getCanonicalType(vecType);
1553 if (CanonVecTy == vecType) {
1554 New = new (*this,8) DependentSizedExtVectorType(*this, vecType,
1555 QualType(), SizeExpr,
1556 AttrLoc);
1557 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1558 } else {
1559 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1560 SourceLocation());
1561 New = new (*this,8) DependentSizedExtVectorType(*this, vecType, Canon,
1562 SizeExpr, AttrLoc);
1563 }
1564 }
1565
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001566 Types.push_back(New);
1567 return QualType(New, 0);
1568}
1569
Douglas Gregor72564e72009-02-26 23:50:07 +00001570/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001571///
Mike Stump24556362009-07-25 21:26:53 +00001572QualType ASTContext::getFunctionNoProtoType(QualType ResultTy, bool NoReturn) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001573 // Unique functions, to guarantee there is only one function of a particular
1574 // structure.
1575 llvm::FoldingSetNodeID ID;
Mike Stump24556362009-07-25 21:26:53 +00001576 FunctionNoProtoType::Profile(ID, ResultTy, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001577
1578 void *InsertPos = 0;
Douglas Gregor72564e72009-02-26 23:50:07 +00001579 if (FunctionNoProtoType *FT =
1580 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001581 return QualType(FT, 0);
1582
1583 QualType Canonical;
1584 if (!ResultTy->isCanonical()) {
Mike Stump24556362009-07-25 21:26:53 +00001585 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001586
1587 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001588 FunctionNoProtoType *NewIP =
1589 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001590 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001591 }
1592
Mike Stump24556362009-07-25 21:26:53 +00001593 FunctionNoProtoType *New
1594 = new (*this,8) FunctionNoProtoType(ResultTy, Canonical, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001595 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001596 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001597 return QualType(New, 0);
1598}
1599
1600/// getFunctionType - Return a normal function type with a typed argument
1601/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner61710852008-10-05 17:34:18 +00001602QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001603 unsigned NumArgs, bool isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001604 unsigned TypeQuals, bool hasExceptionSpec,
1605 bool hasAnyExceptionSpec, unsigned NumExs,
Mike Stump24556362009-07-25 21:26:53 +00001606 const QualType *ExArray, bool NoReturn) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001607 // Unique functions, to guarantee there is only one function of a particular
1608 // structure.
1609 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001610 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001611 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Mike Stump24556362009-07-25 21:26:53 +00001612 NumExs, ExArray, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001613
1614 void *InsertPos = 0;
Douglas Gregor72564e72009-02-26 23:50:07 +00001615 if (FunctionProtoType *FTP =
1616 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001617 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001618
1619 // Determine whether the type being created is already canonical or not.
Reid Spencer5f016e22007-07-11 17:01:13 +00001620 bool isCanonical = ResultTy->isCanonical();
Sebastian Redl465226e2009-05-27 22:11:52 +00001621 if (hasExceptionSpec)
1622 isCanonical = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001623 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
1624 if (!ArgArray[i]->isCanonical())
1625 isCanonical = false;
1626
1627 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001628 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001629 QualType Canonical;
1630 if (!isCanonical) {
1631 llvm::SmallVector<QualType, 16> CanonicalArgs;
1632 CanonicalArgs.reserve(NumArgs);
1633 for (unsigned i = 0; i != NumArgs; ++i)
Chris Lattnerf52ab252008-04-06 22:59:24 +00001634 CanonicalArgs.push_back(getCanonicalType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001635
Chris Lattnerf52ab252008-04-06 22:59:24 +00001636 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001637 CanonicalArgs.data(), NumArgs,
Douglas Gregor47259d92009-08-05 19:03:35 +00001638 isVariadic, TypeQuals, false,
1639 false, 0, 0, NoReturn);
Sebastian Redl465226e2009-05-27 22:11:52 +00001640
Reid Spencer5f016e22007-07-11 17:01:13 +00001641 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001642 FunctionProtoType *NewIP =
1643 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001644 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001645 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001646
Douglas Gregor72564e72009-02-26 23:50:07 +00001647 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001648 // for two variable size arrays (for parameter and exception types) at the
1649 // end of them.
Douglas Gregor72564e72009-02-26 23:50:07 +00001650 FunctionProtoType *FTP =
Sebastian Redl465226e2009-05-27 22:11:52 +00001651 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1652 NumArgs*sizeof(QualType) +
1653 NumExs*sizeof(QualType), 8);
Douglas Gregor72564e72009-02-26 23:50:07 +00001654 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001655 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Mike Stump24556362009-07-25 21:26:53 +00001656 ExArray, NumExs, Canonical, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001657 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001658 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001659 return QualType(FTP, 0);
1660}
1661
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001662/// getTypeDeclType - Return the unique reference to the type for the
1663/// specified type declaration.
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001664QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001665 assert(Decl && "Passed null for Decl param");
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001666 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1667
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001668 if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001669 return getTypedefType(Typedef);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001670 else if (isa<TemplateTypeParmDecl>(Decl)) {
1671 assert(false && "Template type parameter types are always available.");
Mike Stump9fdbab32009-07-31 02:02:20 +00001672 } else if (ObjCInterfaceDecl *ObjCInterface
1673 = dyn_cast<ObjCInterfaceDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001674 return getObjCInterfaceType(ObjCInterface);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001675
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001676 if (RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001677 if (PrevDecl)
1678 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001679 else
1680 Decl->TypeForDecl = new (*this,8) RecordType(Record);
Mike Stump9fdbab32009-07-31 02:02:20 +00001681 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001682 if (PrevDecl)
1683 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001684 else
1685 Decl->TypeForDecl = new (*this,8) EnumType(Enum);
Mike Stump9fdbab32009-07-31 02:02:20 +00001686 } else
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001687 assert(false && "TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001688
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001689 if (!PrevDecl) Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001690 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001691}
1692
Reid Spencer5f016e22007-07-11 17:01:13 +00001693/// getTypedefType - Return the unique reference to the type for the
1694/// specified typename decl.
1695QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
1696 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1697
Chris Lattnerf52ab252008-04-06 22:59:24 +00001698 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
Douglas Gregor72564e72009-02-26 23:50:07 +00001699 Decl->TypeForDecl = new(*this,8) TypedefType(Type::Typedef, Decl, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001700 Types.push_back(Decl->TypeForDecl);
1701 return QualType(Decl->TypeForDecl, 0);
1702}
1703
Douglas Gregorfab9d672009-02-05 23:33:38 +00001704/// \brief Retrieve the template type parameter type for a template
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001705/// parameter or parameter pack with the given depth, index, and (optionally)
1706/// name.
Douglas Gregorfab9d672009-02-05 23:33:38 +00001707QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001708 bool ParameterPack,
Douglas Gregorfab9d672009-02-05 23:33:38 +00001709 IdentifierInfo *Name) {
1710 llvm::FoldingSetNodeID ID;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001711 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001712 void *InsertPos = 0;
1713 TemplateTypeParmType *TypeParm
1714 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1715
1716 if (TypeParm)
1717 return QualType(TypeParm, 0);
1718
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001719 if (Name) {
1720 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
1721 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, ParameterPack,
1722 Name, Canon);
1723 } else
1724 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001725
1726 Types.push_back(TypeParm);
1727 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1728
1729 return QualType(TypeParm, 0);
1730}
1731
Douglas Gregor55f6b142009-02-09 18:46:07 +00001732QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00001733ASTContext::getTemplateSpecializationType(TemplateName Template,
1734 const TemplateArgument *Args,
1735 unsigned NumArgs,
1736 QualType Canon) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00001737 if (!Canon.isNull())
1738 Canon = getCanonicalType(Canon);
1739 else {
1740 // Build the canonical template specialization type.
Douglas Gregor1275ae02009-07-28 23:00:59 +00001741 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
1742 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
1743 CanonArgs.reserve(NumArgs);
1744 for (unsigned I = 0; I != NumArgs; ++I)
1745 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
1746
1747 // Determine whether this canonical template specialization type already
1748 // exists.
1749 llvm::FoldingSetNodeID ID;
1750 TemplateSpecializationType::Profile(ID, CanonTemplate,
Douglas Gregor828e2262009-07-29 16:09:57 +00001751 CanonArgs.data(), NumArgs, *this);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001752
1753 void *InsertPos = 0;
1754 TemplateSpecializationType *Spec
1755 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
1756
1757 if (!Spec) {
1758 // Allocate a new canonical template specialization type.
1759 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
1760 sizeof(TemplateArgument) * NumArgs),
1761 8);
Douglas Gregor828e2262009-07-29 16:09:57 +00001762 Spec = new (Mem) TemplateSpecializationType(*this, CanonTemplate,
Douglas Gregor1275ae02009-07-28 23:00:59 +00001763 CanonArgs.data(), NumArgs,
Douglas Gregorb88e8882009-07-30 17:40:51 +00001764 Canon);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001765 Types.push_back(Spec);
1766 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
1767 }
1768
Douglas Gregorb88e8882009-07-30 17:40:51 +00001769 if (Canon.isNull())
1770 Canon = QualType(Spec, 0);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001771 assert(Canon->isDependentType() &&
1772 "Non-dependent template-id type must have a canonical type");
Douglas Gregorb88e8882009-07-30 17:40:51 +00001773 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00001774
Douglas Gregor1275ae02009-07-28 23:00:59 +00001775 // Allocate the (non-canonical) template specialization type, but don't
1776 // try to unique it: these types typically have location information that
1777 // we don't unique and don't want to lose.
Douglas Gregor7532dc62009-03-30 22:58:21 +00001778 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00001779 sizeof(TemplateArgument) * NumArgs),
1780 8);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001781 TemplateSpecializationType *Spec
Douglas Gregor828e2262009-07-29 16:09:57 +00001782 = new (Mem) TemplateSpecializationType(*this, Template, Args, NumArgs,
1783 Canon);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001784
Douglas Gregor55f6b142009-02-09 18:46:07 +00001785 Types.push_back(Spec);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001786 return QualType(Spec, 0);
1787}
1788
Douglas Gregore4e5b052009-03-19 00:18:19 +00001789QualType
Douglas Gregorab452ba2009-03-26 23:50:42 +00001790ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
Douglas Gregore4e5b052009-03-19 00:18:19 +00001791 QualType NamedType) {
1792 llvm::FoldingSetNodeID ID;
Douglas Gregorab452ba2009-03-26 23:50:42 +00001793 QualifiedNameType::Profile(ID, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001794
1795 void *InsertPos = 0;
1796 QualifiedNameType *T
1797 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
1798 if (T)
1799 return QualType(T, 0);
1800
Douglas Gregorab452ba2009-03-26 23:50:42 +00001801 T = new (*this) QualifiedNameType(NNS, NamedType,
1802 getCanonicalType(NamedType));
Douglas Gregore4e5b052009-03-19 00:18:19 +00001803 Types.push_back(T);
1804 QualifiedNameTypes.InsertNode(T, InsertPos);
1805 return QualType(T, 0);
1806}
1807
Douglas Gregord57959a2009-03-27 23:10:48 +00001808QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1809 const IdentifierInfo *Name,
1810 QualType Canon) {
1811 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1812
1813 if (Canon.isNull()) {
1814 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1815 if (CanonNNS != NNS)
1816 Canon = getTypenameType(CanonNNS, Name);
1817 }
1818
1819 llvm::FoldingSetNodeID ID;
1820 TypenameType::Profile(ID, NNS, Name);
1821
1822 void *InsertPos = 0;
1823 TypenameType *T
1824 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1825 if (T)
1826 return QualType(T, 0);
1827
1828 T = new (*this) TypenameType(NNS, Name, Canon);
1829 Types.push_back(T);
1830 TypenameTypes.InsertNode(T, InsertPos);
1831 return QualType(T, 0);
1832}
1833
Douglas Gregor17343172009-04-01 00:28:59 +00001834QualType
1835ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1836 const TemplateSpecializationType *TemplateId,
1837 QualType Canon) {
1838 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1839
1840 if (Canon.isNull()) {
1841 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1842 QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
1843 if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
1844 const TemplateSpecializationType *CanonTemplateId
1845 = CanonType->getAsTemplateSpecializationType();
1846 assert(CanonTemplateId &&
1847 "Canonical type must also be a template specialization type");
1848 Canon = getTypenameType(CanonNNS, CanonTemplateId);
1849 }
1850 }
1851
1852 llvm::FoldingSetNodeID ID;
1853 TypenameType::Profile(ID, NNS, TemplateId);
1854
1855 void *InsertPos = 0;
1856 TypenameType *T
1857 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1858 if (T)
1859 return QualType(T, 0);
1860
1861 T = new (*this) TypenameType(NNS, TemplateId, Canon);
1862 Types.push_back(T);
1863 TypenameTypes.InsertNode(T, InsertPos);
1864 return QualType(T, 0);
1865}
1866
Chris Lattner88cb27a2008-04-07 04:56:42 +00001867/// CmpProtocolNames - Comparison predicate for sorting protocols
1868/// alphabetically.
1869static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
1870 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001871 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00001872}
1873
1874static void SortAndUniqueProtocols(ObjCProtocolDecl **&Protocols,
1875 unsigned &NumProtocols) {
1876 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
1877
1878 // Sort protocols, keyed by name.
1879 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
1880
1881 // Remove duplicates.
1882 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
1883 NumProtocols = ProtocolsEnd-Protocols;
1884}
1885
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001886/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
1887/// the given interface decl and the conforming protocol list.
Steve Naroff14108da2009-07-10 23:34:53 +00001888QualType ASTContext::getObjCObjectPointerType(QualType InterfaceT,
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001889 ObjCProtocolDecl **Protocols,
1890 unsigned NumProtocols) {
1891 // Sort the protocol list alphabetically to canonicalize it.
1892 if (NumProtocols)
1893 SortAndUniqueProtocols(Protocols, NumProtocols);
1894
1895 llvm::FoldingSetNodeID ID;
Steve Naroff14108da2009-07-10 23:34:53 +00001896 ObjCObjectPointerType::Profile(ID, InterfaceT, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001897
1898 void *InsertPos = 0;
1899 if (ObjCObjectPointerType *QT =
1900 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1901 return QualType(QT, 0);
1902
1903 // No Match;
1904 ObjCObjectPointerType *QType =
Steve Naroff14108da2009-07-10 23:34:53 +00001905 new (*this,8) ObjCObjectPointerType(InterfaceT, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001906
1907 Types.push_back(QType);
1908 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
1909 return QualType(QType, 0);
1910}
Chris Lattner88cb27a2008-04-07 04:56:42 +00001911
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001912/// getObjCInterfaceType - Return the unique reference to the type for the
1913/// specified ObjC interface decl. The list of protocols is optional.
1914QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001915 ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001916 if (NumProtocols)
1917 // Sort the protocol list alphabetically to canonicalize it.
1918 SortAndUniqueProtocols(Protocols, NumProtocols);
Chris Lattner88cb27a2008-04-07 04:56:42 +00001919
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001920 llvm::FoldingSetNodeID ID;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001921 ObjCInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001922
1923 void *InsertPos = 0;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001924 if (ObjCInterfaceType *QT =
1925 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001926 return QualType(QT, 0);
1927
1928 // No Match;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001929 ObjCInterfaceType *QType =
1930 new (*this,8) ObjCInterfaceType(const_cast<ObjCInterfaceDecl*>(Decl),
1931 Protocols, NumProtocols);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001932 Types.push_back(QType);
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001933 ObjCInterfaceTypes.InsertNode(QType, InsertPos);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001934 return QualType(QType, 0);
1935}
1936
Douglas Gregor72564e72009-02-26 23:50:07 +00001937/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
1938/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00001939/// multiple declarations that refer to "typeof(x)" all contain different
1940/// DeclRefExpr's. This doesn't effect the type checker, since it operates
1941/// on canonical type's (which are always unique).
Douglas Gregor72564e72009-02-26 23:50:07 +00001942QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00001943 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00001944 if (tofExpr->isTypeDependent()) {
1945 llvm::FoldingSetNodeID ID;
1946 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
1947
1948 void *InsertPos = 0;
1949 DependentTypeOfExprType *Canon
1950 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
1951 if (Canon) {
1952 // We already have a "canonical" version of an identical, dependent
1953 // typeof(expr) type. Use that as our canonical type.
1954 toe = new (*this, 8) TypeOfExprType(tofExpr,
1955 QualType((TypeOfExprType*)Canon, 0));
1956 }
1957 else {
1958 // Build a new, canonical typeof(expr) type.
1959 Canon = new (*this, 8) DependentTypeOfExprType(*this, tofExpr);
1960 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
1961 toe = Canon;
1962 }
1963 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00001964 QualType Canonical = getCanonicalType(tofExpr->getType());
1965 toe = new (*this,8) TypeOfExprType(tofExpr, Canonical);
1966 }
Steve Naroff9752f252007-08-01 18:02:17 +00001967 Types.push_back(toe);
1968 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00001969}
1970
Steve Naroff9752f252007-08-01 18:02:17 +00001971/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
1972/// TypeOfType AST's. The only motivation to unique these nodes would be
1973/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
1974/// an issue. This doesn't effect the type checker, since it operates
1975/// on canonical type's (which are always unique).
Steve Naroffd1861fd2007-07-31 12:34:36 +00001976QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001977 QualType Canonical = getCanonicalType(tofType);
Steve Narofff83820b2009-01-27 22:08:43 +00001978 TypeOfType *tot = new (*this,8) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00001979 Types.push_back(tot);
1980 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00001981}
1982
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00001983/// getDecltypeForExpr - Given an expr, will return the decltype for that
1984/// expression, according to the rules in C++0x [dcl.type.simple]p4
1985static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00001986 if (e->isTypeDependent())
1987 return Context.DependentTy;
1988
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00001989 // If e is an id expression or a class member access, decltype(e) is defined
1990 // as the type of the entity named by e.
1991 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
1992 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
1993 return VD->getType();
1994 }
1995 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
1996 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
1997 return FD->getType();
1998 }
1999 // If e is a function call or an invocation of an overloaded operator,
2000 // (parentheses around e are ignored), decltype(e) is defined as the
2001 // return type of that function.
2002 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2003 return CE->getCallReturnType();
2004
2005 QualType T = e->getType();
2006
2007 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
2008 // defined as T&, otherwise decltype(e) is defined as T.
2009 if (e->isLvalue(Context) == Expr::LV_Valid)
2010 T = Context.getLValueReferenceType(T);
2011
2012 return T;
2013}
2014
Anders Carlsson395b4752009-06-24 19:06:50 +00002015/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2016/// DecltypeType AST's. The only motivation to unique these nodes would be
2017/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
2018/// an issue. This doesn't effect the type checker, since it operates
2019/// on canonical type's (which are always unique).
2020QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002021 DecltypeType *dt;
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002022 if (e->isTypeDependent()) {
2023 llvm::FoldingSetNodeID ID;
2024 DependentDecltypeType::Profile(ID, *this, e);
2025
2026 void *InsertPos = 0;
2027 DependentDecltypeType *Canon
2028 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2029 if (Canon) {
2030 // We already have a "canonical" version of an equivalent, dependent
2031 // decltype type. Use that as our canonical type.
2032 dt = new (*this, 8) DecltypeType(e, DependentTy,
2033 QualType((DecltypeType*)Canon, 0));
2034 }
2035 else {
2036 // Build a new, canonical typeof(expr) type.
2037 Canon = new (*this, 8) DependentDecltypeType(*this, e);
2038 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2039 dt = Canon;
2040 }
2041 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002042 QualType T = getDecltypeForExpr(e, *this);
Anders Carlsson563a03b2009-07-10 19:20:26 +00002043 dt = new (*this, 8) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002044 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002045 Types.push_back(dt);
2046 return QualType(dt, 0);
2047}
2048
Reid Spencer5f016e22007-07-11 17:01:13 +00002049/// getTagDeclType - Return the unique reference to the type for the
2050/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpe607ed02009-08-07 18:05:12 +00002051QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenekd778f882007-11-26 21:16:01 +00002052 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00002053 // FIXME: What is the design on getTagDeclType when it requires casting
2054 // away const? mutable?
2055 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002056}
2057
2058/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2059/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2060/// needs to agree with the definition in <stddef.h>.
2061QualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002062 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00002063}
2064
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00002065/// getSignedWCharType - Return the type of "signed wchar_t".
2066/// Used when in C++, as a GCC extension.
2067QualType ASTContext::getSignedWCharType() const {
2068 // FIXME: derive from "Target" ?
2069 return WCharTy;
2070}
2071
2072/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2073/// Used when in C++, as a GCC extension.
2074QualType ASTContext::getUnsignedWCharType() const {
2075 // FIXME: derive from "Target" ?
2076 return UnsignedIntTy;
2077}
2078
Chris Lattner8b9023b2007-07-13 03:05:23 +00002079/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2080/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2081QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002082 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00002083}
2084
Chris Lattnere6327742008-04-02 05:18:44 +00002085//===----------------------------------------------------------------------===//
2086// Type Operators
2087//===----------------------------------------------------------------------===//
2088
Chris Lattner77c96472008-04-06 22:41:35 +00002089/// getCanonicalType - Return the canonical (structural) type corresponding to
2090/// the specified potentially non-canonical type. The non-canonical version
2091/// of a type may have many "decorated" versions of types. Decorators can
2092/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2093/// to be free of any of these, allowing two canonical types to be compared
2094/// for exact equality with a simple pointer comparison.
Douglas Gregor50d62d12009-08-05 05:36:45 +00002095CanQualType ASTContext::getCanonicalType(QualType T) {
Chris Lattner77c96472008-04-06 22:41:35 +00002096 QualType CanType = T.getTypePtr()->getCanonicalTypeInternal();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002097
2098 // If the result has type qualifiers, make sure to canonicalize them as well.
2099 unsigned TypeQuals = T.getCVRQualifiers() | CanType.getCVRQualifiers();
Douglas Gregor50d62d12009-08-05 05:36:45 +00002100 if (TypeQuals == 0)
2101 return CanQualType::CreateUnsafe(CanType);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002102
2103 // If the type qualifiers are on an array type, get the canonical type of the
2104 // array with the qualifiers applied to the element type.
2105 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2106 if (!AT)
Douglas Gregor50d62d12009-08-05 05:36:45 +00002107 return CanQualType::CreateUnsafe(CanType.getQualifiedType(TypeQuals));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002108
2109 // Get the canonical version of the element with the extra qualifiers on it.
2110 // This can recursively sink qualifiers through multiple levels of arrays.
2111 QualType NewEltTy=AT->getElementType().getWithAdditionalQualifiers(TypeQuals);
2112 NewEltTy = getCanonicalType(NewEltTy);
2113
2114 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002115 return CanQualType::CreateUnsafe(
2116 getConstantArrayType(NewEltTy, CAT->getSize(),
2117 CAT->getSizeModifier(),
2118 CAT->getIndexTypeQualifier()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002119 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002120 return CanQualType::CreateUnsafe(
2121 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
2122 IAT->getIndexTypeQualifier()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002123
Douglas Gregor898574e2008-12-05 23:32:09 +00002124 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002125 return CanQualType::CreateUnsafe(
2126 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002127 DSAT->getSizeExpr() ?
2128 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002129 DSAT->getSizeModifier(),
2130 DSAT->getIndexTypeQualifier(),
2131 DSAT->getBracketsRange()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002132
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002133 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor50d62d12009-08-05 05:36:45 +00002134 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002135 VAT->getSizeExpr() ?
2136 VAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002137 VAT->getSizeModifier(),
2138 VAT->getIndexTypeQualifier(),
2139 VAT->getBracketsRange()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002140}
2141
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002142TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
2143 // If this template name refers to a template, the canonical
2144 // template name merely stores the template itself.
2145 if (TemplateDecl *Template = Name.getAsTemplateDecl())
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002146 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002147
Douglas Gregord99cbe62009-07-29 18:26:50 +00002148 // If this template name refers to a set of overloaded function templates,
2149 /// the canonical template name merely stores the set of function templates.
Douglas Gregor6ebd15e2009-07-31 05:24:01 +00002150 if (OverloadedFunctionDecl *Ovl = Name.getAsOverloadedFunctionDecl()) {
2151 OverloadedFunctionDecl *CanonOvl = 0;
2152 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
2153 FEnd = Ovl->function_end();
2154 F != FEnd; ++F) {
2155 Decl *Canon = F->get()->getCanonicalDecl();
2156 if (CanonOvl || Canon != F->get()) {
2157 if (!CanonOvl)
2158 CanonOvl = OverloadedFunctionDecl::Create(*this,
2159 Ovl->getDeclContext(),
2160 Ovl->getDeclName());
2161
2162 CanonOvl->addOverload(
2163 AnyFunctionDecl::getFromNamedDecl(cast<NamedDecl>(Canon)));
2164 }
2165 }
2166
2167 return TemplateName(CanonOvl? CanonOvl : Ovl);
2168 }
Douglas Gregord99cbe62009-07-29 18:26:50 +00002169
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002170 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2171 assert(DTN && "Non-dependent template names must refer to template decls.");
2172 return DTN->CanonicalTemplateName;
2173}
2174
Douglas Gregor1275ae02009-07-28 23:00:59 +00002175TemplateArgument
2176ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2177 switch (Arg.getKind()) {
2178 case TemplateArgument::Null:
2179 return Arg;
2180
2181 case TemplateArgument::Expression:
2182 // FIXME: Build canonical expression?
2183 return Arg;
2184
2185 case TemplateArgument::Declaration:
2186 return TemplateArgument(SourceLocation(),
2187 Arg.getAsDecl()->getCanonicalDecl());
2188
2189 case TemplateArgument::Integral:
2190 return TemplateArgument(SourceLocation(),
2191 *Arg.getAsIntegral(),
2192 getCanonicalType(Arg.getIntegralType()));
2193
2194 case TemplateArgument::Type:
2195 return TemplateArgument(SourceLocation(),
2196 getCanonicalType(Arg.getAsType()));
2197
2198 case TemplateArgument::Pack: {
2199 // FIXME: Allocate in ASTContext
2200 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2201 unsigned Idx = 0;
2202 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
2203 AEnd = Arg.pack_end();
2204 A != AEnd; (void)++A, ++Idx)
2205 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
2206
2207 TemplateArgument Result;
2208 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2209 return Result;
2210 }
2211 }
2212
2213 // Silence GCC warning
2214 assert(false && "Unhandled template argument kind");
2215 return TemplateArgument();
2216}
2217
Douglas Gregord57959a2009-03-27 23:10:48 +00002218NestedNameSpecifier *
2219ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
2220 if (!NNS)
2221 return 0;
2222
2223 switch (NNS->getKind()) {
2224 case NestedNameSpecifier::Identifier:
2225 // Canonicalize the prefix but keep the identifier the same.
2226 return NestedNameSpecifier::Create(*this,
2227 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2228 NNS->getAsIdentifier());
2229
2230 case NestedNameSpecifier::Namespace:
2231 // A namespace is canonical; build a nested-name-specifier with
2232 // this namespace and no prefix.
2233 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2234
2235 case NestedNameSpecifier::TypeSpec:
2236 case NestedNameSpecifier::TypeSpecWithTemplate: {
2237 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
2238 NestedNameSpecifier *Prefix = 0;
2239
2240 // FIXME: This isn't the right check!
2241 if (T->isDependentType())
2242 Prefix = getCanonicalNestedNameSpecifier(NNS->getPrefix());
2243
2244 return NestedNameSpecifier::Create(*this, Prefix,
2245 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
2246 T.getTypePtr());
2247 }
2248
2249 case NestedNameSpecifier::Global:
2250 // The global specifier is canonical and unique.
2251 return NNS;
2252 }
2253
2254 // Required to silence a GCC warning
2255 return 0;
2256}
2257
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002258
2259const ArrayType *ASTContext::getAsArrayType(QualType T) {
2260 // Handle the non-qualified case efficiently.
2261 if (T.getCVRQualifiers() == 0) {
2262 // Handle the common positive case fast.
2263 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2264 return AT;
2265 }
2266
2267 // Handle the common negative case fast, ignoring CVR qualifiers.
2268 QualType CType = T->getCanonicalTypeInternal();
2269
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002270 // Make sure to look through type qualifiers (like ExtQuals) for the negative
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002271 // test.
2272 if (!isa<ArrayType>(CType) &&
2273 !isa<ArrayType>(CType.getUnqualifiedType()))
2274 return 0;
2275
2276 // Apply any CVR qualifiers from the array type to the element type. This
2277 // implements C99 6.7.3p8: "If the specification of an array type includes
2278 // any type qualifiers, the element type is so qualified, not the array type."
2279
2280 // If we get here, we either have type qualifiers on the type, or we have
2281 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00002282 // we must propagate them down into the element type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002283 unsigned CVRQuals = T.getCVRQualifiers();
2284 unsigned AddrSpace = 0;
2285 Type *Ty = T.getTypePtr();
2286
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002287 // Rip through ExtQualType's and typedefs to get to a concrete type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002288 while (1) {
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002289 if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(Ty)) {
2290 AddrSpace = EXTQT->getAddressSpace();
2291 Ty = EXTQT->getBaseType();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002292 } else {
2293 T = Ty->getDesugaredType();
2294 if (T.getTypePtr() == Ty && T.getCVRQualifiers() == 0)
2295 break;
2296 CVRQuals |= T.getCVRQualifiers();
2297 Ty = T.getTypePtr();
2298 }
2299 }
2300
2301 // If we have a simple case, just return now.
2302 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
2303 if (ATy == 0 || (AddrSpace == 0 && CVRQuals == 0))
2304 return ATy;
2305
2306 // Otherwise, we have an array and we have qualifiers on it. Push the
2307 // qualifiers into the array element type and return a new array type.
2308 // Get the canonical version of the element with the extra qualifiers on it.
2309 // This can recursively sink qualifiers through multiple levels of arrays.
2310 QualType NewEltTy = ATy->getElementType();
2311 if (AddrSpace)
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002312 NewEltTy = getAddrSpaceQualType(NewEltTy, AddrSpace);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002313 NewEltTy = NewEltTy.getWithAdditionalQualifiers(CVRQuals);
2314
2315 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2316 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2317 CAT->getSizeModifier(),
2318 CAT->getIndexTypeQualifier()));
2319 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2320 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2321 IAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002322 IAT->getIndexTypeQualifier()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002323
Douglas Gregor898574e2008-12-05 23:32:09 +00002324 if (const DependentSizedArrayType *DSAT
2325 = dyn_cast<DependentSizedArrayType>(ATy))
2326 return cast<ArrayType>(
2327 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002328 DSAT->getSizeExpr() ?
2329 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor898574e2008-12-05 23:32:09 +00002330 DSAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002331 DSAT->getIndexTypeQualifier(),
2332 DSAT->getBracketsRange()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002333
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002334 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002335 return cast<ArrayType>(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002336 VAT->getSizeExpr() ?
2337 VAT->getSizeExpr()->Retain() : 0,
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002338 VAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002339 VAT->getIndexTypeQualifier(),
2340 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00002341}
2342
2343
Chris Lattnere6327742008-04-02 05:18:44 +00002344/// getArrayDecayedType - Return the properly qualified result of decaying the
2345/// specified array type to a pointer. This operation is non-trivial when
2346/// handling typedefs etc. The canonical type of "T" must be an array type,
2347/// this returns a pointer to a properly qualified element of the array.
2348///
2349/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2350QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002351 // Get the element type with 'getAsArrayType' so that we don't lose any
2352 // typedefs in the element type of the array. This also handles propagation
2353 // of type qualifiers from the array type into the element type if present
2354 // (C99 6.7.3p8).
2355 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2356 assert(PrettyArrayType && "Not an array type!");
Chris Lattnere6327742008-04-02 05:18:44 +00002357
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002358 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00002359
2360 // int x[restrict 4] -> int *restrict
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002361 return PtrTy.getQualifiedType(PrettyArrayType->getIndexTypeQualifier());
Chris Lattnere6327742008-04-02 05:18:44 +00002362}
2363
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002364QualType ASTContext::getBaseElementType(QualType QT) {
2365 QualifierSet qualifiers;
2366 while (true) {
2367 const Type *UT = qualifiers.strip(QT);
2368 if (const ArrayType *AT = getAsArrayType(QualType(UT,0))) {
2369 QT = AT->getElementType();
Mike Stump6dcbc292009-07-25 23:24:03 +00002370 } else {
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002371 return qualifiers.apply(QT, *this);
2372 }
2373 }
2374}
2375
Daniel Dunbard786f6a2009-01-05 22:14:37 +00002376QualType ASTContext::getBaseElementType(const VariableArrayType *VAT) {
Anders Carlsson6183a992008-12-21 03:44:36 +00002377 QualType ElemTy = VAT->getElementType();
2378
2379 if (const VariableArrayType *VAT = getAsVariableArrayType(ElemTy))
2380 return getBaseElementType(VAT);
2381
2382 return ElemTy;
2383}
2384
Reid Spencer5f016e22007-07-11 17:01:13 +00002385/// getFloatingRank - Return a relative rank for floating point types.
2386/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00002387static FloatingRank getFloatingRank(QualType T) {
Christopher Lambebb97e92008-02-04 02:31:56 +00002388 if (const ComplexType *CT = T->getAsComplexType())
Reid Spencer5f016e22007-07-11 17:01:13 +00002389 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00002390
Daniel Dunbard786f6a2009-01-05 22:14:37 +00002391 assert(T->getAsBuiltinType() && "getFloatingRank(): not a floating type");
Christopher Lambebb97e92008-02-04 02:31:56 +00002392 switch (T->getAsBuiltinType()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00002393 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002394 case BuiltinType::Float: return FloatRank;
2395 case BuiltinType::Double: return DoubleRank;
2396 case BuiltinType::LongDouble: return LongDoubleRank;
2397 }
2398}
2399
Steve Naroff716c7302007-08-27 01:41:48 +00002400/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2401/// point or a complex type (based on typeDomain/typeSize).
2402/// 'typeDomain' is a real floating point or complex type.
2403/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00002404QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2405 QualType Domain) const {
2406 FloatingRank EltRank = getFloatingRank(Size);
2407 if (Domain->isComplexType()) {
2408 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00002409 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00002410 case FloatRank: return FloatComplexTy;
2411 case DoubleRank: return DoubleComplexTy;
2412 case LongDoubleRank: return LongDoubleComplexTy;
2413 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002414 }
Chris Lattner1361b112008-04-06 23:58:54 +00002415
2416 assert(Domain->isRealFloatingType() && "Unknown domain!");
2417 switch (EltRank) {
2418 default: assert(0 && "getFloatingRank(): illegal value for rank");
2419 case FloatRank: return FloatTy;
2420 case DoubleRank: return DoubleTy;
2421 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00002422 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002423}
2424
Chris Lattner7cfeb082008-04-06 23:55:33 +00002425/// getFloatingTypeOrder - Compare the rank of the two specified floating
2426/// point types, ignoring the domain of the type (i.e. 'double' ==
2427/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
2428/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00002429int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2430 FloatingRank LHSR = getFloatingRank(LHS);
2431 FloatingRank RHSR = getFloatingRank(RHS);
2432
2433 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002434 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00002435 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002436 return 1;
2437 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002438}
2439
Chris Lattnerf52ab252008-04-06 22:59:24 +00002440/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2441/// routine will assert if passed a built-in type that isn't an integer or enum,
2442/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00002443unsigned ASTContext::getIntegerRank(Type *T) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002444 assert(T->isCanonical() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00002445 if (EnumType* ET = dyn_cast<EnumType>(T))
2446 T = ET->getDecl()->getIntegerType().getTypePtr();
2447
Eli Friedmana3426752009-07-05 23:44:27 +00002448 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2449 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2450
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002451 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2452 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2453
2454 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2455 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2456
Eli Friedmanf98aba32009-02-13 02:31:07 +00002457 // There are two things which impact the integer rank: the width, and
2458 // the ordering of builtins. The builtin ordering is encoded in the
2459 // bottom three bits; the width is encoded in the bits above that.
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002460 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T))
Eli Friedmanf98aba32009-02-13 02:31:07 +00002461 return FWIT->getWidth() << 3;
Eli Friedmanf98aba32009-02-13 02:31:07 +00002462
Chris Lattnerf52ab252008-04-06 22:59:24 +00002463 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00002464 default: assert(0 && "getIntegerRank(): not a built-in integer");
2465 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002466 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002467 case BuiltinType::Char_S:
2468 case BuiltinType::Char_U:
2469 case BuiltinType::SChar:
2470 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002471 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002472 case BuiltinType::Short:
2473 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002474 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002475 case BuiltinType::Int:
2476 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002477 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002478 case BuiltinType::Long:
2479 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002480 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002481 case BuiltinType::LongLong:
2482 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002483 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00002484 case BuiltinType::Int128:
2485 case BuiltinType::UInt128:
2486 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00002487 }
2488}
2489
Eli Friedmana95d7572009-08-19 07:44:53 +00002490/// getPromotedIntegerType - Returns the type that Promotable will
2491/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2492/// integer type.
2493QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2494 assert(!Promotable.isNull());
2495 assert(Promotable->isPromotableIntegerType());
2496 if (Promotable->isSignedIntegerType())
2497 return IntTy;
2498 uint64_t PromotableSize = getTypeSize(Promotable);
2499 uint64_t IntSize = getTypeSize(IntTy);
2500 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2501 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2502}
2503
Chris Lattner7cfeb082008-04-06 23:55:33 +00002504/// getIntegerTypeOrder - Returns the highest ranked integer type:
2505/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
2506/// LHS < RHS, return -1.
2507int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002508 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2509 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00002510 if (LHSC == RHSC) return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00002511
Chris Lattnerf52ab252008-04-06 22:59:24 +00002512 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2513 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002514
Chris Lattner7cfeb082008-04-06 23:55:33 +00002515 unsigned LHSRank = getIntegerRank(LHSC);
2516 unsigned RHSRank = getIntegerRank(RHSC);
Reid Spencer5f016e22007-07-11 17:01:13 +00002517
Chris Lattner7cfeb082008-04-06 23:55:33 +00002518 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2519 if (LHSRank == RHSRank) return 0;
2520 return LHSRank > RHSRank ? 1 : -1;
2521 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002522
Chris Lattner7cfeb082008-04-06 23:55:33 +00002523 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2524 if (LHSUnsigned) {
2525 // If the unsigned [LHS] type is larger, return it.
2526 if (LHSRank >= RHSRank)
2527 return 1;
2528
2529 // If the signed type can represent all values of the unsigned type, it
2530 // wins. Because we are dealing with 2's complement and types that are
2531 // powers of two larger than each other, this is always safe.
2532 return -1;
2533 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00002534
Chris Lattner7cfeb082008-04-06 23:55:33 +00002535 // If the unsigned [RHS] type is larger, return it.
2536 if (RHSRank >= LHSRank)
2537 return -1;
2538
2539 // If the signed type can represent all values of the unsigned type, it
2540 // wins. Because we are dealing with 2's complement and types that are
2541 // powers of two larger than each other, this is always safe.
2542 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002543}
Anders Carlsson71993dd2007-08-17 05:31:46 +00002544
2545// getCFConstantStringType - Return the type used for constant CFStrings.
2546QualType ASTContext::getCFConstantStringType() {
2547 if (!CFConstantStringTypeDecl) {
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002548 CFConstantStringTypeDecl =
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002549 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002550 &Idents.get("NSConstantString"));
Anders Carlssonf06273f2007-11-19 00:25:30 +00002551 QualType FieldTypes[4];
Anders Carlsson71993dd2007-08-17 05:31:46 +00002552
2553 // const int *isa;
2554 FieldTypes[0] = getPointerType(IntTy.getQualifiedType(QualType::Const));
Anders Carlssonf06273f2007-11-19 00:25:30 +00002555 // int flags;
2556 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00002557 // const char *str;
Anders Carlssonf06273f2007-11-19 00:25:30 +00002558 FieldTypes[2] = getPointerType(CharTy.getQualifiedType(QualType::Const));
Anders Carlsson71993dd2007-08-17 05:31:46 +00002559 // long length;
Anders Carlssonf06273f2007-11-19 00:25:30 +00002560 FieldTypes[3] = LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002561
Anders Carlsson71993dd2007-08-17 05:31:46 +00002562 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002563 for (unsigned i = 0; i < 4; ++i) {
2564 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
2565 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002566 FieldTypes[i], /*DInfo=*/0,
2567 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002568 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002569 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002570 }
2571
2572 CFConstantStringTypeDecl->completeDefinition(*this);
Anders Carlsson71993dd2007-08-17 05:31:46 +00002573 }
2574
2575 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00002576}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002577
Douglas Gregor319ac892009-04-23 22:29:11 +00002578void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002579 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00002580 assert(Rec && "Invalid CFConstantStringType");
2581 CFConstantStringTypeDecl = Rec->getDecl();
2582}
2583
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002584QualType ASTContext::getObjCFastEnumerationStateType()
2585{
2586 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00002587 ObjCFastEnumerationStateTypeDecl =
2588 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2589 &Idents.get("__objcFastEnumerationState"));
2590
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002591 QualType FieldTypes[] = {
2592 UnsignedLongTy,
Steve Naroffde2e22d2009-07-15 18:40:39 +00002593 getPointerType(ObjCIdTypedefType),
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002594 getPointerType(UnsignedLongTy),
2595 getConstantArrayType(UnsignedLongTy,
2596 llvm::APInt(32, 5), ArrayType::Normal, 0)
2597 };
2598
Douglas Gregor44b43212008-12-11 16:49:14 +00002599 for (size_t i = 0; i < 4; ++i) {
2600 FieldDecl *Field = FieldDecl::Create(*this,
2601 ObjCFastEnumerationStateTypeDecl,
2602 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002603 FieldTypes[i], /*DInfo=*/0,
2604 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002605 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002606 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002607 }
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002608
Douglas Gregor44b43212008-12-11 16:49:14 +00002609 ObjCFastEnumerationStateTypeDecl->completeDefinition(*this);
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002610 }
2611
2612 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2613}
2614
Douglas Gregor319ac892009-04-23 22:29:11 +00002615void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002616 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00002617 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
2618 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
2619}
2620
Anders Carlssone8c49532007-10-29 06:33:42 +00002621// This returns true if a type has been typedefed to BOOL:
2622// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00002623static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00002624 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00002625 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
2626 return II->isStr("BOOL");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002627
2628 return false;
2629}
2630
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002631/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002632/// purpose.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002633int ASTContext::getObjCEncodingTypeSize(QualType type) {
Chris Lattner98be4942008-03-05 18:54:05 +00002634 uint64_t sz = getTypeSize(type);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002635
2636 // Make all integer and enum types at least as large as an int
2637 if (sz > 0 && type->isIntegralType())
Chris Lattner98be4942008-03-05 18:54:05 +00002638 sz = std::max(sz, getTypeSize(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002639 // Treat arrays as pointers, since that's how they're passed in.
2640 else if (type->isArrayType())
Chris Lattner98be4942008-03-05 18:54:05 +00002641 sz = getTypeSize(VoidPtrTy);
2642 return sz / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002643}
2644
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002645/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002646/// declaration.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002647void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00002648 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002649 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002650 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002651 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002652 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002653 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002654 // Compute size of all parameters.
2655 // Start with computing size of a pointer in number of bytes.
2656 // FIXME: There might(should) be a better way of doing this computation!
2657 SourceLocation Loc;
Chris Lattner98be4942008-03-05 18:54:05 +00002658 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002659 // The first two arguments (self and _cmd) are pointers; account for
2660 // their size.
2661 int ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00002662 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2663 E = Decl->param_end(); PI != E; ++PI) {
2664 QualType PType = (*PI)->getType();
2665 int sz = getObjCEncodingTypeSize(PType);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002666 assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002667 ParmOffset += sz;
2668 }
2669 S += llvm::utostr(ParmOffset);
2670 S += "@0:";
2671 S += llvm::utostr(PtrSize);
2672
2673 // Argument types.
2674 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00002675 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2676 E = Decl->param_end(); PI != E; ++PI) {
2677 ParmVarDecl *PVDecl = *PI;
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00002678 QualType PType = PVDecl->getOriginalType();
2679 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00002680 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
2681 // Use array's original type only if it has known number of
2682 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00002683 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00002684 PType = PVDecl->getType();
2685 } else if (PType->isFunctionType())
2686 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002687 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002688 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00002689 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002690 getObjCEncodingForType(PType, S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002691 S += llvm::utostr(ParmOffset);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002692 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002693 }
2694}
2695
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002696/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00002697/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002698/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
2699/// NULL when getting encodings for protocol properties.
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00002700/// Property attributes are stored as a comma-delimited C string. The simple
2701/// attributes readonly and bycopy are encoded as single characters. The
2702/// parametrized attributes, getter=name, setter=name, and ivar=name, are
2703/// encoded as single characters, followed by an identifier. Property types
2704/// are also encoded as a parametrized attribute. The characters used to encode
2705/// these attributes are defined by the following enumeration:
2706/// @code
2707/// enum PropertyAttributes {
2708/// kPropertyReadOnly = 'R', // property is read-only.
2709/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
2710/// kPropertyByref = '&', // property is a reference to the value last assigned
2711/// kPropertyDynamic = 'D', // property is dynamic
2712/// kPropertyGetter = 'G', // followed by getter selector name
2713/// kPropertySetter = 'S', // followed by setter selector name
2714/// kPropertyInstanceVariable = 'V' // followed by instance variable name
2715/// kPropertyType = 't' // followed by old-style type encoding.
2716/// kPropertyWeak = 'W' // 'weak' property
2717/// kPropertyStrong = 'P' // property GC'able
2718/// kPropertyNonAtomic = 'N' // property non-atomic
2719/// };
2720/// @endcode
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002721void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
2722 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00002723 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002724 // Collect information from the property implementation decl(s).
2725 bool Dynamic = false;
2726 ObjCPropertyImplDecl *SynthesizePID = 0;
2727
2728 // FIXME: Duplicated code due to poor abstraction.
2729 if (Container) {
2730 if (const ObjCCategoryImplDecl *CID =
2731 dyn_cast<ObjCCategoryImplDecl>(Container)) {
2732 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002733 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00002734 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002735 ObjCPropertyImplDecl *PID = *i;
2736 if (PID->getPropertyDecl() == PD) {
2737 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2738 Dynamic = true;
2739 } else {
2740 SynthesizePID = PID;
2741 }
2742 }
2743 }
2744 } else {
Chris Lattner61710852008-10-05 17:34:18 +00002745 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002746 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002747 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00002748 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002749 ObjCPropertyImplDecl *PID = *i;
2750 if (PID->getPropertyDecl() == PD) {
2751 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2752 Dynamic = true;
2753 } else {
2754 SynthesizePID = PID;
2755 }
2756 }
2757 }
2758 }
2759 }
2760
2761 // FIXME: This is not very efficient.
2762 S = "T";
2763
2764 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002765 // GCC has some special rules regarding encoding of properties which
2766 // closely resembles encoding of ivars.
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002767 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002768 true /* outermost type */,
2769 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002770
2771 if (PD->isReadOnly()) {
2772 S += ",R";
2773 } else {
2774 switch (PD->getSetterKind()) {
2775 case ObjCPropertyDecl::Assign: break;
2776 case ObjCPropertyDecl::Copy: S += ",C"; break;
2777 case ObjCPropertyDecl::Retain: S += ",&"; break;
2778 }
2779 }
2780
2781 // It really isn't clear at all what this means, since properties
2782 // are "dynamic by default".
2783 if (Dynamic)
2784 S += ",D";
2785
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002786 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
2787 S += ",N";
2788
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002789 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
2790 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002791 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002792 }
2793
2794 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
2795 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002796 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002797 }
2798
2799 if (SynthesizePID) {
2800 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
2801 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00002802 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002803 }
2804
2805 // FIXME: OBJCGC: weak & strong
2806}
2807
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002808/// getLegacyIntegralTypeEncoding -
2809/// Another legacy compatibility encoding: 32-bit longs are encoded as
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002810/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002811/// 'i' or 'I' instead if encoding a struct field, or a pointer!
2812///
2813void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00002814 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002815 if (const BuiltinType *BT = PointeeTy->getAsBuiltinType()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002816 if (BT->getKind() == BuiltinType::ULong &&
2817 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002818 PointeeTy = UnsignedIntTy;
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002819 else
2820 if (BT->getKind() == BuiltinType::Long &&
2821 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002822 PointeeTy = IntTy;
2823 }
2824 }
2825}
2826
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002827void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002828 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002829 // We follow the behavior of gcc, expanding structures which are
2830 // directly pointed to, and expanding embedded structures. Note that
2831 // these rules are sufficient to prevent recursive encoding of the
2832 // same type.
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00002833 getObjCEncodingForTypeImpl(T, S, true, true, Field,
2834 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002835}
2836
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002837static void EncodeBitField(const ASTContext *Context, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002838 const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002839 const Expr *E = FD->getBitWidth();
2840 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
2841 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Eli Friedman9a901bb2009-04-26 19:19:15 +00002842 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002843 S += 'b';
2844 S += llvm::utostr(N);
2845}
2846
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002847void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
2848 bool ExpandPointedToStructures,
2849 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002850 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002851 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002852 bool EncodingProperty) {
Anders Carlssone8c49532007-10-29 06:33:42 +00002853 if (const BuiltinType *BT = T->getAsBuiltinType()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002854 if (FD && FD->isBitField())
2855 return EncodeBitField(this, S, FD);
2856 char encoding;
2857 switch (BT->getKind()) {
2858 default: assert(0 && "Unhandled builtin type kind");
2859 case BuiltinType::Void: encoding = 'v'; break;
2860 case BuiltinType::Bool: encoding = 'B'; break;
2861 case BuiltinType::Char_U:
2862 case BuiltinType::UChar: encoding = 'C'; break;
2863 case BuiltinType::UShort: encoding = 'S'; break;
2864 case BuiltinType::UInt: encoding = 'I'; break;
2865 case BuiltinType::ULong:
Fariborz Jahanian72696e12009-02-11 22:31:45 +00002866 encoding =
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002867 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
Fariborz Jahanian72696e12009-02-11 22:31:45 +00002868 break;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002869 case BuiltinType::UInt128: encoding = 'T'; break;
2870 case BuiltinType::ULongLong: encoding = 'Q'; break;
2871 case BuiltinType::Char_S:
2872 case BuiltinType::SChar: encoding = 'c'; break;
2873 case BuiltinType::Short: encoding = 's'; break;
2874 case BuiltinType::Int: encoding = 'i'; break;
2875 case BuiltinType::Long:
2876 encoding =
2877 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
2878 break;
2879 case BuiltinType::LongLong: encoding = 'q'; break;
2880 case BuiltinType::Int128: encoding = 't'; break;
2881 case BuiltinType::Float: encoding = 'f'; break;
2882 case BuiltinType::Double: encoding = 'd'; break;
2883 case BuiltinType::LongDouble: encoding = 'd'; break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002884 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002885
2886 S += encoding;
2887 return;
2888 }
2889
2890 if (const ComplexType *CT = T->getAsComplexType()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00002891 S += 'j';
2892 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
2893 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002894 return;
2895 }
2896
Ted Kremenek6217b802009-07-29 21:53:49 +00002897 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002898 QualType PointeeTy = PT->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002899 bool isReadOnly = false;
2900 // For historical/compatibility reasons, the read-only qualifier of the
2901 // pointee gets emitted _before_ the '^'. The read-only qualifier of
2902 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
2903 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00002904 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002905 if (OutermostType && T.isConstQualified()) {
2906 isReadOnly = true;
2907 S += 'r';
2908 }
Mike Stump9fdbab32009-07-31 02:02:20 +00002909 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002910 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00002911 while (P->getAs<PointerType>())
2912 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002913 if (P.isConstQualified()) {
2914 isReadOnly = true;
2915 S += 'r';
2916 }
2917 }
2918 if (isReadOnly) {
2919 // Another legacy compatibility encoding. Some ObjC qualifier and type
2920 // combinations need to be rearranged.
2921 // Rewrite "in const" from "nr" to "rn"
2922 const char * s = S.c_str();
2923 int len = S.length();
2924 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
2925 std::string replace = "rn";
2926 S.replace(S.end()-2, S.end(), replace);
2927 }
2928 }
Steve Naroff14108da2009-07-10 23:34:53 +00002929 if (isObjCSelType(PointeeTy)) {
Anders Carlsson8baaca52007-10-31 02:53:19 +00002930 S += ':';
2931 return;
Fariborz Jahanianc2939bc2007-10-30 17:06:23 +00002932 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002933
2934 if (PointeeTy->isCharType()) {
2935 // char pointer types should be encoded as '*' unless it is a
2936 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00002937 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002938 S += '*';
2939 return;
2940 }
Ted Kremenek6217b802009-07-29 21:53:49 +00002941 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00002942 // GCC binary compat: Need to convert "struct objc_class *" to "#".
2943 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
2944 S += '#';
2945 return;
2946 }
2947 // GCC binary compat: Need to convert "struct objc_object *" to "@".
2948 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
2949 S += '@';
2950 return;
2951 }
2952 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002953 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002954 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002955 getLegacyIntegralTypeEncoding(PointeeTy);
2956
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002957 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002958 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002959 return;
2960 }
2961
2962 if (const ArrayType *AT =
2963 // Ignore type qualifiers etc.
2964 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00002965 if (isa<IncompleteArrayType>(AT)) {
2966 // Incomplete arrays are encoded as a pointer to the array element.
2967 S += '^';
2968
2969 getObjCEncodingForTypeImpl(AT->getElementType(), S,
2970 false, ExpandStructures, FD);
2971 } else {
2972 S += '[';
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002973
Anders Carlsson559a8332009-02-22 01:38:57 +00002974 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
2975 S += llvm::utostr(CAT->getSize().getZExtValue());
2976 else {
2977 //Variable length arrays are encoded as a regular array with 0 elements.
2978 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
2979 S += '0';
2980 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002981
Anders Carlsson559a8332009-02-22 01:38:57 +00002982 getObjCEncodingForTypeImpl(AT->getElementType(), S,
2983 false, ExpandStructures, FD);
2984 S += ']';
2985 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002986 return;
2987 }
2988
2989 if (T->getAsFunctionType()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00002990 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002991 return;
2992 }
2993
Ted Kremenek6217b802009-07-29 21:53:49 +00002994 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002995 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002996 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00002997 // Anonymous structures print as '?'
2998 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
2999 S += II->getName();
3000 } else {
3001 S += '?';
3002 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003003 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003004 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003005 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3006 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00003007 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003008 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003009 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00003010 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003011 S += '"';
3012 }
3013
3014 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003015 if (Field->isBitField()) {
3016 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
3017 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003018 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003019 QualType qt = Field->getType();
3020 getLegacyIntegralTypeEncoding(qt);
3021 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003022 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003023 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003024 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00003025 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003026 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003027 return;
3028 }
3029
3030 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003031 if (FD && FD->isBitField())
3032 EncodeBitField(this, S, FD);
3033 else
3034 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003035 return;
3036 }
3037
3038 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00003039 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003040 return;
3041 }
3042
3043 if (T->isObjCInterfaceType()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003044 // @encode(class_name)
3045 ObjCInterfaceDecl *OI = T->getAsObjCInterfaceType()->getDecl();
3046 S += '{';
3047 const IdentifierInfo *II = OI->getIdentifier();
3048 S += II->getName();
3049 S += '=';
Chris Lattnerf1690852009-03-31 08:48:01 +00003050 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003051 CollectObjCIvars(OI, RecFields);
Chris Lattnerf1690852009-03-31 08:48:01 +00003052 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003053 if (RecFields[i]->isBitField())
3054 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
3055 RecFields[i]);
3056 else
3057 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
3058 FD);
3059 }
3060 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003061 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003062 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003063
3064 if (const ObjCObjectPointerType *OPT = T->getAsObjCObjectPointerType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003065 if (OPT->isObjCIdType()) {
3066 S += '@';
3067 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003068 }
3069
3070 if (OPT->isObjCClassType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003071 S += '#';
3072 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003073 }
3074
3075 if (OPT->isObjCQualifiedIdType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003076 getObjCEncodingForTypeImpl(getObjCIdType(), S,
3077 ExpandPointedToStructures,
3078 ExpandStructures, FD);
3079 if (FD || EncodingProperty) {
3080 // Note that we do extended encoding of protocol qualifer list
3081 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00003082 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003083 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3084 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00003085 S += '<';
3086 S += (*I)->getNameAsString();
3087 S += '>';
3088 }
3089 S += '"';
3090 }
3091 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003092 }
3093
3094 QualType PointeeTy = OPT->getPointeeType();
3095 if (!EncodingProperty &&
3096 isa<TypedefType>(PointeeTy.getTypePtr())) {
3097 // Another historical/compatibility reason.
3098 // We encode the underlying type which comes out as
3099 // {...};
3100 S += '^';
3101 getObjCEncodingForTypeImpl(PointeeTy, S,
3102 false, ExpandPointedToStructures,
3103 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00003104 return;
3105 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003106
3107 S += '@';
3108 if (FD || EncodingProperty) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003109 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003110 S += OPT->getInterfaceDecl()->getNameAsCString();
3111 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3112 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003113 S += '<';
3114 S += (*I)->getNameAsString();
3115 S += '>';
3116 }
3117 S += '"';
3118 }
3119 return;
3120 }
3121
3122 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003123}
3124
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003125void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003126 std::string& S) const {
3127 if (QT & Decl::OBJC_TQ_In)
3128 S += 'n';
3129 if (QT & Decl::OBJC_TQ_Inout)
3130 S += 'N';
3131 if (QT & Decl::OBJC_TQ_Out)
3132 S += 'o';
3133 if (QT & Decl::OBJC_TQ_Bycopy)
3134 S += 'O';
3135 if (QT & Decl::OBJC_TQ_Byref)
3136 S += 'R';
3137 if (QT & Decl::OBJC_TQ_Oneway)
3138 S += 'V';
3139}
3140
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003141void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003142 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
3143
3144 BuiltinVaListType = T;
3145}
3146
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003147void ASTContext::setObjCIdType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003148 ObjCIdTypedefType = T;
Steve Naroff7e219e42007-10-15 14:41:52 +00003149}
3150
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003151void ASTContext::setObjCSelType(QualType T) {
Douglas Gregor319ac892009-04-23 22:29:11 +00003152 ObjCSelType = T;
3153
3154 const TypedefType *TT = T->getAsTypedefType();
3155 if (!TT)
3156 return;
3157 TypedefDecl *TD = TT->getDecl();
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003158
3159 // typedef struct objc_selector *SEL;
Ted Kremenek6217b802009-07-29 21:53:49 +00003160 const PointerType *ptr = TD->getUnderlyingType()->getAs<PointerType>();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00003161 if (!ptr)
3162 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003163 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00003164 if (!rec)
3165 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003166 SelStructType = rec;
3167}
3168
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003169void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003170 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00003171}
3172
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003173void ASTContext::setObjCClassType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003174 ObjCClassTypedefType = T;
Anders Carlsson8baaca52007-10-31 02:53:19 +00003175}
3176
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003177void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
3178 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00003179 "'NSConstantString' type already set!");
3180
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003181 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00003182}
3183
Douglas Gregor7532dc62009-03-30 22:58:21 +00003184/// \brief Retrieve the template name that represents a qualified
3185/// template name such as \c std::vector.
3186TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
3187 bool TemplateKeyword,
3188 TemplateDecl *Template) {
3189 llvm::FoldingSetNodeID ID;
3190 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3191
3192 void *InsertPos = 0;
3193 QualifiedTemplateName *QTN =
3194 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3195 if (!QTN) {
3196 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3197 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3198 }
3199
3200 return TemplateName(QTN);
3201}
3202
Douglas Gregord99cbe62009-07-29 18:26:50 +00003203/// \brief Retrieve the template name that represents a qualified
3204/// template name such as \c std::vector.
3205TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
3206 bool TemplateKeyword,
3207 OverloadedFunctionDecl *Template) {
3208 llvm::FoldingSetNodeID ID;
3209 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3210
3211 void *InsertPos = 0;
3212 QualifiedTemplateName *QTN =
3213 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3214 if (!QTN) {
3215 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3216 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3217 }
3218
3219 return TemplateName(QTN);
3220}
3221
Douglas Gregor7532dc62009-03-30 22:58:21 +00003222/// \brief Retrieve the template name that represents a dependent
3223/// template name such as \c MetaFun::template apply.
3224TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
3225 const IdentifierInfo *Name) {
3226 assert(NNS->isDependent() && "Nested name specifier must be dependent");
3227
3228 llvm::FoldingSetNodeID ID;
3229 DependentTemplateName::Profile(ID, NNS, Name);
3230
3231 void *InsertPos = 0;
3232 DependentTemplateName *QTN =
3233 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3234
3235 if (QTN)
3236 return TemplateName(QTN);
3237
3238 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3239 if (CanonNNS == NNS) {
3240 QTN = new (*this,4) DependentTemplateName(NNS, Name);
3241 } else {
3242 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
3243 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
3244 }
3245
3246 DependentTemplateNames.InsertNode(QTN, InsertPos);
3247 return TemplateName(QTN);
3248}
3249
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003250/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00003251/// TargetInfo, produce the corresponding type. The unsigned @p Type
3252/// is actually a value of type @c TargetInfo::IntType.
3253QualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003254 switch (Type) {
3255 case TargetInfo::NoInt: return QualType();
3256 case TargetInfo::SignedShort: return ShortTy;
3257 case TargetInfo::UnsignedShort: return UnsignedShortTy;
3258 case TargetInfo::SignedInt: return IntTy;
3259 case TargetInfo::UnsignedInt: return UnsignedIntTy;
3260 case TargetInfo::SignedLong: return LongTy;
3261 case TargetInfo::UnsignedLong: return UnsignedLongTy;
3262 case TargetInfo::SignedLongLong: return LongLongTy;
3263 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
3264 }
3265
3266 assert(false && "Unhandled TargetInfo::IntType value");
Daniel Dunbarb3ac5432008-11-11 01:16:00 +00003267 return QualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003268}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003269
3270//===----------------------------------------------------------------------===//
3271// Type Predicates.
3272//===----------------------------------------------------------------------===//
3273
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003274/// isObjCNSObjectType - Return true if this is an NSObject object using
3275/// NSObject attribute on a c-style pointer type.
3276/// FIXME - Make it work directly on types.
Steve Narofff4954562009-07-16 15:41:00 +00003277/// FIXME: Move to Type.
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003278///
3279bool ASTContext::isObjCNSObjectType(QualType Ty) const {
3280 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
3281 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003282 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003283 return true;
3284 }
3285 return false;
3286}
3287
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003288/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
3289/// garbage collection attribute.
3290///
3291QualType::GCAttrTypes ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
Chris Lattnerb7d25532009-02-18 22:53:11 +00003292 QualType::GCAttrTypes GCAttrs = QualType::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003293 if (getLangOptions().ObjC1 &&
3294 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00003295 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003296 // Default behavious under objective-c's gc is for objective-c pointers
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003297 // (or pointers to them) be treated as though they were declared
3298 // as __strong.
3299 if (GCAttrs == QualType::GCNone) {
Steve Narofff4954562009-07-16 15:41:00 +00003300 if (Ty->isObjCObjectPointerType())
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003301 GCAttrs = QualType::Strong;
3302 else if (Ty->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00003303 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003304 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00003305 // Non-pointers have none gc'able attribute regardless of the attribute
3306 // set on them.
Steve Narofff4954562009-07-16 15:41:00 +00003307 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
Fariborz Jahanianc2112182009-04-11 00:00:54 +00003308 return QualType::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003309 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00003310 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003311}
3312
Chris Lattner6ac46a42008-04-07 06:51:04 +00003313//===----------------------------------------------------------------------===//
3314// Type Compatibility Testing
3315//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00003316
Chris Lattner6ac46a42008-04-07 06:51:04 +00003317/// areCompatVectorTypes - Return true if the two specified vector types are
3318/// compatible.
3319static bool areCompatVectorTypes(const VectorType *LHS,
3320 const VectorType *RHS) {
3321 assert(LHS->isCanonical() && RHS->isCanonical());
3322 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00003323 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00003324}
3325
Steve Naroff4084c302009-07-23 01:01:38 +00003326//===----------------------------------------------------------------------===//
3327// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
3328//===----------------------------------------------------------------------===//
3329
3330/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
3331/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003332bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
3333 ObjCProtocolDecl *rProto) {
Steve Naroff4084c302009-07-23 01:01:38 +00003334 if (lProto == rProto)
3335 return true;
3336 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
3337 E = rProto->protocol_end(); PI != E; ++PI)
3338 if (ProtocolCompatibleWithProtocol(lProto, *PI))
3339 return true;
3340 return false;
3341}
3342
Steve Naroff4084c302009-07-23 01:01:38 +00003343/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
3344/// return true if lhs's protocols conform to rhs's protocol; false
3345/// otherwise.
3346bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
3347 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
3348 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
3349 return false;
3350}
3351
3352/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
3353/// ObjCQualifiedIDType.
3354bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
3355 bool compare) {
3356 // Allow id<P..> and an 'id' or void* type in all cases.
3357 if (lhs->isVoidPointerType() ||
3358 lhs->isObjCIdType() || lhs->isObjCClassType())
3359 return true;
3360 else if (rhs->isVoidPointerType() ||
3361 rhs->isObjCIdType() || rhs->isObjCClassType())
3362 return true;
3363
3364 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
3365 const ObjCObjectPointerType *rhsOPT = rhs->getAsObjCObjectPointerType();
3366
3367 if (!rhsOPT) return false;
3368
3369 if (rhsOPT->qual_empty()) {
3370 // If the RHS is a unqualified interface pointer "NSString*",
3371 // make sure we check the class hierarchy.
3372 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
3373 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3374 E = lhsQID->qual_end(); I != E; ++I) {
3375 // when comparing an id<P> on lhs with a static type on rhs,
3376 // see if static class implements all of id's protocols, directly or
3377 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003378 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00003379 return false;
3380 }
3381 }
3382 // If there are no qualifiers and no interface, we have an 'id'.
3383 return true;
3384 }
3385 // Both the right and left sides have qualifiers.
3386 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3387 E = lhsQID->qual_end(); I != E; ++I) {
3388 ObjCProtocolDecl *lhsProto = *I;
3389 bool match = false;
3390
3391 // when comparing an id<P> on lhs with a static type on rhs,
3392 // see if static class implements all of id's protocols, directly or
3393 // through its super class and categories.
3394 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
3395 E = rhsOPT->qual_end(); J != E; ++J) {
3396 ObjCProtocolDecl *rhsProto = *J;
3397 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
3398 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
3399 match = true;
3400 break;
3401 }
3402 }
3403 // If the RHS is a qualified interface pointer "NSString<P>*",
3404 // make sure we check the class hierarchy.
3405 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
3406 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3407 E = lhsQID->qual_end(); I != E; ++I) {
3408 // when comparing an id<P> on lhs with a static type on rhs,
3409 // see if static class implements all of id's protocols, directly or
3410 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003411 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00003412 match = true;
3413 break;
3414 }
3415 }
3416 }
3417 if (!match)
3418 return false;
3419 }
3420
3421 return true;
3422 }
3423
3424 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
3425 assert(rhsQID && "One of the LHS/RHS should be id<x>");
3426
3427 if (const ObjCObjectPointerType *lhsOPT =
3428 lhs->getAsObjCInterfacePointerType()) {
3429 if (lhsOPT->qual_empty()) {
3430 bool match = false;
3431 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
3432 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
3433 E = rhsQID->qual_end(); I != E; ++I) {
3434 // when comparing an id<P> on lhs with a static type on rhs,
3435 // see if static class implements all of id's protocols, directly or
3436 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003437 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00003438 match = true;
3439 break;
3440 }
3441 }
3442 if (!match)
3443 return false;
3444 }
3445 return true;
3446 }
3447 // Both the right and left sides have qualifiers.
3448 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
3449 E = lhsOPT->qual_end(); I != E; ++I) {
3450 ObjCProtocolDecl *lhsProto = *I;
3451 bool match = false;
3452
3453 // when comparing an id<P> on lhs with a static type on rhs,
3454 // see if static class implements all of id's protocols, directly or
3455 // through its super class and categories.
3456 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
3457 E = rhsQID->qual_end(); J != E; ++J) {
3458 ObjCProtocolDecl *rhsProto = *J;
3459 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
3460 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
3461 match = true;
3462 break;
3463 }
3464 }
3465 if (!match)
3466 return false;
3467 }
3468 return true;
3469 }
3470 return false;
3471}
3472
Eli Friedman3d815e72008-08-22 00:56:42 +00003473/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00003474/// compatible for assignment from RHS to LHS. This handles validation of any
3475/// protocol qualifiers on the LHS or RHS.
3476///
Steve Naroff14108da2009-07-10 23:34:53 +00003477bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
3478 const ObjCObjectPointerType *RHSOPT) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003479 // If either type represents the built-in 'id' or 'Class' types, return true.
3480 if (LHSOPT->isObjCBuiltinType() || RHSOPT->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00003481 return true;
3482
Steve Naroff4084c302009-07-23 01:01:38 +00003483 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
3484 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
3485 QualType(RHSOPT,0),
3486 false);
3487
Steve Naroff14108da2009-07-10 23:34:53 +00003488 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
3489 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
Steve Naroff4084c302009-07-23 01:01:38 +00003490 if (LHS && RHS) // We have 2 user-defined types.
3491 return canAssignObjCInterfaces(LHS, RHS);
3492
3493 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00003494}
3495
Eli Friedman3d815e72008-08-22 00:56:42 +00003496bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
3497 const ObjCInterfaceType *RHS) {
Chris Lattner6ac46a42008-04-07 06:51:04 +00003498 // Verify that the base decls are compatible: the RHS must be a subclass of
3499 // the LHS.
3500 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
3501 return false;
3502
3503 // RHS must have a superset of the protocols in the LHS. If the LHS is not
3504 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00003505 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00003506 return true;
3507
3508 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
3509 // isn't a superset.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00003510 if (RHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00003511 return true; // FIXME: should return false!
3512
Steve Naroffc15cb2a2009-07-18 15:33:26 +00003513 for (ObjCInterfaceType::qual_iterator LHSPI = LHS->qual_begin(),
3514 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003515 LHSPI != LHSPE; LHSPI++) {
3516 bool RHSImplementsProtocol = false;
3517
3518 // If the RHS doesn't implement the protocol on the left, the types
3519 // are incompatible.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00003520 for (ObjCInterfaceType::qual_iterator RHSPI = RHS->qual_begin(),
Steve Naroff4084c302009-07-23 01:01:38 +00003521 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00003522 RHSPI != RHSPE; RHSPI++) {
3523 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003524 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00003525 break;
3526 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003527 }
3528 // FIXME: For better diagnostics, consider passing back the protocol name.
3529 if (!RHSImplementsProtocol)
3530 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00003531 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003532 // The RHS implements all protocols listed on the LHS.
3533 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00003534}
3535
Steve Naroff389bf462009-02-12 17:52:19 +00003536bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
3537 // get the "pointed to" types
Steve Naroff14108da2009-07-10 23:34:53 +00003538 const ObjCObjectPointerType *LHSOPT = LHS->getAsObjCObjectPointerType();
3539 const ObjCObjectPointerType *RHSOPT = RHS->getAsObjCObjectPointerType();
Steve Naroff389bf462009-02-12 17:52:19 +00003540
Steve Naroff14108da2009-07-10 23:34:53 +00003541 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00003542 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00003543
3544 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
3545 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00003546}
3547
Steve Naroffec0550f2007-10-15 20:41:53 +00003548/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
3549/// both shall have the identically qualified version of a compatible type.
3550/// C99 6.2.7p1: Two types have compatible types if their types are the
3551/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman3d815e72008-08-22 00:56:42 +00003552bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
3553 return !mergeTypes(LHS, RHS).isNull();
3554}
3555
3556QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
3557 const FunctionType *lbase = lhs->getAsFunctionType();
3558 const FunctionType *rbase = rhs->getAsFunctionType();
Douglas Gregor72564e72009-02-26 23:50:07 +00003559 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
3560 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00003561 bool allLTypes = true;
3562 bool allRTypes = true;
3563
3564 // Check return type
3565 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
3566 if (retType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00003567 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
3568 allLTypes = false;
3569 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
3570 allRTypes = false;
Mike Stump6dcbc292009-07-25 23:24:03 +00003571 // FIXME: double check this
Mike Stump24556362009-07-25 21:26:53 +00003572 bool NoReturn = lbase->getNoReturnAttr() || rbase->getNoReturnAttr();
3573 if (NoReturn != lbase->getNoReturnAttr())
3574 allLTypes = false;
3575 if (NoReturn != rbase->getNoReturnAttr())
3576 allRTypes = false;
3577
Eli Friedman3d815e72008-08-22 00:56:42 +00003578 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00003579 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
3580 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00003581 unsigned lproto_nargs = lproto->getNumArgs();
3582 unsigned rproto_nargs = rproto->getNumArgs();
3583
3584 // Compatible functions must have the same number of arguments
3585 if (lproto_nargs != rproto_nargs)
3586 return QualType();
3587
3588 // Variadic and non-variadic functions aren't compatible
3589 if (lproto->isVariadic() != rproto->isVariadic())
3590 return QualType();
3591
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003592 if (lproto->getTypeQuals() != rproto->getTypeQuals())
3593 return QualType();
3594
Eli Friedman3d815e72008-08-22 00:56:42 +00003595 // Check argument compatibility
3596 llvm::SmallVector<QualType, 10> types;
3597 for (unsigned i = 0; i < lproto_nargs; i++) {
3598 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
3599 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
3600 QualType argtype = mergeTypes(largtype, rargtype);
3601 if (argtype.isNull()) return QualType();
3602 types.push_back(argtype);
Chris Lattner61710852008-10-05 17:34:18 +00003603 if (getCanonicalType(argtype) != getCanonicalType(largtype))
3604 allLTypes = false;
3605 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
3606 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00003607 }
3608 if (allLTypes) return lhs;
3609 if (allRTypes) return rhs;
3610 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump24556362009-07-25 21:26:53 +00003611 lproto->isVariadic(), lproto->getTypeQuals(),
3612 NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00003613 }
3614
3615 if (lproto) allRTypes = false;
3616 if (rproto) allLTypes = false;
3617
Douglas Gregor72564e72009-02-26 23:50:07 +00003618 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00003619 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00003620 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00003621 if (proto->isVariadic()) return QualType();
3622 // Check that the types are compatible with the types that
3623 // would result from default argument promotions (C99 6.7.5.3p15).
3624 // The only types actually affected are promotable integer
3625 // types and floats, which would be passed as a different
3626 // type depending on whether the prototype is visible.
3627 unsigned proto_nargs = proto->getNumArgs();
3628 for (unsigned i = 0; i < proto_nargs; ++i) {
3629 QualType argTy = proto->getArgType(i);
3630 if (argTy->isPromotableIntegerType() ||
3631 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
3632 return QualType();
3633 }
3634
3635 if (allLTypes) return lhs;
3636 if (allRTypes) return rhs;
3637 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump2d3c1912009-07-27 00:44:23 +00003638 proto->getNumArgs(), proto->isVariadic(),
3639 proto->getTypeQuals(), NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00003640 }
3641
3642 if (allLTypes) return lhs;
3643 if (allRTypes) return rhs;
Mike Stump24556362009-07-25 21:26:53 +00003644 return getFunctionNoProtoType(retType, NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00003645}
3646
3647QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
Bill Wendling43d69752007-12-03 07:33:35 +00003648 // C++ [expr]: If an expression initially has the type "reference to T", the
3649 // type is adjusted to "T" prior to any further analysis, the expression
3650 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003651 // expression is an lvalue unless the reference is an rvalue reference and
3652 // the expression is a function call (possibly inside parentheses).
Eli Friedman3d815e72008-08-22 00:56:42 +00003653 // FIXME: C++ shouldn't be going through here! The rules are different
3654 // enough that they should be handled separately.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003655 // FIXME: Merging of lvalue and rvalue references is incorrect. C++ *really*
3656 // shouldn't be going through here!
Ted Kremenek6217b802009-07-29 21:53:49 +00003657 if (const ReferenceType *RT = LHS->getAs<ReferenceType>())
Chris Lattnerc4e40592008-04-07 04:07:56 +00003658 LHS = RT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003659 if (const ReferenceType *RT = RHS->getAs<ReferenceType>())
Chris Lattnerc4e40592008-04-07 04:07:56 +00003660 RHS = RT->getPointeeType();
Chris Lattnerf3692dc2008-04-07 05:37:56 +00003661
Eli Friedman3d815e72008-08-22 00:56:42 +00003662 QualType LHSCan = getCanonicalType(LHS),
3663 RHSCan = getCanonicalType(RHS);
3664
3665 // If two types are identical, they are compatible.
3666 if (LHSCan == RHSCan)
3667 return LHS;
3668
3669 // If the qualifiers are different, the types aren't compatible
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003670 // Note that we handle extended qualifiers later, in the
3671 // case for ExtQualType.
3672 if (LHSCan.getCVRQualifiers() != RHSCan.getCVRQualifiers())
Eli Friedman3d815e72008-08-22 00:56:42 +00003673 return QualType();
3674
Eli Friedman852d63b2009-06-01 01:22:52 +00003675 Type::TypeClass LHSClass = LHSCan->getTypeClass();
3676 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00003677
Chris Lattner1adb8832008-01-14 05:45:46 +00003678 // We want to consider the two function types to be the same for these
3679 // comparisons, just force one to the other.
3680 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
3681 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00003682
Eli Friedman07d25872009-06-02 05:28:56 +00003683 // Strip off objc_gc attributes off the top level so they can be merged.
3684 // This is a complete mess, but the attribute itself doesn't make much sense.
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003685 if (RHSClass == Type::ExtQual) {
Eli Friedman07d25872009-06-02 05:28:56 +00003686 QualType::GCAttrTypes GCAttr = RHSCan.getObjCGCAttr();
3687 if (GCAttr != QualType::GCNone) {
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003688 QualType::GCAttrTypes GCLHSAttr = LHSCan.getObjCGCAttr();
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003689 // __weak attribute must appear on both declarations.
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003690 // __strong attribue is redundant if other decl is an objective-c
3691 // object pointer (or decorated with __strong attribute); otherwise
3692 // issue error.
3693 if ((GCAttr == QualType::Weak && GCLHSAttr != GCAttr) ||
3694 (GCAttr == QualType::Strong && GCLHSAttr != GCAttr &&
Steve Naroff14108da2009-07-10 23:34:53 +00003695 !LHSCan->isObjCObjectPointerType()))
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003696 return QualType();
3697
Eli Friedman07d25872009-06-02 05:28:56 +00003698 RHS = QualType(cast<ExtQualType>(RHS.getDesugaredType())->getBaseType(),
3699 RHS.getCVRQualifiers());
3700 QualType Result = mergeTypes(LHS, RHS);
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003701 if (!Result.isNull()) {
3702 if (Result.getObjCGCAttr() == QualType::GCNone)
3703 Result = getObjCGCQualType(Result, GCAttr);
3704 else if (Result.getObjCGCAttr() != GCAttr)
3705 Result = QualType();
3706 }
Eli Friedman07d25872009-06-02 05:28:56 +00003707 return Result;
3708 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003709 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003710 if (LHSClass == Type::ExtQual) {
Eli Friedman07d25872009-06-02 05:28:56 +00003711 QualType::GCAttrTypes GCAttr = LHSCan.getObjCGCAttr();
3712 if (GCAttr != QualType::GCNone) {
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003713 QualType::GCAttrTypes GCRHSAttr = RHSCan.getObjCGCAttr();
3714 // __weak attribute must appear on both declarations. __strong
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003715 // __strong attribue is redundant if other decl is an objective-c
3716 // object pointer (or decorated with __strong attribute); otherwise
3717 // issue error.
3718 if ((GCAttr == QualType::Weak && GCRHSAttr != GCAttr) ||
3719 (GCAttr == QualType::Strong && GCRHSAttr != GCAttr &&
Steve Naroff14108da2009-07-10 23:34:53 +00003720 !RHSCan->isObjCObjectPointerType()))
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003721 return QualType();
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003722
Eli Friedman07d25872009-06-02 05:28:56 +00003723 LHS = QualType(cast<ExtQualType>(LHS.getDesugaredType())->getBaseType(),
3724 LHS.getCVRQualifiers());
3725 QualType Result = mergeTypes(LHS, RHS);
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003726 if (!Result.isNull()) {
3727 if (Result.getObjCGCAttr() == QualType::GCNone)
3728 Result = getObjCGCQualType(Result, GCAttr);
3729 else if (Result.getObjCGCAttr() != GCAttr)
3730 Result = QualType();
3731 }
Eli Friedman354e53d2009-06-02 07:45:37 +00003732 return Result;
Eli Friedman07d25872009-06-02 05:28:56 +00003733 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003734 }
3735
Eli Friedman4c721d32008-02-12 08:23:06 +00003736 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00003737 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
3738 LHSClass = Type::ConstantArray;
3739 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
3740 RHSClass = Type::ConstantArray;
Steve Naroffec0550f2007-10-15 20:41:53 +00003741
Nate Begeman213541a2008-04-18 23:10:10 +00003742 // Canonicalize ExtVector -> Vector.
3743 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
3744 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Chris Lattnera36a61f2008-04-07 05:43:21 +00003745
3746 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00003747 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00003748 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
3749 // a signed integer type, or an unsigned integer type.
Eli Friedman3d815e72008-08-22 00:56:42 +00003750 if (const EnumType* ETy = LHS->getAsEnumType()) {
3751 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
3752 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00003753 }
Eli Friedman3d815e72008-08-22 00:56:42 +00003754 if (const EnumType* ETy = RHS->getAsEnumType()) {
3755 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
3756 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00003757 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003758
Eli Friedman3d815e72008-08-22 00:56:42 +00003759 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00003760 }
Eli Friedman3d815e72008-08-22 00:56:42 +00003761
Steve Naroff4a746782008-01-09 22:43:08 +00003762 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00003763 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00003764#define TYPE(Class, Base)
3765#define ABSTRACT_TYPE(Class, Base)
3766#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3767#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3768#include "clang/AST/TypeNodes.def"
3769 assert(false && "Non-canonical and dependent types shouldn't get here");
3770 return QualType();
3771
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003772 case Type::LValueReference:
3773 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00003774 case Type::MemberPointer:
3775 assert(false && "C++ should never be in mergeTypes");
3776 return QualType();
3777
3778 case Type::IncompleteArray:
3779 case Type::VariableArray:
3780 case Type::FunctionProto:
3781 case Type::ExtVector:
Douglas Gregor72564e72009-02-26 23:50:07 +00003782 assert(false && "Types are eliminated above");
3783 return QualType();
3784
Chris Lattner1adb8832008-01-14 05:45:46 +00003785 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00003786 {
3787 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00003788 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
3789 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Eli Friedman3d815e72008-08-22 00:56:42 +00003790 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
3791 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00003792 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00003793 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00003794 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00003795 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00003796 return getPointerType(ResultType);
3797 }
Steve Naroffc0febd52008-12-10 17:49:55 +00003798 case Type::BlockPointer:
3799 {
3800 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00003801 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
3802 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Steve Naroffc0febd52008-12-10 17:49:55 +00003803 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
3804 if (ResultType.isNull()) return QualType();
3805 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
3806 return LHS;
3807 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
3808 return RHS;
3809 return getBlockPointerType(ResultType);
3810 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003811 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00003812 {
3813 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
3814 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
3815 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
3816 return QualType();
3817
3818 QualType LHSElem = getAsArrayType(LHS)->getElementType();
3819 QualType RHSElem = getAsArrayType(RHS)->getElementType();
3820 QualType ResultType = mergeTypes(LHSElem, RHSElem);
3821 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00003822 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3823 return LHS;
3824 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3825 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00003826 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
3827 ArrayType::ArraySizeModifier(), 0);
3828 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
3829 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00003830 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
3831 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00003832 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3833 return LHS;
3834 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3835 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00003836 if (LVAT) {
3837 // FIXME: This isn't correct! But tricky to implement because
3838 // the array's size has to be the size of LHS, but the type
3839 // has to be different.
3840 return LHS;
3841 }
3842 if (RVAT) {
3843 // FIXME: This isn't correct! But tricky to implement because
3844 // the array's size has to be the size of RHS, but the type
3845 // has to be different.
3846 return RHS;
3847 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00003848 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
3849 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003850 return getIncompleteArrayType(ResultType,
3851 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00003852 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003853 case Type::FunctionNoProto:
Eli Friedman3d815e72008-08-22 00:56:42 +00003854 return mergeFunctionTypes(LHS, RHS);
Douglas Gregor72564e72009-02-26 23:50:07 +00003855 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00003856 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00003857 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00003858 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00003859 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00003860 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00003861 case Type::Complex:
3862 // Distinct complex types are incompatible.
3863 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00003864 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003865 // FIXME: The merged type should be an ExtVector!
Eli Friedman3d815e72008-08-22 00:56:42 +00003866 if (areCompatVectorTypes(LHS->getAsVectorType(), RHS->getAsVectorType()))
3867 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00003868 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00003869 case Type::ObjCInterface: {
Steve Naroff5fd659d2009-02-21 16:18:07 +00003870 // Check if the interfaces are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003871 // FIXME: This should be type compatibility, e.g. whether
3872 // "LHS x; RHS x;" at global scope is legal.
Steve Naroff5fd659d2009-02-21 16:18:07 +00003873 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
3874 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
3875 if (LHSIface && RHSIface &&
3876 canAssignObjCInterfaces(LHSIface, RHSIface))
3877 return LHS;
3878
Eli Friedman3d815e72008-08-22 00:56:42 +00003879 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00003880 }
Steve Naroff14108da2009-07-10 23:34:53 +00003881 case Type::ObjCObjectPointer: {
Steve Naroff14108da2009-07-10 23:34:53 +00003882 if (canAssignObjCInterfaces(LHS->getAsObjCObjectPointerType(),
3883 RHS->getAsObjCObjectPointerType()))
3884 return LHS;
3885
Steve Naroffbc76dd02008-12-10 22:14:21 +00003886 return QualType();
Steve Naroff14108da2009-07-10 23:34:53 +00003887 }
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003888 case Type::FixedWidthInt:
3889 // Distinct fixed-width integers are not compatible.
3890 return QualType();
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003891 case Type::ExtQual:
3892 // FIXME: ExtQual types can be compatible even if they're not
3893 // identical!
3894 return QualType();
3895 // First attempt at an implementation, but I'm not really sure it's
3896 // right...
3897#if 0
3898 ExtQualType* LQual = cast<ExtQualType>(LHSCan);
3899 ExtQualType* RQual = cast<ExtQualType>(RHSCan);
3900 if (LQual->getAddressSpace() != RQual->getAddressSpace() ||
3901 LQual->getObjCGCAttr() != RQual->getObjCGCAttr())
3902 return QualType();
3903 QualType LHSBase, RHSBase, ResultType, ResCanUnqual;
3904 LHSBase = QualType(LQual->getBaseType(), 0);
3905 RHSBase = QualType(RQual->getBaseType(), 0);
3906 ResultType = mergeTypes(LHSBase, RHSBase);
3907 if (ResultType.isNull()) return QualType();
3908 ResCanUnqual = getCanonicalType(ResultType).getUnqualifiedType();
3909 if (LHSCan.getUnqualifiedType() == ResCanUnqual)
3910 return LHS;
3911 if (RHSCan.getUnqualifiedType() == ResCanUnqual)
3912 return RHS;
3913 ResultType = getAddrSpaceQualType(ResultType, LQual->getAddressSpace());
3914 ResultType = getObjCGCQualType(ResultType, LQual->getObjCGCAttr());
3915 ResultType.setCVRQualifiers(LHSCan.getCVRQualifiers());
3916 return ResultType;
3917#endif
Douglas Gregor7532dc62009-03-30 22:58:21 +00003918
3919 case Type::TemplateSpecialization:
3920 assert(false && "Dependent types have no size");
3921 break;
Steve Naroffec0550f2007-10-15 20:41:53 +00003922 }
Douglas Gregor72564e72009-02-26 23:50:07 +00003923
3924 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00003925}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00003926
Chris Lattner5426bf62008-04-07 07:01:58 +00003927//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00003928// Integer Predicates
3929//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00003930
Eli Friedmanad74a752008-06-28 06:23:08 +00003931unsigned ASTContext::getIntWidth(QualType T) {
3932 if (T == BoolTy)
3933 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00003934 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T)) {
3935 return FWIT->getWidth();
3936 }
3937 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00003938 return (unsigned)getTypeSize(T);
3939}
3940
3941QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
3942 assert(T->isSignedIntegerType() && "Unexpected type");
3943 if (const EnumType* ETy = T->getAsEnumType())
3944 T = ETy->getDecl()->getIntegerType();
3945 const BuiltinType* BTy = T->getAsBuiltinType();
3946 assert (BTy && "Unexpected signed integer type");
3947 switch (BTy->getKind()) {
3948 case BuiltinType::Char_S:
3949 case BuiltinType::SChar:
3950 return UnsignedCharTy;
3951 case BuiltinType::Short:
3952 return UnsignedShortTy;
3953 case BuiltinType::Int:
3954 return UnsignedIntTy;
3955 case BuiltinType::Long:
3956 return UnsignedLongTy;
3957 case BuiltinType::LongLong:
3958 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00003959 case BuiltinType::Int128:
3960 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00003961 default:
3962 assert(0 && "Unexpected signed integer type");
3963 return QualType();
3964 }
3965}
3966
Douglas Gregor2cf26342009-04-09 22:27:44 +00003967ExternalASTSource::~ExternalASTSource() { }
3968
3969void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00003970
3971
3972//===----------------------------------------------------------------------===//
3973// Builtin Type Computation
3974//===----------------------------------------------------------------------===//
3975
3976/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
3977/// pointer over the consumed characters. This returns the resultant type.
3978static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
3979 ASTContext::GetBuiltinTypeError &Error,
3980 bool AllowTypeModifiers = true) {
3981 // Modifiers.
3982 int HowLong = 0;
3983 bool Signed = false, Unsigned = false;
3984
3985 // Read the modifiers first.
3986 bool Done = false;
3987 while (!Done) {
3988 switch (*Str++) {
3989 default: Done = true; --Str; break;
3990 case 'S':
3991 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
3992 assert(!Signed && "Can't use 'S' modifier multiple times!");
3993 Signed = true;
3994 break;
3995 case 'U':
3996 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
3997 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
3998 Unsigned = true;
3999 break;
4000 case 'L':
4001 assert(HowLong <= 2 && "Can't have LLLL modifier");
4002 ++HowLong;
4003 break;
4004 }
4005 }
4006
4007 QualType Type;
4008
4009 // Read the base type.
4010 switch (*Str++) {
4011 default: assert(0 && "Unknown builtin type letter!");
4012 case 'v':
4013 assert(HowLong == 0 && !Signed && !Unsigned &&
4014 "Bad modifiers used with 'v'!");
4015 Type = Context.VoidTy;
4016 break;
4017 case 'f':
4018 assert(HowLong == 0 && !Signed && !Unsigned &&
4019 "Bad modifiers used with 'f'!");
4020 Type = Context.FloatTy;
4021 break;
4022 case 'd':
4023 assert(HowLong < 2 && !Signed && !Unsigned &&
4024 "Bad modifiers used with 'd'!");
4025 if (HowLong)
4026 Type = Context.LongDoubleTy;
4027 else
4028 Type = Context.DoubleTy;
4029 break;
4030 case 's':
4031 assert(HowLong == 0 && "Bad modifiers used with 's'!");
4032 if (Unsigned)
4033 Type = Context.UnsignedShortTy;
4034 else
4035 Type = Context.ShortTy;
4036 break;
4037 case 'i':
4038 if (HowLong == 3)
4039 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
4040 else if (HowLong == 2)
4041 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
4042 else if (HowLong == 1)
4043 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
4044 else
4045 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
4046 break;
4047 case 'c':
4048 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
4049 if (Signed)
4050 Type = Context.SignedCharTy;
4051 else if (Unsigned)
4052 Type = Context.UnsignedCharTy;
4053 else
4054 Type = Context.CharTy;
4055 break;
4056 case 'b': // boolean
4057 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
4058 Type = Context.BoolTy;
4059 break;
4060 case 'z': // size_t.
4061 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
4062 Type = Context.getSizeType();
4063 break;
4064 case 'F':
4065 Type = Context.getCFConstantStringType();
4066 break;
4067 case 'a':
4068 Type = Context.getBuiltinVaListType();
4069 assert(!Type.isNull() && "builtin va list type not initialized!");
4070 break;
4071 case 'A':
4072 // This is a "reference" to a va_list; however, what exactly
4073 // this means depends on how va_list is defined. There are two
4074 // different kinds of va_list: ones passed by value, and ones
4075 // passed by reference. An example of a by-value va_list is
4076 // x86, where va_list is a char*. An example of by-ref va_list
4077 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
4078 // we want this argument to be a char*&; for x86-64, we want
4079 // it to be a __va_list_tag*.
4080 Type = Context.getBuiltinVaListType();
4081 assert(!Type.isNull() && "builtin va list type not initialized!");
4082 if (Type->isArrayType()) {
4083 Type = Context.getArrayDecayedType(Type);
4084 } else {
4085 Type = Context.getLValueReferenceType(Type);
4086 }
4087 break;
4088 case 'V': {
4089 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00004090 unsigned NumElements = strtoul(Str, &End, 10);
4091 assert(End != Str && "Missing vector size");
4092
4093 Str = End;
4094
4095 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4096 Type = Context.getVectorType(ElementType, NumElements);
4097 break;
4098 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004099 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00004100 Type = Context.getFILEType();
4101 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004102 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00004103 return QualType();
4104 }
Mike Stumpfd612db2009-07-28 23:47:15 +00004105 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004106 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00004107 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00004108 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00004109 else
4110 Type = Context.getjmp_bufType();
4111
Mike Stumpfd612db2009-07-28 23:47:15 +00004112 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004113 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00004114 return QualType();
4115 }
4116 break;
Mike Stump782fa302009-07-28 02:25:19 +00004117 }
Chris Lattner86df27b2009-06-14 00:45:47 +00004118
4119 if (!AllowTypeModifiers)
4120 return Type;
4121
4122 Done = false;
4123 while (!Done) {
4124 switch (*Str++) {
4125 default: Done = true; --Str; break;
4126 case '*':
4127 Type = Context.getPointerType(Type);
4128 break;
4129 case '&':
4130 Type = Context.getLValueReferenceType(Type);
4131 break;
4132 // FIXME: There's no way to have a built-in with an rvalue ref arg.
4133 case 'C':
4134 Type = Type.getQualifiedType(QualType::Const);
4135 break;
4136 }
4137 }
4138
4139 return Type;
4140}
4141
4142/// GetBuiltinType - Return the type for the specified builtin.
4143QualType ASTContext::GetBuiltinType(unsigned id,
4144 GetBuiltinTypeError &Error) {
4145 const char *TypeStr = BuiltinInfo.GetTypeString(id);
4146
4147 llvm::SmallVector<QualType, 8> ArgTypes;
4148
4149 Error = GE_None;
4150 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
4151 if (Error != GE_None)
4152 return QualType();
4153 while (TypeStr[0] && TypeStr[0] != '.') {
4154 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
4155 if (Error != GE_None)
4156 return QualType();
4157
4158 // Do array -> pointer decay. The builtin should use the decayed type.
4159 if (Ty->isArrayType())
4160 Ty = getArrayDecayedType(Ty);
4161
4162 ArgTypes.push_back(Ty);
4163 }
4164
4165 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
4166 "'.' should only occur at end of builtin type list!");
4167
4168 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
4169 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
4170 return getFunctionNoProtoType(ResType);
4171 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
4172 TypeStr[0] == '.', 0);
4173}
Eli Friedmana95d7572009-08-19 07:44:53 +00004174
4175QualType
4176ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
4177 // Perform the usual unary conversions. We do this early so that
4178 // integral promotions to "int" can allow us to exit early, in the
4179 // lhs == rhs check. Also, for conversion purposes, we ignore any
4180 // qualifiers. For example, "const float" and "float" are
4181 // equivalent.
4182 if (lhs->isPromotableIntegerType())
4183 lhs = getPromotedIntegerType(lhs);
4184 else
4185 lhs = lhs.getUnqualifiedType();
4186 if (rhs->isPromotableIntegerType())
4187 rhs = getPromotedIntegerType(rhs);
4188 else
4189 rhs = rhs.getUnqualifiedType();
4190
4191 // If both types are identical, no conversion is needed.
4192 if (lhs == rhs)
4193 return lhs;
4194
4195 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
4196 // The caller can deal with this (e.g. pointer + int).
4197 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
4198 return lhs;
4199
4200 // At this point, we have two different arithmetic types.
4201
4202 // Handle complex types first (C99 6.3.1.8p1).
4203 if (lhs->isComplexType() || rhs->isComplexType()) {
4204 // if we have an integer operand, the result is the complex type.
4205 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
4206 // convert the rhs to the lhs complex type.
4207 return lhs;
4208 }
4209 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
4210 // convert the lhs to the rhs complex type.
4211 return rhs;
4212 }
4213 // This handles complex/complex, complex/float, or float/complex.
4214 // When both operands are complex, the shorter operand is converted to the
4215 // type of the longer, and that is the type of the result. This corresponds
4216 // to what is done when combining two real floating-point operands.
4217 // The fun begins when size promotion occur across type domains.
4218 // From H&S 6.3.4: When one operand is complex and the other is a real
4219 // floating-point type, the less precise type is converted, within it's
4220 // real or complex domain, to the precision of the other type. For example,
4221 // when combining a "long double" with a "double _Complex", the
4222 // "double _Complex" is promoted to "long double _Complex".
4223 int result = getFloatingTypeOrder(lhs, rhs);
4224
4225 if (result > 0) { // The left side is bigger, convert rhs.
4226 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
4227 } else if (result < 0) { // The right side is bigger, convert lhs.
4228 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
4229 }
4230 // At this point, lhs and rhs have the same rank/size. Now, make sure the
4231 // domains match. This is a requirement for our implementation, C99
4232 // does not require this promotion.
4233 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
4234 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
4235 return rhs;
4236 } else { // handle "_Complex double, double".
4237 return lhs;
4238 }
4239 }
4240 return lhs; // The domain/size match exactly.
4241 }
4242 // Now handle "real" floating types (i.e. float, double, long double).
4243 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
4244 // if we have an integer operand, the result is the real floating type.
4245 if (rhs->isIntegerType()) {
4246 // convert rhs to the lhs floating point type.
4247 return lhs;
4248 }
4249 if (rhs->isComplexIntegerType()) {
4250 // convert rhs to the complex floating point type.
4251 return getComplexType(lhs);
4252 }
4253 if (lhs->isIntegerType()) {
4254 // convert lhs to the rhs floating point type.
4255 return rhs;
4256 }
4257 if (lhs->isComplexIntegerType()) {
4258 // convert lhs to the complex floating point type.
4259 return getComplexType(rhs);
4260 }
4261 // We have two real floating types, float/complex combos were handled above.
4262 // Convert the smaller operand to the bigger result.
4263 int result = getFloatingTypeOrder(lhs, rhs);
4264 if (result > 0) // convert the rhs
4265 return lhs;
4266 assert(result < 0 && "illegal float comparison");
4267 return rhs; // convert the lhs
4268 }
4269 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
4270 // Handle GCC complex int extension.
4271 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
4272 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
4273
4274 if (lhsComplexInt && rhsComplexInt) {
4275 if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
4276 rhsComplexInt->getElementType()) >= 0)
4277 return lhs; // convert the rhs
4278 return rhs;
4279 } else if (lhsComplexInt && rhs->isIntegerType()) {
4280 // convert the rhs to the lhs complex type.
4281 return lhs;
4282 } else if (rhsComplexInt && lhs->isIntegerType()) {
4283 // convert the lhs to the rhs complex type.
4284 return rhs;
4285 }
4286 }
4287 // Finally, we have two differing integer types.
4288 // The rules for this case are in C99 6.3.1.8
4289 int compare = getIntegerTypeOrder(lhs, rhs);
4290 bool lhsSigned = lhs->isSignedIntegerType(),
4291 rhsSigned = rhs->isSignedIntegerType();
4292 QualType destType;
4293 if (lhsSigned == rhsSigned) {
4294 // Same signedness; use the higher-ranked type
4295 destType = compare >= 0 ? lhs : rhs;
4296 } else if (compare != (lhsSigned ? 1 : -1)) {
4297 // The unsigned type has greater than or equal rank to the
4298 // signed type, so use the unsigned type
4299 destType = lhsSigned ? rhs : lhs;
4300 } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
4301 // The two types are different widths; if we are here, that
4302 // means the signed type is larger than the unsigned type, so
4303 // use the signed type.
4304 destType = lhsSigned ? lhs : rhs;
4305 } else {
4306 // The signed type is higher-ranked than the unsigned type,
4307 // but isn't actually any bigger (like unsigned int and long
4308 // on most 32-bit systems). Use the unsigned type corresponding
4309 // to the signed type.
4310 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
4311 }
4312 return destType;
4313}