blob: f0ab845f7c1ae2b5eec1330d103cca1edc874003 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +000015#include "clang/AST/DeclCXX.h"
Steve Naroff980e5082007-10-01 19:00:59 +000016#include "clang/AST/DeclObjC.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000017#include "clang/AST/DeclTemplate.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000018#include "clang/AST/Expr.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000019#include "clang/AST/ExternalASTSource.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000020#include "clang/AST/RecordLayout.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000021#include "clang/Basic/Builtins.h"
Chris Lattnera9376d42009-03-28 03:45:20 +000022#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000023#include "clang/Basic/TargetInfo.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000024#include "llvm/ADT/StringExtras.h"
Nate Begeman6fe7c8a2009-01-18 06:42:49 +000025#include "llvm/Support/MathExtras.h"
Chris Lattner557c5b12009-03-28 04:27:18 +000026#include "llvm/Support/MemoryBuffer.h"
Anders Carlsson29445a02009-07-18 21:19:52 +000027#include "RecordLayoutBuilder.h"
28
Reid Spencer5f016e22007-07-11 17:01:13 +000029using namespace clang;
30
31enum FloatingRank {
32 FloatRank, DoubleRank, LongDoubleRank
33};
34
Chris Lattner61710852008-10-05 17:34:18 +000035ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
36 TargetInfo &t,
Daniel Dunbare91593e2008-08-11 04:54:23 +000037 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +000038 Builtin::Context &builtins,
39 bool FreeMem, unsigned size_reserve) :
Douglas Gregorab452ba2009-03-26 23:50:42 +000040 GlobalNestedNameSpecifier(0), CFConstantStringTypeDecl(0),
Mike Stump782fa302009-07-28 02:25:19 +000041 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
42 sigjmp_bufDecl(0), SourceMgr(SM), LangOpts(LOpts),
Douglas Gregor2e222532009-07-02 17:08:52 +000043 LoadedExternalComments(false), FreeMemory(FreeMem), Target(t),
44 Idents(idents), Selectors(sels),
Chris Lattnere4f21422009-06-30 01:26:17 +000045 BuiltinInfo(builtins), ExternalSource(0), PrintingPolicy(LOpts) {
David Chisnall0f436562009-08-17 16:35:33 +000046 ObjCIdRedefinitionType = QualType();
47 ObjCClassRedefinitionType = QualType();
Daniel Dunbare91593e2008-08-11 04:54:23 +000048 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +000049 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff14108da2009-07-10 23:34:53 +000050 InitBuiltinTypes();
Daniel Dunbare91593e2008-08-11 04:54:23 +000051}
52
Reid Spencer5f016e22007-07-11 17:01:13 +000053ASTContext::~ASTContext() {
54 // Deallocate all the types.
55 while (!Types.empty()) {
Ted Kremenek4b05b1d2008-05-21 16:38:54 +000056 Types.back()->Destroy(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +000057 Types.pop_back();
58 }
Eli Friedmanb26153c2008-05-27 03:08:09 +000059
Nuno Lopesb74668e2008-12-17 22:30:25 +000060 {
61 llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
62 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end();
63 while (I != E) {
64 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
65 delete R;
66 }
67 }
68
69 {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +000070 llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>::iterator
71 I = ObjCLayouts.begin(), E = ObjCLayouts.end();
Nuno Lopesb74668e2008-12-17 22:30:25 +000072 while (I != E) {
73 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
74 delete R;
75 }
76 }
77
Douglas Gregorab452ba2009-03-26 23:50:42 +000078 // Destroy nested-name-specifiers.
Douglas Gregor1ae0afa2009-03-27 23:54:10 +000079 for (llvm::FoldingSet<NestedNameSpecifier>::iterator
80 NNS = NestedNameSpecifiers.begin(),
81 NNSEnd = NestedNameSpecifiers.end();
Douglas Gregore7dcd782009-03-27 23:25:45 +000082 NNS != NNSEnd;
Douglas Gregor1ae0afa2009-03-27 23:54:10 +000083 /* Increment in loop */)
84 (*NNS++).Destroy(*this);
Douglas Gregorab452ba2009-03-26 23:50:42 +000085
86 if (GlobalNestedNameSpecifier)
87 GlobalNestedNameSpecifier->Destroy(*this);
88
Eli Friedmanb26153c2008-05-27 03:08:09 +000089 TUDecl->Destroy(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +000090}
91
Douglas Gregor2cf26342009-04-09 22:27:44 +000092void
93ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
94 ExternalSource.reset(Source.take());
95}
96
Reid Spencer5f016e22007-07-11 17:01:13 +000097void ASTContext::PrintStats() const {
98 fprintf(stderr, "*** AST Context Stats:\n");
99 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000100
Douglas Gregordbe833d2009-05-26 14:40:08 +0000101 unsigned counts[] = {
102#define TYPE(Name, Parent) 0,
103#define ABSTRACT_TYPE(Name, Parent)
104#include "clang/AST/TypeNodes.def"
105 0 // Extra
106 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000107
Reid Spencer5f016e22007-07-11 17:01:13 +0000108 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
109 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000110 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000111 }
112
Douglas Gregordbe833d2009-05-26 14:40:08 +0000113 unsigned Idx = 0;
114 unsigned TotalBytes = 0;
115#define TYPE(Name, Parent) \
116 if (counts[Idx]) \
117 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
118 TotalBytes += counts[Idx] * sizeof(Name##Type); \
119 ++Idx;
120#define ABSTRACT_TYPE(Name, Parent)
121#include "clang/AST/TypeNodes.def"
122
123 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregor2cf26342009-04-09 22:27:44 +0000124
125 if (ExternalSource.get()) {
126 fprintf(stderr, "\n");
127 ExternalSource->PrintStats();
128 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000129}
130
131
132void ASTContext::InitBuiltinType(QualType &R, BuiltinType::Kind K) {
Steve Narofff83820b2009-01-27 22:08:43 +0000133 Types.push_back((R = QualType(new (*this,8) BuiltinType(K),0)).getTypePtr());
Reid Spencer5f016e22007-07-11 17:01:13 +0000134}
135
Reid Spencer5f016e22007-07-11 17:01:13 +0000136void ASTContext::InitBuiltinTypes() {
137 assert(VoidTy.isNull() && "Context reinitialized?");
138
139 // C99 6.2.5p19.
140 InitBuiltinType(VoidTy, BuiltinType::Void);
141
142 // C99 6.2.5p2.
143 InitBuiltinType(BoolTy, BuiltinType::Bool);
144 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000145 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000146 InitBuiltinType(CharTy, BuiltinType::Char_S);
147 else
148 InitBuiltinType(CharTy, BuiltinType::Char_U);
149 // C99 6.2.5p4.
150 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
151 InitBuiltinType(ShortTy, BuiltinType::Short);
152 InitBuiltinType(IntTy, BuiltinType::Int);
153 InitBuiltinType(LongTy, BuiltinType::Long);
154 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
155
156 // C99 6.2.5p6.
157 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
158 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
159 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
160 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
161 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
162
163 // C99 6.2.5p10.
164 InitBuiltinType(FloatTy, BuiltinType::Float);
165 InitBuiltinType(DoubleTy, BuiltinType::Double);
166 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000167
Chris Lattner2df9ced2009-04-30 02:43:43 +0000168 // GNU extension, 128-bit integers.
169 InitBuiltinType(Int128Ty, BuiltinType::Int128);
170 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
171
Chris Lattner3a250322009-02-26 23:43:47 +0000172 if (LangOpts.CPlusPlus) // C++ 3.9.1p5
173 InitBuiltinType(WCharTy, BuiltinType::WChar);
174 else // C99
175 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000176
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000177 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
178 InitBuiltinType(Char16Ty, BuiltinType::Char16);
179 else // C99
180 Char16Ty = getFromTargetType(Target.getChar16Type());
181
182 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
183 InitBuiltinType(Char32Ty, BuiltinType::Char32);
184 else // C99
185 Char32Ty = getFromTargetType(Target.getChar32Type());
186
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000187 // Placeholder type for functions.
Douglas Gregor898574e2008-12-05 23:32:09 +0000188 InitBuiltinType(OverloadTy, BuiltinType::Overload);
189
190 // Placeholder type for type-dependent expressions whose type is
191 // completely unknown. No code should ever check a type against
192 // DependentTy and users should never see it; however, it is here to
193 // help diagnose failures to properly check for type-dependent
194 // expressions.
195 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000196
Anders Carlssone89d1592009-06-26 18:41:36 +0000197 // Placeholder type for C++0x auto declarations whose real type has
198 // not yet been deduced.
199 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
200
Reid Spencer5f016e22007-07-11 17:01:13 +0000201 // C99 6.2.5p11.
202 FloatComplexTy = getComplexType(FloatTy);
203 DoubleComplexTy = getComplexType(DoubleTy);
204 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000205
Steve Naroff7e219e42007-10-15 14:41:52 +0000206 BuiltinVaListType = QualType();
Anders Carlsson8baaca52007-10-31 02:53:19 +0000207
Steve Naroffde2e22d2009-07-15 18:40:39 +0000208 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
209 ObjCIdTypedefType = QualType();
210 ObjCClassTypedefType = QualType();
211
212 // Builtin types for 'id' and 'Class'.
213 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
214 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Steve Naroff14108da2009-07-10 23:34:53 +0000215
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000216 ObjCConstantStringType = QualType();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000217
218 // void * type
219 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000220
221 // nullptr type (C++0x 2.14.7)
222 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000223}
224
Douglas Gregor7caa6822009-07-24 20:34:43 +0000225VarDecl *ASTContext::getInstantiatedFromStaticDataMember(VarDecl *Var) {
226 assert(Var->isStaticDataMember() && "Not a static data member");
227 llvm::DenseMap<VarDecl *, VarDecl *>::iterator Pos
228 = InstantiatedFromStaticDataMember.find(Var);
229 if (Pos == InstantiatedFromStaticDataMember.end())
230 return 0;
231
232 return Pos->second;
233}
234
235void
236ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl) {
237 assert(Inst->isStaticDataMember() && "Not a static data member");
238 assert(Tmpl->isStaticDataMember() && "Not a static data member");
239 assert(!InstantiatedFromStaticDataMember[Inst] &&
240 "Already noted what static data member was instantiated from");
241 InstantiatedFromStaticDataMember[Inst] = Tmpl;
242}
243
Douglas Gregor2e222532009-07-02 17:08:52 +0000244namespace {
245 class BeforeInTranslationUnit
246 : std::binary_function<SourceRange, SourceRange, bool> {
247 SourceManager *SourceMgr;
248
249 public:
250 explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { }
251
252 bool operator()(SourceRange X, SourceRange Y) {
253 return SourceMgr->isBeforeInTranslationUnit(X.getBegin(), Y.getBegin());
254 }
255 };
256}
257
258/// \brief Determine whether the given comment is a Doxygen-style comment.
259///
260/// \param Start the start of the comment text.
261///
262/// \param End the end of the comment text.
263///
264/// \param Member whether we want to check whether this is a member comment
265/// (which requires a < after the Doxygen-comment delimiter). Otherwise,
266/// we only return true when we find a non-member comment.
267static bool
268isDoxygenComment(SourceManager &SourceMgr, SourceRange Comment,
269 bool Member = false) {
270 const char *BufferStart
271 = SourceMgr.getBufferData(SourceMgr.getFileID(Comment.getBegin())).first;
272 const char *Start = BufferStart + SourceMgr.getFileOffset(Comment.getBegin());
273 const char* End = BufferStart + SourceMgr.getFileOffset(Comment.getEnd());
274
275 if (End - Start < 4)
276 return false;
277
278 assert(Start[0] == '/' && "Not a comment?");
279 if (Start[1] == '*' && !(Start[2] == '!' || Start[2] == '*'))
280 return false;
281 if (Start[1] == '/' && !(Start[2] == '!' || Start[2] == '/'))
282 return false;
283
284 return (Start[3] == '<') == Member;
285}
286
287/// \brief Retrieve the comment associated with the given declaration, if
288/// it has one.
289const char *ASTContext::getCommentForDecl(const Decl *D) {
290 if (!D)
291 return 0;
292
293 // Check whether we have cached a comment string for this declaration
294 // already.
295 llvm::DenseMap<const Decl *, std::string>::iterator Pos
296 = DeclComments.find(D);
297 if (Pos != DeclComments.end())
298 return Pos->second.c_str();
299
300 // If we have an external AST source and have not yet loaded comments from
301 // that source, do so now.
302 if (ExternalSource && !LoadedExternalComments) {
303 std::vector<SourceRange> LoadedComments;
304 ExternalSource->ReadComments(LoadedComments);
305
306 if (!LoadedComments.empty())
307 Comments.insert(Comments.begin(), LoadedComments.begin(),
308 LoadedComments.end());
309
310 LoadedExternalComments = true;
311 }
312
313 // If there are no comments anywhere, we won't find anything.
314 if (Comments.empty())
315 return 0;
316
317 // If the declaration doesn't map directly to a location in a file, we
318 // can't find the comment.
319 SourceLocation DeclStartLoc = D->getLocStart();
320 if (DeclStartLoc.isInvalid() || !DeclStartLoc.isFileID())
321 return 0;
322
323 // Find the comment that occurs just before this declaration.
324 std::vector<SourceRange>::iterator LastComment
325 = std::lower_bound(Comments.begin(), Comments.end(),
326 SourceRange(DeclStartLoc),
327 BeforeInTranslationUnit(&SourceMgr));
328
329 // Decompose the location for the start of the declaration and find the
330 // beginning of the file buffer.
331 std::pair<FileID, unsigned> DeclStartDecomp
332 = SourceMgr.getDecomposedLoc(DeclStartLoc);
333 const char *FileBufferStart
334 = SourceMgr.getBufferData(DeclStartDecomp.first).first;
335
336 // First check whether we have a comment for a member.
337 if (LastComment != Comments.end() &&
338 !isa<TagDecl>(D) && !isa<NamespaceDecl>(D) &&
339 isDoxygenComment(SourceMgr, *LastComment, true)) {
340 std::pair<FileID, unsigned> LastCommentEndDecomp
341 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
342 if (DeclStartDecomp.first == LastCommentEndDecomp.first &&
343 SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second)
344 == SourceMgr.getLineNumber(LastCommentEndDecomp.first,
345 LastCommentEndDecomp.second)) {
346 // The Doxygen member comment comes after the declaration starts and
347 // is on the same line and in the same file as the declaration. This
348 // is the comment we want.
349 std::string &Result = DeclComments[D];
350 Result.append(FileBufferStart +
351 SourceMgr.getFileOffset(LastComment->getBegin()),
352 FileBufferStart + LastCommentEndDecomp.second + 1);
353 return Result.c_str();
354 }
355 }
356
357 if (LastComment == Comments.begin())
358 return 0;
359 --LastComment;
360
361 // Decompose the end of the comment.
362 std::pair<FileID, unsigned> LastCommentEndDecomp
363 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
364
365 // If the comment and the declaration aren't in the same file, then they
366 // aren't related.
367 if (DeclStartDecomp.first != LastCommentEndDecomp.first)
368 return 0;
369
370 // Check that we actually have a Doxygen comment.
371 if (!isDoxygenComment(SourceMgr, *LastComment))
372 return 0;
373
374 // Compute the starting line for the declaration and for the end of the
375 // comment (this is expensive).
376 unsigned DeclStartLine
377 = SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second);
378 unsigned CommentEndLine
379 = SourceMgr.getLineNumber(LastCommentEndDecomp.first,
380 LastCommentEndDecomp.second);
381
382 // If the comment does not end on the line prior to the declaration, then
383 // the comment is not associated with the declaration at all.
384 if (CommentEndLine + 1 != DeclStartLine)
385 return 0;
386
387 // We have a comment, but there may be more comments on the previous lines.
388 // Keep looking so long as the comments are still Doxygen comments and are
389 // still adjacent.
390 unsigned ExpectedLine
391 = SourceMgr.getSpellingLineNumber(LastComment->getBegin()) - 1;
392 std::vector<SourceRange>::iterator FirstComment = LastComment;
393 while (FirstComment != Comments.begin()) {
394 // Look at the previous comment
395 --FirstComment;
396 std::pair<FileID, unsigned> Decomp
397 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
398
399 // If this previous comment is in a different file, we're done.
400 if (Decomp.first != DeclStartDecomp.first) {
401 ++FirstComment;
402 break;
403 }
404
405 // If this comment is not a Doxygen comment, we're done.
406 if (!isDoxygenComment(SourceMgr, *FirstComment)) {
407 ++FirstComment;
408 break;
409 }
410
411 // If the line number is not what we expected, we're done.
412 unsigned Line = SourceMgr.getLineNumber(Decomp.first, Decomp.second);
413 if (Line != ExpectedLine) {
414 ++FirstComment;
415 break;
416 }
417
418 // Set the next expected line number.
419 ExpectedLine
420 = SourceMgr.getSpellingLineNumber(FirstComment->getBegin()) - 1;
421 }
422
423 // The iterator range [FirstComment, LastComment] contains all of the
424 // BCPL comments that, together, are associated with this declaration.
425 // Form a single comment block string for this declaration that concatenates
426 // all of these comments.
427 std::string &Result = DeclComments[D];
428 while (FirstComment != LastComment) {
429 std::pair<FileID, unsigned> DecompStart
430 = SourceMgr.getDecomposedLoc(FirstComment->getBegin());
431 std::pair<FileID, unsigned> DecompEnd
432 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
433 Result.append(FileBufferStart + DecompStart.second,
434 FileBufferStart + DecompEnd.second + 1);
435 ++FirstComment;
436 }
437
438 // Append the last comment line.
439 Result.append(FileBufferStart +
440 SourceMgr.getFileOffset(LastComment->getBegin()),
441 FileBufferStart + LastCommentEndDecomp.second + 1);
442 return Result.c_str();
443}
444
Chris Lattner464175b2007-07-18 17:52:12 +0000445//===----------------------------------------------------------------------===//
446// Type Sizing and Analysis
447//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000448
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000449/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
450/// scalar floating point type.
451const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
452 const BuiltinType *BT = T->getAsBuiltinType();
453 assert(BT && "Not a floating point type!");
454 switch (BT->getKind()) {
455 default: assert(0 && "Not a floating point type!");
456 case BuiltinType::Float: return Target.getFloatFormat();
457 case BuiltinType::Double: return Target.getDoubleFormat();
458 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
459 }
460}
461
Chris Lattneraf707ab2009-01-24 21:53:27 +0000462/// getDeclAlign - Return a conservative estimate of the alignment of the
463/// specified decl. Note that bitfields do not have a valid alignment, so
464/// this method will assert on them.
Daniel Dunbarb7d08442009-02-17 22:16:19 +0000465unsigned ASTContext::getDeclAlignInBytes(const Decl *D) {
Eli Friedmandcdafb62009-02-22 02:56:25 +0000466 unsigned Align = Target.getCharWidth();
467
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000468 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
Eli Friedmandcdafb62009-02-22 02:56:25 +0000469 Align = std::max(Align, AA->getAlignment());
470
Chris Lattneraf707ab2009-01-24 21:53:27 +0000471 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
472 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000473 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000474 unsigned AS = RT->getPointeeType().getAddressSpace();
Anders Carlssonf0930232009-04-10 04:52:36 +0000475 Align = Target.getPointerAlign(AS);
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000476 } else if (!T->isIncompleteType() && !T->isFunctionType()) {
477 // Incomplete or function types default to 1.
Eli Friedmandcdafb62009-02-22 02:56:25 +0000478 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
479 T = cast<ArrayType>(T)->getElementType();
480
481 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
482 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000483 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000484
485 return Align / Target.getCharWidth();
Chris Lattneraf707ab2009-01-24 21:53:27 +0000486}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000487
Chris Lattnera7674d82007-07-13 22:13:22 +0000488/// getTypeSize - Return the size of the specified type, in bits. This method
489/// does not work on incomplete types.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000490std::pair<uint64_t, unsigned>
Daniel Dunbar1d751182008-11-08 05:48:37 +0000491ASTContext::getTypeInfo(const Type *T) {
Mike Stump5e301002009-02-27 18:32:39 +0000492 uint64_t Width=0;
493 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000494 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000495#define TYPE(Class, Base)
496#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000497#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000498#define DEPENDENT_TYPE(Class, Base) case Type::Class:
499#include "clang/AST/TypeNodes.def"
Douglas Gregor18857642009-04-30 17:32:17 +0000500 assert(false && "Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000501 break;
502
Chris Lattner692233e2007-07-13 22:27:08 +0000503 case Type::FunctionNoProto:
504 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000505 // GCC extension: alignof(function) = 32 bits
506 Width = 0;
507 Align = 32;
508 break;
509
Douglas Gregor72564e72009-02-26 23:50:07 +0000510 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000511 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000512 Width = 0;
513 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
514 break;
515
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +0000516 case Type::ConstantArrayWithExpr:
517 case Type::ConstantArrayWithoutExpr:
Steve Narofffb22d962007-08-30 01:06:46 +0000518 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000519 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Steve Narofffb22d962007-08-30 01:06:46 +0000520
Chris Lattner98be4942008-03-05 18:54:05 +0000521 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000522 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000523 Align = EltInfo.second;
524 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000525 }
Nate Begeman213541a2008-04-18 23:10:10 +0000526 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000527 case Type::Vector: {
528 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000529 getTypeInfo(cast<VectorType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000530 Width = EltInfo.first*cast<VectorType>(T)->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000531 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000532 // If the alignment is not a power of 2, round up to the next power of 2.
533 // This happens for non-power-of-2 length vectors.
534 // FIXME: this should probably be a target property.
535 Align = 1 << llvm::Log2_32_Ceil(Align);
Chris Lattner030d8842007-07-19 22:06:24 +0000536 break;
537 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000538
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000539 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000540 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000541 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000542 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000543 // GCC extension: alignof(void) = 8 bits.
544 Width = 0;
545 Align = 8;
546 break;
547
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000548 case BuiltinType::Bool:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000549 Width = Target.getBoolWidth();
550 Align = Target.getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000551 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000552 case BuiltinType::Char_S:
553 case BuiltinType::Char_U:
554 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000555 case BuiltinType::SChar:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000556 Width = Target.getCharWidth();
557 Align = Target.getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000558 break;
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000559 case BuiltinType::WChar:
560 Width = Target.getWCharWidth();
561 Align = Target.getWCharAlign();
562 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000563 case BuiltinType::Char16:
564 Width = Target.getChar16Width();
565 Align = Target.getChar16Align();
566 break;
567 case BuiltinType::Char32:
568 Width = Target.getChar32Width();
569 Align = Target.getChar32Align();
570 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000571 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000572 case BuiltinType::Short:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000573 Width = Target.getShortWidth();
574 Align = Target.getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000575 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000576 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000577 case BuiltinType::Int:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000578 Width = Target.getIntWidth();
579 Align = Target.getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000580 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000581 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000582 case BuiltinType::Long:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000583 Width = Target.getLongWidth();
584 Align = Target.getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000585 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000586 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000587 case BuiltinType::LongLong:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000588 Width = Target.getLongLongWidth();
589 Align = Target.getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000590 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000591 case BuiltinType::Int128:
592 case BuiltinType::UInt128:
593 Width = 128;
594 Align = 128; // int128_t is 128-bit aligned on all targets.
595 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000596 case BuiltinType::Float:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000597 Width = Target.getFloatWidth();
598 Align = Target.getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000599 break;
600 case BuiltinType::Double:
Chris Lattner5426bf62008-04-07 07:01:58 +0000601 Width = Target.getDoubleWidth();
602 Align = Target.getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000603 break;
604 case BuiltinType::LongDouble:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000605 Width = Target.getLongDoubleWidth();
606 Align = Target.getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000607 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000608 case BuiltinType::NullPtr:
609 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
610 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000611 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000612 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000613 break;
Eli Friedmanf98aba32009-02-13 02:31:07 +0000614 case Type::FixedWidthInt:
615 // FIXME: This isn't precisely correct; the width/alignment should depend
616 // on the available types for the target
617 Width = cast<FixedWidthIntType>(T)->getWidth();
Chris Lattner736166b2009-02-15 21:20:13 +0000618 Width = std::max(llvm::NextPowerOf2(Width - 1), (uint64_t)8);
Eli Friedmanf98aba32009-02-13 02:31:07 +0000619 Align = Width;
620 break;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000621 case Type::ExtQual:
Chris Lattner98be4942008-03-05 18:54:05 +0000622 // FIXME: Pointers into different addr spaces could have different sizes and
623 // alignment requirements: getPointerInfo should take an AddrSpace.
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000624 return getTypeInfo(QualType(cast<ExtQualType>(T)->getBaseType(), 0));
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000625 case Type::ObjCObjectPointer:
Chris Lattner5426bf62008-04-07 07:01:58 +0000626 Width = Target.getPointerWidth(0);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000627 Align = Target.getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000628 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000629 case Type::BlockPointer: {
630 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
631 Width = Target.getPointerWidth(AS);
632 Align = Target.getPointerAlign(AS);
633 break;
634 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000635 case Type::Pointer: {
636 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner5426bf62008-04-07 07:01:58 +0000637 Width = Target.getPointerWidth(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000638 Align = Target.getPointerAlign(AS);
639 break;
640 }
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000641 case Type::LValueReference:
642 case Type::RValueReference:
Chris Lattner7ab2ed82007-07-13 22:16:13 +0000643 // "When applied to a reference or a reference type, the result is the size
Chris Lattner5d2a6302007-07-18 18:26:58 +0000644 // of the referenced type." C++98 5.3.3p2: expr.sizeof.
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000645 // FIXME: This is wrong for struct layout: a reference in a struct has
646 // pointer size.
Chris Lattnerbdcd6372008-04-02 17:35:06 +0000647 return getTypeInfo(cast<ReferenceType>(T)->getPointeeType());
Sebastian Redlf30208a2009-01-24 21:16:55 +0000648 case Type::MemberPointer: {
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000649 // FIXME: This is ABI dependent. We use the Itanium C++ ABI.
650 // http://www.codesourcery.com/public/cxx-abi/abi.html#member-pointers
651 // If we ever want to support other ABIs this needs to be abstracted.
652
Sebastian Redlf30208a2009-01-24 21:16:55 +0000653 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000654 std::pair<uint64_t, unsigned> PtrDiffInfo =
655 getTypeInfo(getPointerDiffType());
656 Width = PtrDiffInfo.first;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000657 if (Pointee->isFunctionType())
658 Width *= 2;
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000659 Align = PtrDiffInfo.second;
660 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000661 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000662 case Type::Complex: {
663 // Complex types have the same alignment as their elements, but twice the
664 // size.
665 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000666 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000667 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000668 Align = EltInfo.second;
669 break;
670 }
Devang Patel44a3dde2008-06-04 21:54:36 +0000671 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000672 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000673 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
674 Width = Layout.getSize();
675 Align = Layout.getAlignment();
676 break;
677 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000678 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000679 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000680 const TagType *TT = cast<TagType>(T);
681
682 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner8389eab2008-08-09 21:35:13 +0000683 Width = 1;
684 Align = 1;
685 break;
686 }
687
Daniel Dunbar1d751182008-11-08 05:48:37 +0000688 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000689 return getTypeInfo(ET->getDecl()->getIntegerType());
690
Daniel Dunbar1d751182008-11-08 05:48:37 +0000691 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000692 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
693 Width = Layout.getSize();
694 Align = Layout.getAlignment();
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000695 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000696 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000697
Douglas Gregor18857642009-04-30 17:32:17 +0000698 case Type::Typedef: {
699 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000700 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
Douglas Gregor18857642009-04-30 17:32:17 +0000701 Align = Aligned->getAlignment();
702 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
703 } else
704 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregor7532dc62009-03-30 22:58:21 +0000705 break;
Chris Lattner71763312008-04-06 22:05:18 +0000706 }
Douglas Gregor18857642009-04-30 17:32:17 +0000707
708 case Type::TypeOfExpr:
709 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
710 .getTypePtr());
711
712 case Type::TypeOf:
713 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
714
Anders Carlsson395b4752009-06-24 19:06:50 +0000715 case Type::Decltype:
716 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
717 .getTypePtr());
718
Douglas Gregor18857642009-04-30 17:32:17 +0000719 case Type::QualifiedName:
720 return getTypeInfo(cast<QualifiedNameType>(T)->getNamedType().getTypePtr());
721
722 case Type::TemplateSpecialization:
723 assert(getCanonicalType(T) != T &&
724 "Cannot request the size of a dependent type");
725 // FIXME: this is likely to be wrong once we support template
726 // aliases, since a template alias could refer to a typedef that
727 // has an __aligned__ attribute on it.
728 return getTypeInfo(getCanonicalType(T));
729 }
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000730
Chris Lattner464175b2007-07-18 17:52:12 +0000731 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000732 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +0000733}
734
Chris Lattner34ebde42009-01-27 18:08:34 +0000735/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
736/// type for the current target in bits. This can be different than the ABI
737/// alignment in cases where it is beneficial for performance to overalign
738/// a data type.
739unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
740 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +0000741
742 // Double and long long should be naturally aligned if possible.
743 if (const ComplexType* CT = T->getAsComplexType())
744 T = CT->getElementType().getTypePtr();
745 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
746 T->isSpecificBuiltinType(BuiltinType::LongLong))
747 return std::max(ABIAlign, (unsigned)getTypeSize(T));
748
Chris Lattner34ebde42009-01-27 18:08:34 +0000749 return ABIAlign;
750}
751
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000752static void CollectLocalObjCIvars(ASTContext *Ctx,
753 const ObjCInterfaceDecl *OI,
754 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000755 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
756 E = OI->ivar_end(); I != E; ++I) {
Chris Lattnerf1690852009-03-31 08:48:01 +0000757 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000758 if (!IVDecl->isInvalidDecl())
759 Fields.push_back(cast<FieldDecl>(IVDecl));
760 }
761}
762
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000763void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
764 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
765 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
766 CollectObjCIvars(SuperClass, Fields);
767 CollectLocalObjCIvars(this, OI, Fields);
768}
769
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000770/// ShallowCollectObjCIvars -
771/// Collect all ivars, including those synthesized, in the current class.
772///
773void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
774 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars,
775 bool CollectSynthesized) {
776 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
777 E = OI->ivar_end(); I != E; ++I) {
778 Ivars.push_back(*I);
779 }
780 if (CollectSynthesized)
781 CollectSynthesizedIvars(OI, Ivars);
782}
783
Fariborz Jahanian98200742009-05-12 18:14:29 +0000784void ASTContext::CollectProtocolSynthesizedIvars(const ObjCProtocolDecl *PD,
785 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000786 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
787 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian98200742009-05-12 18:14:29 +0000788 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
789 Ivars.push_back(Ivar);
790
791 // Also look into nested protocols.
792 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
793 E = PD->protocol_end(); P != E; ++P)
794 CollectProtocolSynthesizedIvars(*P, Ivars);
795}
796
797/// CollectSynthesizedIvars -
798/// This routine collect synthesized ivars for the designated class.
799///
800void ASTContext::CollectSynthesizedIvars(const ObjCInterfaceDecl *OI,
801 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000802 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
803 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian98200742009-05-12 18:14:29 +0000804 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
805 Ivars.push_back(Ivar);
806 }
807 // Also look into interface's protocol list for properties declared
808 // in the protocol and whose ivars are synthesized.
809 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
810 PE = OI->protocol_end(); P != PE; ++P) {
811 ObjCProtocolDecl *PD = (*P);
812 CollectProtocolSynthesizedIvars(PD, Ivars);
813 }
814}
815
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000816unsigned ASTContext::CountProtocolSynthesizedIvars(const ObjCProtocolDecl *PD) {
817 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000818 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
819 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000820 if ((*I)->getPropertyIvarDecl())
821 ++count;
822
823 // Also look into nested protocols.
824 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
825 E = PD->protocol_end(); P != E; ++P)
826 count += CountProtocolSynthesizedIvars(*P);
827 return count;
828}
829
830unsigned ASTContext::CountSynthesizedIvars(const ObjCInterfaceDecl *OI)
831{
832 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000833 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
834 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000835 if ((*I)->getPropertyIvarDecl())
836 ++count;
837 }
838 // Also look into interface's protocol list for properties declared
839 // in the protocol and whose ivars are synthesized.
840 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
841 PE = OI->protocol_end(); P != PE; ++P) {
842 ObjCProtocolDecl *PD = (*P);
843 count += CountProtocolSynthesizedIvars(PD);
844 }
845 return count;
846}
847
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +0000848/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
849ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
850 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
851 I = ObjCImpls.find(D);
852 if (I != ObjCImpls.end())
853 return cast<ObjCImplementationDecl>(I->second);
854 return 0;
855}
856/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
857ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
858 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
859 I = ObjCImpls.find(D);
860 if (I != ObjCImpls.end())
861 return cast<ObjCCategoryImplDecl>(I->second);
862 return 0;
863}
864
865/// \brief Set the implementation of ObjCInterfaceDecl.
866void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
867 ObjCImplementationDecl *ImplD) {
868 assert(IFaceD && ImplD && "Passed null params");
869 ObjCImpls[IFaceD] = ImplD;
870}
871/// \brief Set the implementation of ObjCCategoryDecl.
872void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
873 ObjCCategoryImplDecl *ImplD) {
874 assert(CatD && ImplD && "Passed null params");
875 ObjCImpls[CatD] = ImplD;
876}
877
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000878/// getInterfaceLayoutImpl - Get or compute information about the
879/// layout of the given interface.
880///
881/// \param Impl - If given, also include the layout of the interface's
882/// implementation. This may differ by including synthesized ivars.
Devang Patel44a3dde2008-06-04 21:54:36 +0000883const ASTRecordLayout &
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000884ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
885 const ObjCImplementationDecl *Impl) {
Daniel Dunbar532d4da2009-05-03 13:15:50 +0000886 assert(!D->isForwardDecl() && "Invalid interface decl!");
887
Devang Patel44a3dde2008-06-04 21:54:36 +0000888 // Look up this layout, if already laid out, return what we have.
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000889 ObjCContainerDecl *Key =
890 Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
891 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
892 return *Entry;
Devang Patel44a3dde2008-06-04 21:54:36 +0000893
Daniel Dunbar453addb2009-05-03 11:16:44 +0000894 // Add in synthesized ivar count if laying out an implementation.
895 if (Impl) {
Anders Carlsson29445a02009-07-18 21:19:52 +0000896 unsigned FieldCount = D->ivar_size();
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000897 unsigned SynthCount = CountSynthesizedIvars(D);
898 FieldCount += SynthCount;
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000899 // If there aren't any sythesized ivars then reuse the interface
Daniel Dunbar453addb2009-05-03 11:16:44 +0000900 // entry. Note we can't cache this because we simply free all
901 // entries later; however we shouldn't look up implementations
902 // frequently.
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000903 if (SynthCount == 0)
Daniel Dunbar453addb2009-05-03 11:16:44 +0000904 return getObjCLayout(D, 0);
905 }
906
Anders Carlsson29445a02009-07-18 21:19:52 +0000907 const ASTRecordLayout *NewEntry =
908 ASTRecordLayoutBuilder::ComputeLayout(*this, D, Impl);
909 ObjCLayouts[Key] = NewEntry;
910
Devang Patel44a3dde2008-06-04 21:54:36 +0000911 return *NewEntry;
912}
913
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000914const ASTRecordLayout &
915ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
916 return getObjCLayout(D, 0);
917}
918
919const ASTRecordLayout &
920ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
921 return getObjCLayout(D->getClassInterface(), D);
922}
923
Devang Patel88a981b2007-11-01 19:11:01 +0000924/// getASTRecordLayout - Get or compute information about the layout of the
Chris Lattner464175b2007-07-18 17:52:12 +0000925/// specified record (struct/union/class), which indicates its size and field
926/// position information.
Chris Lattner98be4942008-03-05 18:54:05 +0000927const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +0000928 D = D->getDefinition(*this);
929 assert(D && "Cannot get layout of forward declarations!");
Eli Friedman4bd998b2008-05-30 09:31:38 +0000930
Chris Lattner464175b2007-07-18 17:52:12 +0000931 // Look up this layout, if already laid out, return what we have.
Eli Friedmanab22c432009-07-22 20:29:16 +0000932 // Note that we can't save a reference to the entry because this function
933 // is recursive.
934 const ASTRecordLayout *Entry = ASTRecordLayouts[D];
Chris Lattner464175b2007-07-18 17:52:12 +0000935 if (Entry) return *Entry;
Eli Friedman4bd998b2008-05-30 09:31:38 +0000936
Anders Carlsson29445a02009-07-18 21:19:52 +0000937 const ASTRecordLayout *NewEntry =
938 ASTRecordLayoutBuilder::ComputeLayout(*this, D);
Eli Friedmanab22c432009-07-22 20:29:16 +0000939 ASTRecordLayouts[D] = NewEntry;
Anders Carlsson29445a02009-07-18 21:19:52 +0000940
Chris Lattner5d2a6302007-07-18 18:26:58 +0000941 return *NewEntry;
Chris Lattner464175b2007-07-18 17:52:12 +0000942}
943
Chris Lattnera7674d82007-07-13 22:13:22 +0000944//===----------------------------------------------------------------------===//
945// Type creation/memoization methods
946//===----------------------------------------------------------------------===//
947
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000948QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerf52ab252008-04-06 22:59:24 +0000949 QualType CanT = getCanonicalType(T);
950 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +0000951 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +0000952
953 // If we are composing extended qualifiers together, merge together into one
954 // ExtQualType node.
955 unsigned CVRQuals = T.getCVRQualifiers();
956 QualType::GCAttrTypes GCAttr = QualType::GCNone;
957 Type *TypeNode = T.getTypePtr();
Chris Lattnerf46699c2008-02-20 20:55:12 +0000958
Chris Lattnerb7d25532009-02-18 22:53:11 +0000959 if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
960 // If this type already has an address space specified, it cannot get
961 // another one.
962 assert(EQT->getAddressSpace() == 0 &&
963 "Type cannot be in multiple addr spaces!");
964 GCAttr = EQT->getObjCGCAttr();
965 TypeNode = EQT->getBaseType();
966 }
Chris Lattnerf46699c2008-02-20 20:55:12 +0000967
Chris Lattnerb7d25532009-02-18 22:53:11 +0000968 // Check if we've already instantiated this type.
Christopher Lambebb97e92008-02-04 02:31:56 +0000969 llvm::FoldingSetNodeID ID;
Mike Stump24556362009-07-25 21:26:53 +0000970 ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
Christopher Lambebb97e92008-02-04 02:31:56 +0000971 void *InsertPos = 0;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000972 if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattnerb7d25532009-02-18 22:53:11 +0000973 return QualType(EXTQy, CVRQuals);
974
Christopher Lambebb97e92008-02-04 02:31:56 +0000975 // If the base type isn't canonical, this won't be a canonical type either,
976 // so fill in the canonical type field.
977 QualType Canonical;
Chris Lattnerb7d25532009-02-18 22:53:11 +0000978 if (!TypeNode->isCanonical()) {
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000979 Canonical = getAddrSpaceQualType(CanT, AddressSpace);
Christopher Lambebb97e92008-02-04 02:31:56 +0000980
Chris Lattnerb7d25532009-02-18 22:53:11 +0000981 // Update InsertPos, the previous call could have invalidated it.
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000982 ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +0000983 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Christopher Lambebb97e92008-02-04 02:31:56 +0000984 }
Chris Lattnerb7d25532009-02-18 22:53:11 +0000985 ExtQualType *New =
986 new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000987 ExtQualTypes.InsertNode(New, InsertPos);
Christopher Lambebb97e92008-02-04 02:31:56 +0000988 Types.push_back(New);
Chris Lattnerb7d25532009-02-18 22:53:11 +0000989 return QualType(New, CVRQuals);
Christopher Lambebb97e92008-02-04 02:31:56 +0000990}
991
Chris Lattnerb7d25532009-02-18 22:53:11 +0000992QualType ASTContext::getObjCGCQualType(QualType T,
993 QualType::GCAttrTypes GCAttr) {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000994 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +0000995 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +0000996 return T;
997
Fariborz Jahanian4027cd12009-06-03 17:15:17 +0000998 if (T->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000999 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001000 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001001 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1002 return getPointerType(ResultType);
1003 }
1004 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00001005 // If we are composing extended qualifiers together, merge together into one
1006 // ExtQualType node.
1007 unsigned CVRQuals = T.getCVRQualifiers();
1008 Type *TypeNode = T.getTypePtr();
1009 unsigned AddressSpace = 0;
1010
1011 if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
Mike Stump24556362009-07-25 21:26:53 +00001012 // If this type already has an ObjCGC specified, it cannot get
Chris Lattnerb7d25532009-02-18 22:53:11 +00001013 // another one.
1014 assert(EQT->getObjCGCAttr() == QualType::GCNone &&
Mike Stump24556362009-07-25 21:26:53 +00001015 "Type cannot have multiple ObjCGCs!");
Chris Lattnerb7d25532009-02-18 22:53:11 +00001016 AddressSpace = EQT->getAddressSpace();
1017 TypeNode = EQT->getBaseType();
1018 }
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001019
1020 // Check if we've already instantiated an gc qual'd type of this type.
1021 llvm::FoldingSetNodeID ID;
Mike Stump24556362009-07-25 21:26:53 +00001022 ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001023 void *InsertPos = 0;
1024 if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattnerb7d25532009-02-18 22:53:11 +00001025 return QualType(EXTQy, CVRQuals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001026
1027 // If the base type isn't canonical, this won't be a canonical type either,
1028 // so fill in the canonical type field.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00001029 // FIXME: Isn't this also not canonical if the base type is a array
1030 // or pointer type? I can't find any documentation for objc_gc, though...
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001031 QualType Canonical;
1032 if (!T->isCanonical()) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00001033 Canonical = getObjCGCQualType(CanT, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001034
Chris Lattnerb7d25532009-02-18 22:53:11 +00001035 // Update InsertPos, the previous call could have invalidated it.
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001036 ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
1037 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1038 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00001039 ExtQualType *New =
1040 new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001041 ExtQualTypes.InsertNode(New, InsertPos);
1042 Types.push_back(New);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001043 return QualType(New, CVRQuals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001044}
Chris Lattnera7674d82007-07-13 22:13:22 +00001045
Mike Stump24556362009-07-25 21:26:53 +00001046QualType ASTContext::getNoReturnType(QualType T) {
Mike Stump6dcbc292009-07-25 23:24:03 +00001047 QualifierSet qs;
1048 qs.strip(T);
Mike Stump24556362009-07-25 21:26:53 +00001049 if (T->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001050 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Mike Stump24556362009-07-25 21:26:53 +00001051 QualType ResultType = getNoReturnType(Pointee);
Mike Stump6dcbc292009-07-25 23:24:03 +00001052 ResultType = getPointerType(ResultType);
1053 ResultType.setCVRQualifiers(T.getCVRQualifiers());
1054 return qs.apply(ResultType, *this);
Mike Stump24556362009-07-25 21:26:53 +00001055 }
1056 if (T->isBlockPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001057 QualType Pointee = T->getAs<BlockPointerType>()->getPointeeType();
Mike Stump24556362009-07-25 21:26:53 +00001058 QualType ResultType = getNoReturnType(Pointee);
Mike Stump6dcbc292009-07-25 23:24:03 +00001059 ResultType = getBlockPointerType(ResultType);
1060 ResultType.setCVRQualifiers(T.getCVRQualifiers());
1061 return qs.apply(ResultType, *this);
Mike Stump24556362009-07-25 21:26:53 +00001062 }
1063 if (!T->isFunctionType())
1064 assert(0 && "can't noreturn qualify non-pointer to function or block type");
1065
Mike Stumpe24aea22009-07-27 22:25:19 +00001066 if (const FunctionNoProtoType *F = T->getAsFunctionNoProtoType()) {
Mike Stump24556362009-07-25 21:26:53 +00001067 return getFunctionNoProtoType(F->getResultType(), true);
1068 }
Mike Stumpe24aea22009-07-27 22:25:19 +00001069 const FunctionProtoType *F = T->getAsFunctionProtoType();
Mike Stump24556362009-07-25 21:26:53 +00001070 return getFunctionType(F->getResultType(), F->arg_type_begin(),
1071 F->getNumArgs(), F->isVariadic(), F->getTypeQuals(),
1072 F->hasExceptionSpec(), F->hasAnyExceptionSpec(),
1073 F->getNumExceptions(), F->exception_begin(), true);
1074}
1075
Reid Spencer5f016e22007-07-11 17:01:13 +00001076/// getComplexType - Return the uniqued reference to the type for a complex
1077/// number with the specified element type.
1078QualType ASTContext::getComplexType(QualType T) {
1079 // Unique pointers, to guarantee there is only one pointer of a particular
1080 // structure.
1081 llvm::FoldingSetNodeID ID;
1082 ComplexType::Profile(ID, T);
1083
1084 void *InsertPos = 0;
1085 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1086 return QualType(CT, 0);
1087
1088 // If the pointee type isn't canonical, this won't be a canonical type either,
1089 // so fill in the canonical type field.
1090 QualType Canonical;
1091 if (!T->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001092 Canonical = getComplexType(getCanonicalType(T));
Reid Spencer5f016e22007-07-11 17:01:13 +00001093
1094 // Get the new insert position for the node we care about.
1095 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001096 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001097 }
Steve Narofff83820b2009-01-27 22:08:43 +00001098 ComplexType *New = new (*this,8) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001099 Types.push_back(New);
1100 ComplexTypes.InsertNode(New, InsertPos);
1101 return QualType(New, 0);
1102}
1103
Eli Friedmanf98aba32009-02-13 02:31:07 +00001104QualType ASTContext::getFixedWidthIntType(unsigned Width, bool Signed) {
1105 llvm::DenseMap<unsigned, FixedWidthIntType*> &Map = Signed ?
1106 SignedFixedWidthIntTypes : UnsignedFixedWidthIntTypes;
1107 FixedWidthIntType *&Entry = Map[Width];
1108 if (!Entry)
1109 Entry = new FixedWidthIntType(Width, Signed);
1110 return QualType(Entry, 0);
1111}
Reid Spencer5f016e22007-07-11 17:01:13 +00001112
1113/// getPointerType - Return the uniqued reference to the type for a pointer to
1114/// the specified type.
1115QualType ASTContext::getPointerType(QualType T) {
1116 // Unique pointers, to guarantee there is only one pointer of a particular
1117 // structure.
1118 llvm::FoldingSetNodeID ID;
1119 PointerType::Profile(ID, T);
1120
1121 void *InsertPos = 0;
1122 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1123 return QualType(PT, 0);
1124
1125 // If the pointee type isn't canonical, this won't be a canonical type either,
1126 // so fill in the canonical type field.
1127 QualType Canonical;
1128 if (!T->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001129 Canonical = getPointerType(getCanonicalType(T));
Reid Spencer5f016e22007-07-11 17:01:13 +00001130
1131 // Get the new insert position for the node we care about.
1132 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001133 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001134 }
Steve Narofff83820b2009-01-27 22:08:43 +00001135 PointerType *New = new (*this,8) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001136 Types.push_back(New);
1137 PointerTypes.InsertNode(New, InsertPos);
1138 return QualType(New, 0);
1139}
1140
Steve Naroff5618bd42008-08-27 16:04:49 +00001141/// getBlockPointerType - Return the uniqued reference to the type for
1142/// a pointer to the specified block.
1143QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff296e8d52008-08-28 19:20:44 +00001144 assert(T->isFunctionType() && "block of function types only");
1145 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001146 // structure.
1147 llvm::FoldingSetNodeID ID;
1148 BlockPointerType::Profile(ID, T);
1149
1150 void *InsertPos = 0;
1151 if (BlockPointerType *PT =
1152 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1153 return QualType(PT, 0);
1154
Steve Naroff296e8d52008-08-28 19:20:44 +00001155 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001156 // type either so fill in the canonical type field.
1157 QualType Canonical;
1158 if (!T->isCanonical()) {
1159 Canonical = getBlockPointerType(getCanonicalType(T));
1160
1161 // Get the new insert position for the node we care about.
1162 BlockPointerType *NewIP =
1163 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001164 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001165 }
Steve Narofff83820b2009-01-27 22:08:43 +00001166 BlockPointerType *New = new (*this,8) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001167 Types.push_back(New);
1168 BlockPointerTypes.InsertNode(New, InsertPos);
1169 return QualType(New, 0);
1170}
1171
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001172/// getLValueReferenceType - Return the uniqued reference to the type for an
1173/// lvalue reference to the specified type.
1174QualType ASTContext::getLValueReferenceType(QualType T) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001175 // Unique pointers, to guarantee there is only one pointer of a particular
1176 // structure.
1177 llvm::FoldingSetNodeID ID;
1178 ReferenceType::Profile(ID, T);
1179
1180 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001181 if (LValueReferenceType *RT =
1182 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001183 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001184
Reid Spencer5f016e22007-07-11 17:01:13 +00001185 // If the referencee type isn't canonical, this won't be a canonical type
1186 // either, so fill in the canonical type field.
1187 QualType Canonical;
1188 if (!T->isCanonical()) {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001189 Canonical = getLValueReferenceType(getCanonicalType(T));
1190
Reid Spencer5f016e22007-07-11 17:01:13 +00001191 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001192 LValueReferenceType *NewIP =
1193 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001194 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001195 }
1196
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001197 LValueReferenceType *New = new (*this,8) LValueReferenceType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001198 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001199 LValueReferenceTypes.InsertNode(New, InsertPos);
1200 return QualType(New, 0);
1201}
1202
1203/// getRValueReferenceType - Return the uniqued reference to the type for an
1204/// rvalue reference to the specified type.
1205QualType ASTContext::getRValueReferenceType(QualType T) {
1206 // Unique pointers, to guarantee there is only one pointer of a particular
1207 // structure.
1208 llvm::FoldingSetNodeID ID;
1209 ReferenceType::Profile(ID, T);
1210
1211 void *InsertPos = 0;
1212 if (RValueReferenceType *RT =
1213 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1214 return QualType(RT, 0);
1215
1216 // If the referencee type isn't canonical, this won't be a canonical type
1217 // either, so fill in the canonical type field.
1218 QualType Canonical;
1219 if (!T->isCanonical()) {
1220 Canonical = getRValueReferenceType(getCanonicalType(T));
1221
1222 // Get the new insert position for the node we care about.
1223 RValueReferenceType *NewIP =
1224 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1225 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1226 }
1227
1228 RValueReferenceType *New = new (*this,8) RValueReferenceType(T, Canonical);
1229 Types.push_back(New);
1230 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001231 return QualType(New, 0);
1232}
1233
Sebastian Redlf30208a2009-01-24 21:16:55 +00001234/// getMemberPointerType - Return the uniqued reference to the type for a
1235/// member pointer to the specified type, in the specified class.
1236QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls)
1237{
1238 // Unique pointers, to guarantee there is only one pointer of a particular
1239 // structure.
1240 llvm::FoldingSetNodeID ID;
1241 MemberPointerType::Profile(ID, T, Cls);
1242
1243 void *InsertPos = 0;
1244 if (MemberPointerType *PT =
1245 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1246 return QualType(PT, 0);
1247
1248 // If the pointee or class type isn't canonical, this won't be a canonical
1249 // type either, so fill in the canonical type field.
1250 QualType Canonical;
1251 if (!T->isCanonical()) {
1252 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1253
1254 // Get the new insert position for the node we care about.
1255 MemberPointerType *NewIP =
1256 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1257 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1258 }
Steve Narofff83820b2009-01-27 22:08:43 +00001259 MemberPointerType *New = new (*this,8) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001260 Types.push_back(New);
1261 MemberPointerTypes.InsertNode(New, InsertPos);
1262 return QualType(New, 0);
1263}
1264
Steve Narofffb22d962007-08-30 01:06:46 +00001265/// getConstantArrayType - Return the unique reference to the type for an
1266/// array of the specified element type.
1267QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001268 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001269 ArrayType::ArraySizeModifier ASM,
1270 unsigned EltTypeQuals) {
Eli Friedman587cbdf2009-05-29 20:17:55 +00001271 assert((EltTy->isDependentType() || EltTy->isConstantSizeType()) &&
1272 "Constant array of VLAs is illegal!");
1273
Chris Lattner38aeec72009-05-13 04:12:56 +00001274 // Convert the array size into a canonical width matching the pointer size for
1275 // the target.
1276 llvm::APInt ArySize(ArySizeIn);
1277 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1278
Reid Spencer5f016e22007-07-11 17:01:13 +00001279 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001280 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001281
1282 void *InsertPos = 0;
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001283 if (ConstantArrayType *ATP =
1284 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001285 return QualType(ATP, 0);
1286
1287 // If the element type isn't canonical, this won't be a canonical type either,
1288 // so fill in the canonical type field.
1289 QualType Canonical;
1290 if (!EltTy->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001291 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroffc9406122007-08-30 18:10:14 +00001292 ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001293 // Get the new insert position for the node we care about.
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001294 ConstantArrayType *NewIP =
1295 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001296 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001297 }
1298
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001299 ConstantArrayType *New =
Steve Narofff83820b2009-01-27 22:08:43 +00001300 new(*this,8)ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001301 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001302 Types.push_back(New);
1303 return QualType(New, 0);
1304}
1305
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001306/// getConstantArrayWithExprType - Return a reference to the type for
1307/// an array of the specified element type.
1308QualType
1309ASTContext::getConstantArrayWithExprType(QualType EltTy,
1310 const llvm::APInt &ArySizeIn,
1311 Expr *ArySizeExpr,
1312 ArrayType::ArraySizeModifier ASM,
1313 unsigned EltTypeQuals,
1314 SourceRange Brackets) {
1315 // Convert the array size into a canonical width matching the pointer
1316 // size for the target.
1317 llvm::APInt ArySize(ArySizeIn);
1318 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1319
1320 // Compute the canonical ConstantArrayType.
1321 QualType Canonical = getConstantArrayType(getCanonicalType(EltTy),
1322 ArySize, ASM, EltTypeQuals);
1323 // Since we don't unique expressions, it isn't possible to unique VLA's
1324 // that have an expression provided for their size.
1325 ConstantArrayWithExprType *New =
1326 new(*this,8)ConstantArrayWithExprType(EltTy, Canonical,
1327 ArySize, ArySizeExpr,
1328 ASM, EltTypeQuals, Brackets);
1329 Types.push_back(New);
1330 return QualType(New, 0);
1331}
1332
1333/// getConstantArrayWithoutExprType - Return a reference to the type for
1334/// an array of the specified element type.
1335QualType
1336ASTContext::getConstantArrayWithoutExprType(QualType EltTy,
1337 const llvm::APInt &ArySizeIn,
1338 ArrayType::ArraySizeModifier ASM,
1339 unsigned EltTypeQuals) {
1340 // Convert the array size into a canonical width matching the pointer
1341 // size for the target.
1342 llvm::APInt ArySize(ArySizeIn);
1343 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1344
1345 // Compute the canonical ConstantArrayType.
1346 QualType Canonical = getConstantArrayType(getCanonicalType(EltTy),
1347 ArySize, ASM, EltTypeQuals);
1348 ConstantArrayWithoutExprType *New =
1349 new(*this,8)ConstantArrayWithoutExprType(EltTy, Canonical,
1350 ArySize, ASM, EltTypeQuals);
1351 Types.push_back(New);
1352 return QualType(New, 0);
1353}
1354
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001355/// getVariableArrayType - Returns a non-unique reference to the type for a
1356/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001357QualType ASTContext::getVariableArrayType(QualType EltTy,
1358 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001359 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001360 unsigned EltTypeQuals,
1361 SourceRange Brackets) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001362 // Since we don't unique expressions, it isn't possible to unique VLA's
1363 // that have an expression provided for their size.
1364
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001365 VariableArrayType *New =
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001366 new(*this,8)VariableArrayType(EltTy, QualType(),
1367 NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001368
1369 VariableArrayTypes.push_back(New);
1370 Types.push_back(New);
1371 return QualType(New, 0);
1372}
1373
Douglas Gregor898574e2008-12-05 23:32:09 +00001374/// getDependentSizedArrayType - Returns a non-unique reference to
1375/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001376/// type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001377QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1378 Expr *NumElts,
Douglas Gregor898574e2008-12-05 23:32:09 +00001379 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001380 unsigned EltTypeQuals,
1381 SourceRange Brackets) {
Douglas Gregor898574e2008-12-05 23:32:09 +00001382 assert((NumElts->isTypeDependent() || NumElts->isValueDependent()) &&
1383 "Size must be type- or value-dependent!");
1384
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001385 llvm::FoldingSetNodeID ID;
1386 DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
1387 EltTypeQuals, NumElts);
Douglas Gregor898574e2008-12-05 23:32:09 +00001388
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001389 void *InsertPos = 0;
1390 DependentSizedArrayType *Canon
1391 = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1392 DependentSizedArrayType *New;
1393 if (Canon) {
1394 // We already have a canonical version of this array type; use it as
1395 // the canonical type for a newly-built type.
1396 New = new (*this,8) DependentSizedArrayType(*this, EltTy,
1397 QualType(Canon, 0),
1398 NumElts, ASM, EltTypeQuals,
1399 Brackets);
1400 } else {
1401 QualType CanonEltTy = getCanonicalType(EltTy);
1402 if (CanonEltTy == EltTy) {
1403 New = new (*this,8) DependentSizedArrayType(*this, EltTy, QualType(),
1404 NumElts, ASM, EltTypeQuals,
1405 Brackets);
1406 DependentSizedArrayTypes.InsertNode(New, InsertPos);
1407 } else {
1408 QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1409 ASM, EltTypeQuals,
1410 SourceRange());
1411 New = new (*this,8) DependentSizedArrayType(*this, EltTy, Canon,
1412 NumElts, ASM, EltTypeQuals,
1413 Brackets);
1414 }
1415 }
1416
Douglas Gregor898574e2008-12-05 23:32:09 +00001417 Types.push_back(New);
1418 return QualType(New, 0);
1419}
1420
Eli Friedmanc5773c42008-02-15 18:16:39 +00001421QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1422 ArrayType::ArraySizeModifier ASM,
1423 unsigned EltTypeQuals) {
1424 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001425 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001426
1427 void *InsertPos = 0;
1428 if (IncompleteArrayType *ATP =
1429 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1430 return QualType(ATP, 0);
1431
1432 // If the element type isn't canonical, this won't be a canonical type
1433 // either, so fill in the canonical type field.
1434 QualType Canonical;
1435
1436 if (!EltTy->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001437 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001438 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001439
1440 // Get the new insert position for the node we care about.
1441 IncompleteArrayType *NewIP =
1442 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001443 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001444 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001445
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001446 IncompleteArrayType *New
1447 = new (*this,8) IncompleteArrayType(EltTy, Canonical,
1448 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001449
1450 IncompleteArrayTypes.InsertNode(New, InsertPos);
1451 Types.push_back(New);
1452 return QualType(New, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001453}
1454
Steve Naroff73322922007-07-18 18:00:27 +00001455/// getVectorType - Return the unique reference to a vector type of
1456/// the specified element type and size. VectorType must be a built-in type.
1457QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001458 BuiltinType *baseType;
1459
Chris Lattnerf52ab252008-04-06 22:59:24 +00001460 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff73322922007-07-18 18:00:27 +00001461 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Reid Spencer5f016e22007-07-11 17:01:13 +00001462
1463 // Check if we've already instantiated a vector of this type.
1464 llvm::FoldingSetNodeID ID;
Steve Naroff73322922007-07-18 18:00:27 +00001465 VectorType::Profile(ID, vecType, NumElts, Type::Vector);
Reid Spencer5f016e22007-07-11 17:01:13 +00001466 void *InsertPos = 0;
1467 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1468 return QualType(VTP, 0);
1469
1470 // If the element type isn't canonical, this won't be a canonical type either,
1471 // so fill in the canonical type field.
1472 QualType Canonical;
1473 if (!vecType->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001474 Canonical = getVectorType(getCanonicalType(vecType), NumElts);
Reid Spencer5f016e22007-07-11 17:01:13 +00001475
1476 // Get the new insert position for the node we care about.
1477 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001478 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001479 }
Steve Narofff83820b2009-01-27 22:08:43 +00001480 VectorType *New = new (*this,8) VectorType(vecType, NumElts, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001481 VectorTypes.InsertNode(New, InsertPos);
1482 Types.push_back(New);
1483 return QualType(New, 0);
1484}
1485
Nate Begeman213541a2008-04-18 23:10:10 +00001486/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001487/// the specified element type and size. VectorType must be a built-in type.
Nate Begeman213541a2008-04-18 23:10:10 +00001488QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff73322922007-07-18 18:00:27 +00001489 BuiltinType *baseType;
1490
Chris Lattnerf52ab252008-04-06 22:59:24 +00001491 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begeman213541a2008-04-18 23:10:10 +00001492 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Steve Naroff73322922007-07-18 18:00:27 +00001493
1494 // Check if we've already instantiated a vector of this type.
1495 llvm::FoldingSetNodeID ID;
Nate Begeman213541a2008-04-18 23:10:10 +00001496 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector);
Steve Naroff73322922007-07-18 18:00:27 +00001497 void *InsertPos = 0;
1498 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1499 return QualType(VTP, 0);
1500
1501 // If the element type isn't canonical, this won't be a canonical type either,
1502 // so fill in the canonical type field.
1503 QualType Canonical;
1504 if (!vecType->isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001505 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Steve Naroff73322922007-07-18 18:00:27 +00001506
1507 // Get the new insert position for the node we care about.
1508 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001509 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001510 }
Steve Narofff83820b2009-01-27 22:08:43 +00001511 ExtVectorType *New = new (*this,8) ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001512 VectorTypes.InsertNode(New, InsertPos);
1513 Types.push_back(New);
1514 return QualType(New, 0);
1515}
1516
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001517QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
1518 Expr *SizeExpr,
1519 SourceLocation AttrLoc) {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001520 llvm::FoldingSetNodeID ID;
1521 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
1522 SizeExpr);
1523
1524 void *InsertPos = 0;
1525 DependentSizedExtVectorType *Canon
1526 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1527 DependentSizedExtVectorType *New;
1528 if (Canon) {
1529 // We already have a canonical version of this array type; use it as
1530 // the canonical type for a newly-built type.
1531 New = new (*this,8) DependentSizedExtVectorType(*this, vecType,
1532 QualType(Canon, 0),
1533 SizeExpr, AttrLoc);
1534 } else {
1535 QualType CanonVecTy = getCanonicalType(vecType);
1536 if (CanonVecTy == vecType) {
1537 New = new (*this,8) DependentSizedExtVectorType(*this, vecType,
1538 QualType(), SizeExpr,
1539 AttrLoc);
1540 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1541 } else {
1542 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1543 SourceLocation());
1544 New = new (*this,8) DependentSizedExtVectorType(*this, vecType, Canon,
1545 SizeExpr, AttrLoc);
1546 }
1547 }
1548
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001549 Types.push_back(New);
1550 return QualType(New, 0);
1551}
1552
Douglas Gregor72564e72009-02-26 23:50:07 +00001553/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001554///
Mike Stump24556362009-07-25 21:26:53 +00001555QualType ASTContext::getFunctionNoProtoType(QualType ResultTy, bool NoReturn) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001556 // Unique functions, to guarantee there is only one function of a particular
1557 // structure.
1558 llvm::FoldingSetNodeID ID;
Mike Stump24556362009-07-25 21:26:53 +00001559 FunctionNoProtoType::Profile(ID, ResultTy, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001560
1561 void *InsertPos = 0;
Douglas Gregor72564e72009-02-26 23:50:07 +00001562 if (FunctionNoProtoType *FT =
1563 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001564 return QualType(FT, 0);
1565
1566 QualType Canonical;
1567 if (!ResultTy->isCanonical()) {
Mike Stump24556362009-07-25 21:26:53 +00001568 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001569
1570 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001571 FunctionNoProtoType *NewIP =
1572 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001573 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001574 }
1575
Mike Stump24556362009-07-25 21:26:53 +00001576 FunctionNoProtoType *New
1577 = new (*this,8) FunctionNoProtoType(ResultTy, Canonical, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001578 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001579 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001580 return QualType(New, 0);
1581}
1582
1583/// getFunctionType - Return a normal function type with a typed argument
1584/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner61710852008-10-05 17:34:18 +00001585QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001586 unsigned NumArgs, bool isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001587 unsigned TypeQuals, bool hasExceptionSpec,
1588 bool hasAnyExceptionSpec, unsigned NumExs,
Mike Stump24556362009-07-25 21:26:53 +00001589 const QualType *ExArray, bool NoReturn) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001590 // Unique functions, to guarantee there is only one function of a particular
1591 // structure.
1592 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001593 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001594 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Mike Stump24556362009-07-25 21:26:53 +00001595 NumExs, ExArray, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001596
1597 void *InsertPos = 0;
Douglas Gregor72564e72009-02-26 23:50:07 +00001598 if (FunctionProtoType *FTP =
1599 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001600 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001601
1602 // Determine whether the type being created is already canonical or not.
Reid Spencer5f016e22007-07-11 17:01:13 +00001603 bool isCanonical = ResultTy->isCanonical();
Sebastian Redl465226e2009-05-27 22:11:52 +00001604 if (hasExceptionSpec)
1605 isCanonical = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001606 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
1607 if (!ArgArray[i]->isCanonical())
1608 isCanonical = false;
1609
1610 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001611 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001612 QualType Canonical;
1613 if (!isCanonical) {
1614 llvm::SmallVector<QualType, 16> CanonicalArgs;
1615 CanonicalArgs.reserve(NumArgs);
1616 for (unsigned i = 0; i != NumArgs; ++i)
Chris Lattnerf52ab252008-04-06 22:59:24 +00001617 CanonicalArgs.push_back(getCanonicalType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001618
Chris Lattnerf52ab252008-04-06 22:59:24 +00001619 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001620 CanonicalArgs.data(), NumArgs,
Douglas Gregor47259d92009-08-05 19:03:35 +00001621 isVariadic, TypeQuals, false,
1622 false, 0, 0, NoReturn);
Sebastian Redl465226e2009-05-27 22:11:52 +00001623
Reid Spencer5f016e22007-07-11 17:01:13 +00001624 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001625 FunctionProtoType *NewIP =
1626 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001627 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001628 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001629
Douglas Gregor72564e72009-02-26 23:50:07 +00001630 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001631 // for two variable size arrays (for parameter and exception types) at the
1632 // end of them.
Douglas Gregor72564e72009-02-26 23:50:07 +00001633 FunctionProtoType *FTP =
Sebastian Redl465226e2009-05-27 22:11:52 +00001634 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1635 NumArgs*sizeof(QualType) +
1636 NumExs*sizeof(QualType), 8);
Douglas Gregor72564e72009-02-26 23:50:07 +00001637 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001638 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Mike Stump24556362009-07-25 21:26:53 +00001639 ExArray, NumExs, Canonical, NoReturn);
Reid Spencer5f016e22007-07-11 17:01:13 +00001640 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001641 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001642 return QualType(FTP, 0);
1643}
1644
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001645/// getTypeDeclType - Return the unique reference to the type for the
1646/// specified type declaration.
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001647QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001648 assert(Decl && "Passed null for Decl param");
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001649 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1650
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001651 if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001652 return getTypedefType(Typedef);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001653 else if (isa<TemplateTypeParmDecl>(Decl)) {
1654 assert(false && "Template type parameter types are always available.");
Mike Stump9fdbab32009-07-31 02:02:20 +00001655 } else if (ObjCInterfaceDecl *ObjCInterface
1656 = dyn_cast<ObjCInterfaceDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001657 return getObjCInterfaceType(ObjCInterface);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001658
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001659 if (RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001660 if (PrevDecl)
1661 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001662 else
1663 Decl->TypeForDecl = new (*this,8) RecordType(Record);
Mike Stump9fdbab32009-07-31 02:02:20 +00001664 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001665 if (PrevDecl)
1666 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001667 else
1668 Decl->TypeForDecl = new (*this,8) EnumType(Enum);
Mike Stump9fdbab32009-07-31 02:02:20 +00001669 } else
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001670 assert(false && "TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001671
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001672 if (!PrevDecl) Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001673 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001674}
1675
Reid Spencer5f016e22007-07-11 17:01:13 +00001676/// getTypedefType - Return the unique reference to the type for the
1677/// specified typename decl.
1678QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
1679 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1680
Chris Lattnerf52ab252008-04-06 22:59:24 +00001681 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
Douglas Gregor72564e72009-02-26 23:50:07 +00001682 Decl->TypeForDecl = new(*this,8) TypedefType(Type::Typedef, Decl, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001683 Types.push_back(Decl->TypeForDecl);
1684 return QualType(Decl->TypeForDecl, 0);
1685}
1686
Douglas Gregorfab9d672009-02-05 23:33:38 +00001687/// \brief Retrieve the template type parameter type for a template
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001688/// parameter or parameter pack with the given depth, index, and (optionally)
1689/// name.
Douglas Gregorfab9d672009-02-05 23:33:38 +00001690QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001691 bool ParameterPack,
Douglas Gregorfab9d672009-02-05 23:33:38 +00001692 IdentifierInfo *Name) {
1693 llvm::FoldingSetNodeID ID;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001694 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001695 void *InsertPos = 0;
1696 TemplateTypeParmType *TypeParm
1697 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1698
1699 if (TypeParm)
1700 return QualType(TypeParm, 0);
1701
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001702 if (Name) {
1703 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
1704 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, ParameterPack,
1705 Name, Canon);
1706 } else
1707 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001708
1709 Types.push_back(TypeParm);
1710 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1711
1712 return QualType(TypeParm, 0);
1713}
1714
Douglas Gregor55f6b142009-02-09 18:46:07 +00001715QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00001716ASTContext::getTemplateSpecializationType(TemplateName Template,
1717 const TemplateArgument *Args,
1718 unsigned NumArgs,
1719 QualType Canon) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00001720 if (!Canon.isNull())
1721 Canon = getCanonicalType(Canon);
1722 else {
1723 // Build the canonical template specialization type.
Douglas Gregor1275ae02009-07-28 23:00:59 +00001724 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
1725 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
1726 CanonArgs.reserve(NumArgs);
1727 for (unsigned I = 0; I != NumArgs; ++I)
1728 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
1729
1730 // Determine whether this canonical template specialization type already
1731 // exists.
1732 llvm::FoldingSetNodeID ID;
1733 TemplateSpecializationType::Profile(ID, CanonTemplate,
Douglas Gregor828e2262009-07-29 16:09:57 +00001734 CanonArgs.data(), NumArgs, *this);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001735
1736 void *InsertPos = 0;
1737 TemplateSpecializationType *Spec
1738 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
1739
1740 if (!Spec) {
1741 // Allocate a new canonical template specialization type.
1742 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
1743 sizeof(TemplateArgument) * NumArgs),
1744 8);
Douglas Gregor828e2262009-07-29 16:09:57 +00001745 Spec = new (Mem) TemplateSpecializationType(*this, CanonTemplate,
Douglas Gregor1275ae02009-07-28 23:00:59 +00001746 CanonArgs.data(), NumArgs,
Douglas Gregorb88e8882009-07-30 17:40:51 +00001747 Canon);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001748 Types.push_back(Spec);
1749 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
1750 }
1751
Douglas Gregorb88e8882009-07-30 17:40:51 +00001752 if (Canon.isNull())
1753 Canon = QualType(Spec, 0);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001754 assert(Canon->isDependentType() &&
1755 "Non-dependent template-id type must have a canonical type");
Douglas Gregorb88e8882009-07-30 17:40:51 +00001756 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00001757
Douglas Gregor1275ae02009-07-28 23:00:59 +00001758 // Allocate the (non-canonical) template specialization type, but don't
1759 // try to unique it: these types typically have location information that
1760 // we don't unique and don't want to lose.
Douglas Gregor7532dc62009-03-30 22:58:21 +00001761 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00001762 sizeof(TemplateArgument) * NumArgs),
1763 8);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001764 TemplateSpecializationType *Spec
Douglas Gregor828e2262009-07-29 16:09:57 +00001765 = new (Mem) TemplateSpecializationType(*this, Template, Args, NumArgs,
1766 Canon);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001767
Douglas Gregor55f6b142009-02-09 18:46:07 +00001768 Types.push_back(Spec);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001769 return QualType(Spec, 0);
1770}
1771
Douglas Gregore4e5b052009-03-19 00:18:19 +00001772QualType
Douglas Gregorab452ba2009-03-26 23:50:42 +00001773ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
Douglas Gregore4e5b052009-03-19 00:18:19 +00001774 QualType NamedType) {
1775 llvm::FoldingSetNodeID ID;
Douglas Gregorab452ba2009-03-26 23:50:42 +00001776 QualifiedNameType::Profile(ID, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001777
1778 void *InsertPos = 0;
1779 QualifiedNameType *T
1780 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
1781 if (T)
1782 return QualType(T, 0);
1783
Douglas Gregorab452ba2009-03-26 23:50:42 +00001784 T = new (*this) QualifiedNameType(NNS, NamedType,
1785 getCanonicalType(NamedType));
Douglas Gregore4e5b052009-03-19 00:18:19 +00001786 Types.push_back(T);
1787 QualifiedNameTypes.InsertNode(T, InsertPos);
1788 return QualType(T, 0);
1789}
1790
Douglas Gregord57959a2009-03-27 23:10:48 +00001791QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1792 const IdentifierInfo *Name,
1793 QualType Canon) {
1794 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1795
1796 if (Canon.isNull()) {
1797 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1798 if (CanonNNS != NNS)
1799 Canon = getTypenameType(CanonNNS, Name);
1800 }
1801
1802 llvm::FoldingSetNodeID ID;
1803 TypenameType::Profile(ID, NNS, Name);
1804
1805 void *InsertPos = 0;
1806 TypenameType *T
1807 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1808 if (T)
1809 return QualType(T, 0);
1810
1811 T = new (*this) TypenameType(NNS, Name, Canon);
1812 Types.push_back(T);
1813 TypenameTypes.InsertNode(T, InsertPos);
1814 return QualType(T, 0);
1815}
1816
Douglas Gregor17343172009-04-01 00:28:59 +00001817QualType
1818ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1819 const TemplateSpecializationType *TemplateId,
1820 QualType Canon) {
1821 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1822
1823 if (Canon.isNull()) {
1824 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1825 QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
1826 if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
1827 const TemplateSpecializationType *CanonTemplateId
1828 = CanonType->getAsTemplateSpecializationType();
1829 assert(CanonTemplateId &&
1830 "Canonical type must also be a template specialization type");
1831 Canon = getTypenameType(CanonNNS, CanonTemplateId);
1832 }
1833 }
1834
1835 llvm::FoldingSetNodeID ID;
1836 TypenameType::Profile(ID, NNS, TemplateId);
1837
1838 void *InsertPos = 0;
1839 TypenameType *T
1840 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1841 if (T)
1842 return QualType(T, 0);
1843
1844 T = new (*this) TypenameType(NNS, TemplateId, Canon);
1845 Types.push_back(T);
1846 TypenameTypes.InsertNode(T, InsertPos);
1847 return QualType(T, 0);
1848}
1849
Chris Lattner88cb27a2008-04-07 04:56:42 +00001850/// CmpProtocolNames - Comparison predicate for sorting protocols
1851/// alphabetically.
1852static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
1853 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001854 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00001855}
1856
1857static void SortAndUniqueProtocols(ObjCProtocolDecl **&Protocols,
1858 unsigned &NumProtocols) {
1859 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
1860
1861 // Sort protocols, keyed by name.
1862 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
1863
1864 // Remove duplicates.
1865 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
1866 NumProtocols = ProtocolsEnd-Protocols;
1867}
1868
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001869/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
1870/// the given interface decl and the conforming protocol list.
Steve Naroff14108da2009-07-10 23:34:53 +00001871QualType ASTContext::getObjCObjectPointerType(QualType InterfaceT,
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001872 ObjCProtocolDecl **Protocols,
1873 unsigned NumProtocols) {
1874 // Sort the protocol list alphabetically to canonicalize it.
1875 if (NumProtocols)
1876 SortAndUniqueProtocols(Protocols, NumProtocols);
1877
1878 llvm::FoldingSetNodeID ID;
Steve Naroff14108da2009-07-10 23:34:53 +00001879 ObjCObjectPointerType::Profile(ID, InterfaceT, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001880
1881 void *InsertPos = 0;
1882 if (ObjCObjectPointerType *QT =
1883 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1884 return QualType(QT, 0);
1885
1886 // No Match;
1887 ObjCObjectPointerType *QType =
Steve Naroff14108da2009-07-10 23:34:53 +00001888 new (*this,8) ObjCObjectPointerType(InterfaceT, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001889
1890 Types.push_back(QType);
1891 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
1892 return QualType(QType, 0);
1893}
Chris Lattner88cb27a2008-04-07 04:56:42 +00001894
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001895/// getObjCInterfaceType - Return the unique reference to the type for the
1896/// specified ObjC interface decl. The list of protocols is optional.
1897QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001898 ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001899 if (NumProtocols)
1900 // Sort the protocol list alphabetically to canonicalize it.
1901 SortAndUniqueProtocols(Protocols, NumProtocols);
Chris Lattner88cb27a2008-04-07 04:56:42 +00001902
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001903 llvm::FoldingSetNodeID ID;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001904 ObjCInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001905
1906 void *InsertPos = 0;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001907 if (ObjCInterfaceType *QT =
1908 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001909 return QualType(QT, 0);
1910
1911 // No Match;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001912 ObjCInterfaceType *QType =
1913 new (*this,8) ObjCInterfaceType(const_cast<ObjCInterfaceDecl*>(Decl),
1914 Protocols, NumProtocols);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001915 Types.push_back(QType);
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001916 ObjCInterfaceTypes.InsertNode(QType, InsertPos);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001917 return QualType(QType, 0);
1918}
1919
Douglas Gregor72564e72009-02-26 23:50:07 +00001920/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
1921/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00001922/// multiple declarations that refer to "typeof(x)" all contain different
1923/// DeclRefExpr's. This doesn't effect the type checker, since it operates
1924/// on canonical type's (which are always unique).
Douglas Gregor72564e72009-02-26 23:50:07 +00001925QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00001926 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00001927 if (tofExpr->isTypeDependent()) {
1928 llvm::FoldingSetNodeID ID;
1929 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
1930
1931 void *InsertPos = 0;
1932 DependentTypeOfExprType *Canon
1933 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
1934 if (Canon) {
1935 // We already have a "canonical" version of an identical, dependent
1936 // typeof(expr) type. Use that as our canonical type.
1937 toe = new (*this, 8) TypeOfExprType(tofExpr,
1938 QualType((TypeOfExprType*)Canon, 0));
1939 }
1940 else {
1941 // Build a new, canonical typeof(expr) type.
1942 Canon = new (*this, 8) DependentTypeOfExprType(*this, tofExpr);
1943 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
1944 toe = Canon;
1945 }
1946 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00001947 QualType Canonical = getCanonicalType(tofExpr->getType());
1948 toe = new (*this,8) TypeOfExprType(tofExpr, Canonical);
1949 }
Steve Naroff9752f252007-08-01 18:02:17 +00001950 Types.push_back(toe);
1951 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00001952}
1953
Steve Naroff9752f252007-08-01 18:02:17 +00001954/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
1955/// TypeOfType AST's. The only motivation to unique these nodes would be
1956/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
1957/// an issue. This doesn't effect the type checker, since it operates
1958/// on canonical type's (which are always unique).
Steve Naroffd1861fd2007-07-31 12:34:36 +00001959QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001960 QualType Canonical = getCanonicalType(tofType);
Steve Narofff83820b2009-01-27 22:08:43 +00001961 TypeOfType *tot = new (*this,8) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00001962 Types.push_back(tot);
1963 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00001964}
1965
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00001966/// getDecltypeForExpr - Given an expr, will return the decltype for that
1967/// expression, according to the rules in C++0x [dcl.type.simple]p4
1968static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00001969 if (e->isTypeDependent())
1970 return Context.DependentTy;
1971
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00001972 // If e is an id expression or a class member access, decltype(e) is defined
1973 // as the type of the entity named by e.
1974 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
1975 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
1976 return VD->getType();
1977 }
1978 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
1979 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
1980 return FD->getType();
1981 }
1982 // If e is a function call or an invocation of an overloaded operator,
1983 // (parentheses around e are ignored), decltype(e) is defined as the
1984 // return type of that function.
1985 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
1986 return CE->getCallReturnType();
1987
1988 QualType T = e->getType();
1989
1990 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
1991 // defined as T&, otherwise decltype(e) is defined as T.
1992 if (e->isLvalue(Context) == Expr::LV_Valid)
1993 T = Context.getLValueReferenceType(T);
1994
1995 return T;
1996}
1997
Anders Carlsson395b4752009-06-24 19:06:50 +00001998/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
1999/// DecltypeType AST's. The only motivation to unique these nodes would be
2000/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
2001/// an issue. This doesn't effect the type checker, since it operates
2002/// on canonical type's (which are always unique).
2003QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002004 DecltypeType *dt;
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002005 if (e->isTypeDependent()) {
2006 llvm::FoldingSetNodeID ID;
2007 DependentDecltypeType::Profile(ID, *this, e);
2008
2009 void *InsertPos = 0;
2010 DependentDecltypeType *Canon
2011 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2012 if (Canon) {
2013 // We already have a "canonical" version of an equivalent, dependent
2014 // decltype type. Use that as our canonical type.
2015 dt = new (*this, 8) DecltypeType(e, DependentTy,
2016 QualType((DecltypeType*)Canon, 0));
2017 }
2018 else {
2019 // Build a new, canonical typeof(expr) type.
2020 Canon = new (*this, 8) DependentDecltypeType(*this, e);
2021 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2022 dt = Canon;
2023 }
2024 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002025 QualType T = getDecltypeForExpr(e, *this);
Anders Carlsson563a03b2009-07-10 19:20:26 +00002026 dt = new (*this, 8) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002027 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002028 Types.push_back(dt);
2029 return QualType(dt, 0);
2030}
2031
Reid Spencer5f016e22007-07-11 17:01:13 +00002032/// getTagDeclType - Return the unique reference to the type for the
2033/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpe607ed02009-08-07 18:05:12 +00002034QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenekd778f882007-11-26 21:16:01 +00002035 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00002036 // FIXME: What is the design on getTagDeclType when it requires casting
2037 // away const? mutable?
2038 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002039}
2040
2041/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2042/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2043/// needs to agree with the definition in <stddef.h>.
2044QualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002045 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00002046}
2047
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00002048/// getSignedWCharType - Return the type of "signed wchar_t".
2049/// Used when in C++, as a GCC extension.
2050QualType ASTContext::getSignedWCharType() const {
2051 // FIXME: derive from "Target" ?
2052 return WCharTy;
2053}
2054
2055/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2056/// Used when in C++, as a GCC extension.
2057QualType ASTContext::getUnsignedWCharType() const {
2058 // FIXME: derive from "Target" ?
2059 return UnsignedIntTy;
2060}
2061
Chris Lattner8b9023b2007-07-13 03:05:23 +00002062/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2063/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2064QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002065 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00002066}
2067
Chris Lattnere6327742008-04-02 05:18:44 +00002068//===----------------------------------------------------------------------===//
2069// Type Operators
2070//===----------------------------------------------------------------------===//
2071
Chris Lattner77c96472008-04-06 22:41:35 +00002072/// getCanonicalType - Return the canonical (structural) type corresponding to
2073/// the specified potentially non-canonical type. The non-canonical version
2074/// of a type may have many "decorated" versions of types. Decorators can
2075/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2076/// to be free of any of these, allowing two canonical types to be compared
2077/// for exact equality with a simple pointer comparison.
Douglas Gregor50d62d12009-08-05 05:36:45 +00002078CanQualType ASTContext::getCanonicalType(QualType T) {
Chris Lattner77c96472008-04-06 22:41:35 +00002079 QualType CanType = T.getTypePtr()->getCanonicalTypeInternal();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002080
2081 // If the result has type qualifiers, make sure to canonicalize them as well.
2082 unsigned TypeQuals = T.getCVRQualifiers() | CanType.getCVRQualifiers();
Douglas Gregor50d62d12009-08-05 05:36:45 +00002083 if (TypeQuals == 0)
2084 return CanQualType::CreateUnsafe(CanType);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002085
2086 // If the type qualifiers are on an array type, get the canonical type of the
2087 // array with the qualifiers applied to the element type.
2088 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2089 if (!AT)
Douglas Gregor50d62d12009-08-05 05:36:45 +00002090 return CanQualType::CreateUnsafe(CanType.getQualifiedType(TypeQuals));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002091
2092 // Get the canonical version of the element with the extra qualifiers on it.
2093 // This can recursively sink qualifiers through multiple levels of arrays.
2094 QualType NewEltTy=AT->getElementType().getWithAdditionalQualifiers(TypeQuals);
2095 NewEltTy = getCanonicalType(NewEltTy);
2096
2097 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002098 return CanQualType::CreateUnsafe(
2099 getConstantArrayType(NewEltTy, CAT->getSize(),
2100 CAT->getSizeModifier(),
2101 CAT->getIndexTypeQualifier()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002102 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002103 return CanQualType::CreateUnsafe(
2104 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
2105 IAT->getIndexTypeQualifier()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002106
Douglas Gregor898574e2008-12-05 23:32:09 +00002107 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002108 return CanQualType::CreateUnsafe(
2109 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002110 DSAT->getSizeExpr() ?
2111 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002112 DSAT->getSizeModifier(),
2113 DSAT->getIndexTypeQualifier(),
2114 DSAT->getBracketsRange()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002115
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002116 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor50d62d12009-08-05 05:36:45 +00002117 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002118 VAT->getSizeExpr() ?
2119 VAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002120 VAT->getSizeModifier(),
2121 VAT->getIndexTypeQualifier(),
2122 VAT->getBracketsRange()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002123}
2124
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002125TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
2126 // If this template name refers to a template, the canonical
2127 // template name merely stores the template itself.
2128 if (TemplateDecl *Template = Name.getAsTemplateDecl())
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002129 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002130
Douglas Gregord99cbe62009-07-29 18:26:50 +00002131 // If this template name refers to a set of overloaded function templates,
2132 /// the canonical template name merely stores the set of function templates.
Douglas Gregor6ebd15e2009-07-31 05:24:01 +00002133 if (OverloadedFunctionDecl *Ovl = Name.getAsOverloadedFunctionDecl()) {
2134 OverloadedFunctionDecl *CanonOvl = 0;
2135 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
2136 FEnd = Ovl->function_end();
2137 F != FEnd; ++F) {
2138 Decl *Canon = F->get()->getCanonicalDecl();
2139 if (CanonOvl || Canon != F->get()) {
2140 if (!CanonOvl)
2141 CanonOvl = OverloadedFunctionDecl::Create(*this,
2142 Ovl->getDeclContext(),
2143 Ovl->getDeclName());
2144
2145 CanonOvl->addOverload(
2146 AnyFunctionDecl::getFromNamedDecl(cast<NamedDecl>(Canon)));
2147 }
2148 }
2149
2150 return TemplateName(CanonOvl? CanonOvl : Ovl);
2151 }
Douglas Gregord99cbe62009-07-29 18:26:50 +00002152
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002153 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2154 assert(DTN && "Non-dependent template names must refer to template decls.");
2155 return DTN->CanonicalTemplateName;
2156}
2157
Douglas Gregor1275ae02009-07-28 23:00:59 +00002158TemplateArgument
2159ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2160 switch (Arg.getKind()) {
2161 case TemplateArgument::Null:
2162 return Arg;
2163
2164 case TemplateArgument::Expression:
2165 // FIXME: Build canonical expression?
2166 return Arg;
2167
2168 case TemplateArgument::Declaration:
2169 return TemplateArgument(SourceLocation(),
2170 Arg.getAsDecl()->getCanonicalDecl());
2171
2172 case TemplateArgument::Integral:
2173 return TemplateArgument(SourceLocation(),
2174 *Arg.getAsIntegral(),
2175 getCanonicalType(Arg.getIntegralType()));
2176
2177 case TemplateArgument::Type:
2178 return TemplateArgument(SourceLocation(),
2179 getCanonicalType(Arg.getAsType()));
2180
2181 case TemplateArgument::Pack: {
2182 // FIXME: Allocate in ASTContext
2183 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2184 unsigned Idx = 0;
2185 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
2186 AEnd = Arg.pack_end();
2187 A != AEnd; (void)++A, ++Idx)
2188 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
2189
2190 TemplateArgument Result;
2191 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2192 return Result;
2193 }
2194 }
2195
2196 // Silence GCC warning
2197 assert(false && "Unhandled template argument kind");
2198 return TemplateArgument();
2199}
2200
Douglas Gregord57959a2009-03-27 23:10:48 +00002201NestedNameSpecifier *
2202ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
2203 if (!NNS)
2204 return 0;
2205
2206 switch (NNS->getKind()) {
2207 case NestedNameSpecifier::Identifier:
2208 // Canonicalize the prefix but keep the identifier the same.
2209 return NestedNameSpecifier::Create(*this,
2210 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2211 NNS->getAsIdentifier());
2212
2213 case NestedNameSpecifier::Namespace:
2214 // A namespace is canonical; build a nested-name-specifier with
2215 // this namespace and no prefix.
2216 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2217
2218 case NestedNameSpecifier::TypeSpec:
2219 case NestedNameSpecifier::TypeSpecWithTemplate: {
2220 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
2221 NestedNameSpecifier *Prefix = 0;
2222
2223 // FIXME: This isn't the right check!
2224 if (T->isDependentType())
2225 Prefix = getCanonicalNestedNameSpecifier(NNS->getPrefix());
2226
2227 return NestedNameSpecifier::Create(*this, Prefix,
2228 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
2229 T.getTypePtr());
2230 }
2231
2232 case NestedNameSpecifier::Global:
2233 // The global specifier is canonical and unique.
2234 return NNS;
2235 }
2236
2237 // Required to silence a GCC warning
2238 return 0;
2239}
2240
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002241
2242const ArrayType *ASTContext::getAsArrayType(QualType T) {
2243 // Handle the non-qualified case efficiently.
2244 if (T.getCVRQualifiers() == 0) {
2245 // Handle the common positive case fast.
2246 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2247 return AT;
2248 }
2249
2250 // Handle the common negative case fast, ignoring CVR qualifiers.
2251 QualType CType = T->getCanonicalTypeInternal();
2252
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002253 // Make sure to look through type qualifiers (like ExtQuals) for the negative
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002254 // test.
2255 if (!isa<ArrayType>(CType) &&
2256 !isa<ArrayType>(CType.getUnqualifiedType()))
2257 return 0;
2258
2259 // Apply any CVR qualifiers from the array type to the element type. This
2260 // implements C99 6.7.3p8: "If the specification of an array type includes
2261 // any type qualifiers, the element type is so qualified, not the array type."
2262
2263 // If we get here, we either have type qualifiers on the type, or we have
2264 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00002265 // we must propagate them down into the element type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002266 unsigned CVRQuals = T.getCVRQualifiers();
2267 unsigned AddrSpace = 0;
2268 Type *Ty = T.getTypePtr();
2269
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002270 // Rip through ExtQualType's and typedefs to get to a concrete type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002271 while (1) {
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002272 if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(Ty)) {
2273 AddrSpace = EXTQT->getAddressSpace();
2274 Ty = EXTQT->getBaseType();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002275 } else {
2276 T = Ty->getDesugaredType();
2277 if (T.getTypePtr() == Ty && T.getCVRQualifiers() == 0)
2278 break;
2279 CVRQuals |= T.getCVRQualifiers();
2280 Ty = T.getTypePtr();
2281 }
2282 }
2283
2284 // If we have a simple case, just return now.
2285 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
2286 if (ATy == 0 || (AddrSpace == 0 && CVRQuals == 0))
2287 return ATy;
2288
2289 // Otherwise, we have an array and we have qualifiers on it. Push the
2290 // qualifiers into the array element type and return a new array type.
2291 // Get the canonical version of the element with the extra qualifiers on it.
2292 // This can recursively sink qualifiers through multiple levels of arrays.
2293 QualType NewEltTy = ATy->getElementType();
2294 if (AddrSpace)
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002295 NewEltTy = getAddrSpaceQualType(NewEltTy, AddrSpace);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002296 NewEltTy = NewEltTy.getWithAdditionalQualifiers(CVRQuals);
2297
2298 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2299 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2300 CAT->getSizeModifier(),
2301 CAT->getIndexTypeQualifier()));
2302 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2303 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2304 IAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002305 IAT->getIndexTypeQualifier()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002306
Douglas Gregor898574e2008-12-05 23:32:09 +00002307 if (const DependentSizedArrayType *DSAT
2308 = dyn_cast<DependentSizedArrayType>(ATy))
2309 return cast<ArrayType>(
2310 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002311 DSAT->getSizeExpr() ?
2312 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor898574e2008-12-05 23:32:09 +00002313 DSAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002314 DSAT->getIndexTypeQualifier(),
2315 DSAT->getBracketsRange()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002316
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002317 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002318 return cast<ArrayType>(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002319 VAT->getSizeExpr() ?
2320 VAT->getSizeExpr()->Retain() : 0,
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002321 VAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002322 VAT->getIndexTypeQualifier(),
2323 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00002324}
2325
2326
Chris Lattnere6327742008-04-02 05:18:44 +00002327/// getArrayDecayedType - Return the properly qualified result of decaying the
2328/// specified array type to a pointer. This operation is non-trivial when
2329/// handling typedefs etc. The canonical type of "T" must be an array type,
2330/// this returns a pointer to a properly qualified element of the array.
2331///
2332/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2333QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002334 // Get the element type with 'getAsArrayType' so that we don't lose any
2335 // typedefs in the element type of the array. This also handles propagation
2336 // of type qualifiers from the array type into the element type if present
2337 // (C99 6.7.3p8).
2338 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2339 assert(PrettyArrayType && "Not an array type!");
Chris Lattnere6327742008-04-02 05:18:44 +00002340
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002341 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00002342
2343 // int x[restrict 4] -> int *restrict
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002344 return PtrTy.getQualifiedType(PrettyArrayType->getIndexTypeQualifier());
Chris Lattnere6327742008-04-02 05:18:44 +00002345}
2346
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002347QualType ASTContext::getBaseElementType(QualType QT) {
2348 QualifierSet qualifiers;
2349 while (true) {
2350 const Type *UT = qualifiers.strip(QT);
2351 if (const ArrayType *AT = getAsArrayType(QualType(UT,0))) {
2352 QT = AT->getElementType();
Mike Stump6dcbc292009-07-25 23:24:03 +00002353 } else {
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002354 return qualifiers.apply(QT, *this);
2355 }
2356 }
2357}
2358
Daniel Dunbard786f6a2009-01-05 22:14:37 +00002359QualType ASTContext::getBaseElementType(const VariableArrayType *VAT) {
Anders Carlsson6183a992008-12-21 03:44:36 +00002360 QualType ElemTy = VAT->getElementType();
2361
2362 if (const VariableArrayType *VAT = getAsVariableArrayType(ElemTy))
2363 return getBaseElementType(VAT);
2364
2365 return ElemTy;
2366}
2367
Reid Spencer5f016e22007-07-11 17:01:13 +00002368/// getFloatingRank - Return a relative rank for floating point types.
2369/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00002370static FloatingRank getFloatingRank(QualType T) {
Christopher Lambebb97e92008-02-04 02:31:56 +00002371 if (const ComplexType *CT = T->getAsComplexType())
Reid Spencer5f016e22007-07-11 17:01:13 +00002372 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00002373
Daniel Dunbard786f6a2009-01-05 22:14:37 +00002374 assert(T->getAsBuiltinType() && "getFloatingRank(): not a floating type");
Christopher Lambebb97e92008-02-04 02:31:56 +00002375 switch (T->getAsBuiltinType()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00002376 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002377 case BuiltinType::Float: return FloatRank;
2378 case BuiltinType::Double: return DoubleRank;
2379 case BuiltinType::LongDouble: return LongDoubleRank;
2380 }
2381}
2382
Steve Naroff716c7302007-08-27 01:41:48 +00002383/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2384/// point or a complex type (based on typeDomain/typeSize).
2385/// 'typeDomain' is a real floating point or complex type.
2386/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00002387QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2388 QualType Domain) const {
2389 FloatingRank EltRank = getFloatingRank(Size);
2390 if (Domain->isComplexType()) {
2391 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00002392 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00002393 case FloatRank: return FloatComplexTy;
2394 case DoubleRank: return DoubleComplexTy;
2395 case LongDoubleRank: return LongDoubleComplexTy;
2396 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002397 }
Chris Lattner1361b112008-04-06 23:58:54 +00002398
2399 assert(Domain->isRealFloatingType() && "Unknown domain!");
2400 switch (EltRank) {
2401 default: assert(0 && "getFloatingRank(): illegal value for rank");
2402 case FloatRank: return FloatTy;
2403 case DoubleRank: return DoubleTy;
2404 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00002405 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002406}
2407
Chris Lattner7cfeb082008-04-06 23:55:33 +00002408/// getFloatingTypeOrder - Compare the rank of the two specified floating
2409/// point types, ignoring the domain of the type (i.e. 'double' ==
2410/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
2411/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00002412int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2413 FloatingRank LHSR = getFloatingRank(LHS);
2414 FloatingRank RHSR = getFloatingRank(RHS);
2415
2416 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002417 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00002418 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002419 return 1;
2420 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002421}
2422
Chris Lattnerf52ab252008-04-06 22:59:24 +00002423/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2424/// routine will assert if passed a built-in type that isn't an integer or enum,
2425/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00002426unsigned ASTContext::getIntegerRank(Type *T) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002427 assert(T->isCanonical() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00002428 if (EnumType* ET = dyn_cast<EnumType>(T))
2429 T = ET->getDecl()->getIntegerType().getTypePtr();
2430
Eli Friedmana3426752009-07-05 23:44:27 +00002431 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2432 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2433
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002434 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2435 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2436
2437 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2438 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2439
Eli Friedmanf98aba32009-02-13 02:31:07 +00002440 // There are two things which impact the integer rank: the width, and
2441 // the ordering of builtins. The builtin ordering is encoded in the
2442 // bottom three bits; the width is encoded in the bits above that.
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002443 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T))
Eli Friedmanf98aba32009-02-13 02:31:07 +00002444 return FWIT->getWidth() << 3;
Eli Friedmanf98aba32009-02-13 02:31:07 +00002445
Chris Lattnerf52ab252008-04-06 22:59:24 +00002446 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00002447 default: assert(0 && "getIntegerRank(): not a built-in integer");
2448 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002449 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002450 case BuiltinType::Char_S:
2451 case BuiltinType::Char_U:
2452 case BuiltinType::SChar:
2453 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002454 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002455 case BuiltinType::Short:
2456 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002457 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002458 case BuiltinType::Int:
2459 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002460 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002461 case BuiltinType::Long:
2462 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002463 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002464 case BuiltinType::LongLong:
2465 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002466 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00002467 case BuiltinType::Int128:
2468 case BuiltinType::UInt128:
2469 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00002470 }
2471}
2472
Chris Lattner7cfeb082008-04-06 23:55:33 +00002473/// getIntegerTypeOrder - Returns the highest ranked integer type:
2474/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
2475/// LHS < RHS, return -1.
2476int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002477 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2478 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00002479 if (LHSC == RHSC) return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00002480
Chris Lattnerf52ab252008-04-06 22:59:24 +00002481 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2482 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002483
Chris Lattner7cfeb082008-04-06 23:55:33 +00002484 unsigned LHSRank = getIntegerRank(LHSC);
2485 unsigned RHSRank = getIntegerRank(RHSC);
Reid Spencer5f016e22007-07-11 17:01:13 +00002486
Chris Lattner7cfeb082008-04-06 23:55:33 +00002487 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2488 if (LHSRank == RHSRank) return 0;
2489 return LHSRank > RHSRank ? 1 : -1;
2490 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002491
Chris Lattner7cfeb082008-04-06 23:55:33 +00002492 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2493 if (LHSUnsigned) {
2494 // If the unsigned [LHS] type is larger, return it.
2495 if (LHSRank >= RHSRank)
2496 return 1;
2497
2498 // If the signed type can represent all values of the unsigned type, it
2499 // wins. Because we are dealing with 2's complement and types that are
2500 // powers of two larger than each other, this is always safe.
2501 return -1;
2502 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00002503
Chris Lattner7cfeb082008-04-06 23:55:33 +00002504 // If the unsigned [RHS] type is larger, return it.
2505 if (RHSRank >= LHSRank)
2506 return -1;
2507
2508 // If the signed type can represent all values of the unsigned type, it
2509 // wins. Because we are dealing with 2's complement and types that are
2510 // powers of two larger than each other, this is always safe.
2511 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002512}
Anders Carlsson71993dd2007-08-17 05:31:46 +00002513
2514// getCFConstantStringType - Return the type used for constant CFStrings.
2515QualType ASTContext::getCFConstantStringType() {
2516 if (!CFConstantStringTypeDecl) {
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002517 CFConstantStringTypeDecl =
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002518 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002519 &Idents.get("NSConstantString"));
Anders Carlssonf06273f2007-11-19 00:25:30 +00002520 QualType FieldTypes[4];
Anders Carlsson71993dd2007-08-17 05:31:46 +00002521
2522 // const int *isa;
2523 FieldTypes[0] = getPointerType(IntTy.getQualifiedType(QualType::Const));
Anders Carlssonf06273f2007-11-19 00:25:30 +00002524 // int flags;
2525 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00002526 // const char *str;
Anders Carlssonf06273f2007-11-19 00:25:30 +00002527 FieldTypes[2] = getPointerType(CharTy.getQualifiedType(QualType::Const));
Anders Carlsson71993dd2007-08-17 05:31:46 +00002528 // long length;
Anders Carlssonf06273f2007-11-19 00:25:30 +00002529 FieldTypes[3] = LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002530
Anders Carlsson71993dd2007-08-17 05:31:46 +00002531 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002532 for (unsigned i = 0; i < 4; ++i) {
2533 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
2534 SourceLocation(), 0,
2535 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002536 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002537 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002538 }
2539
2540 CFConstantStringTypeDecl->completeDefinition(*this);
Anders Carlsson71993dd2007-08-17 05:31:46 +00002541 }
2542
2543 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00002544}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002545
Douglas Gregor319ac892009-04-23 22:29:11 +00002546void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002547 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00002548 assert(Rec && "Invalid CFConstantStringType");
2549 CFConstantStringTypeDecl = Rec->getDecl();
2550}
2551
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002552QualType ASTContext::getObjCFastEnumerationStateType()
2553{
2554 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00002555 ObjCFastEnumerationStateTypeDecl =
2556 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2557 &Idents.get("__objcFastEnumerationState"));
2558
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002559 QualType FieldTypes[] = {
2560 UnsignedLongTy,
Steve Naroffde2e22d2009-07-15 18:40:39 +00002561 getPointerType(ObjCIdTypedefType),
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002562 getPointerType(UnsignedLongTy),
2563 getConstantArrayType(UnsignedLongTy,
2564 llvm::APInt(32, 5), ArrayType::Normal, 0)
2565 };
2566
Douglas Gregor44b43212008-12-11 16:49:14 +00002567 for (size_t i = 0; i < 4; ++i) {
2568 FieldDecl *Field = FieldDecl::Create(*this,
2569 ObjCFastEnumerationStateTypeDecl,
2570 SourceLocation(), 0,
2571 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002572 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002573 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002574 }
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002575
Douglas Gregor44b43212008-12-11 16:49:14 +00002576 ObjCFastEnumerationStateTypeDecl->completeDefinition(*this);
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002577 }
2578
2579 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2580}
2581
Douglas Gregor319ac892009-04-23 22:29:11 +00002582void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002583 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00002584 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
2585 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
2586}
2587
Anders Carlssone8c49532007-10-29 06:33:42 +00002588// This returns true if a type has been typedefed to BOOL:
2589// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00002590static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00002591 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00002592 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
2593 return II->isStr("BOOL");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002594
2595 return false;
2596}
2597
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002598/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002599/// purpose.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002600int ASTContext::getObjCEncodingTypeSize(QualType type) {
Chris Lattner98be4942008-03-05 18:54:05 +00002601 uint64_t sz = getTypeSize(type);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002602
2603 // Make all integer and enum types at least as large as an int
2604 if (sz > 0 && type->isIntegralType())
Chris Lattner98be4942008-03-05 18:54:05 +00002605 sz = std::max(sz, getTypeSize(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002606 // Treat arrays as pointers, since that's how they're passed in.
2607 else if (type->isArrayType())
Chris Lattner98be4942008-03-05 18:54:05 +00002608 sz = getTypeSize(VoidPtrTy);
2609 return sz / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002610}
2611
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002612/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002613/// declaration.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002614void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00002615 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002616 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002617 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002618 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002619 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002620 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002621 // Compute size of all parameters.
2622 // Start with computing size of a pointer in number of bytes.
2623 // FIXME: There might(should) be a better way of doing this computation!
2624 SourceLocation Loc;
Chris Lattner98be4942008-03-05 18:54:05 +00002625 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002626 // The first two arguments (self and _cmd) are pointers; account for
2627 // their size.
2628 int ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00002629 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2630 E = Decl->param_end(); PI != E; ++PI) {
2631 QualType PType = (*PI)->getType();
2632 int sz = getObjCEncodingTypeSize(PType);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002633 assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002634 ParmOffset += sz;
2635 }
2636 S += llvm::utostr(ParmOffset);
2637 S += "@0:";
2638 S += llvm::utostr(PtrSize);
2639
2640 // Argument types.
2641 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00002642 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2643 E = Decl->param_end(); PI != E; ++PI) {
2644 ParmVarDecl *PVDecl = *PI;
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00002645 QualType PType = PVDecl->getOriginalType();
2646 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00002647 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
2648 // Use array's original type only if it has known number of
2649 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00002650 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00002651 PType = PVDecl->getType();
2652 } else if (PType->isFunctionType())
2653 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002654 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002655 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00002656 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002657 getObjCEncodingForType(PType, S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002658 S += llvm::utostr(ParmOffset);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002659 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002660 }
2661}
2662
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002663/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00002664/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002665/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
2666/// NULL when getting encodings for protocol properties.
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00002667/// Property attributes are stored as a comma-delimited C string. The simple
2668/// attributes readonly and bycopy are encoded as single characters. The
2669/// parametrized attributes, getter=name, setter=name, and ivar=name, are
2670/// encoded as single characters, followed by an identifier. Property types
2671/// are also encoded as a parametrized attribute. The characters used to encode
2672/// these attributes are defined by the following enumeration:
2673/// @code
2674/// enum PropertyAttributes {
2675/// kPropertyReadOnly = 'R', // property is read-only.
2676/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
2677/// kPropertyByref = '&', // property is a reference to the value last assigned
2678/// kPropertyDynamic = 'D', // property is dynamic
2679/// kPropertyGetter = 'G', // followed by getter selector name
2680/// kPropertySetter = 'S', // followed by setter selector name
2681/// kPropertyInstanceVariable = 'V' // followed by instance variable name
2682/// kPropertyType = 't' // followed by old-style type encoding.
2683/// kPropertyWeak = 'W' // 'weak' property
2684/// kPropertyStrong = 'P' // property GC'able
2685/// kPropertyNonAtomic = 'N' // property non-atomic
2686/// };
2687/// @endcode
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002688void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
2689 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00002690 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002691 // Collect information from the property implementation decl(s).
2692 bool Dynamic = false;
2693 ObjCPropertyImplDecl *SynthesizePID = 0;
2694
2695 // FIXME: Duplicated code due to poor abstraction.
2696 if (Container) {
2697 if (const ObjCCategoryImplDecl *CID =
2698 dyn_cast<ObjCCategoryImplDecl>(Container)) {
2699 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002700 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00002701 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002702 ObjCPropertyImplDecl *PID = *i;
2703 if (PID->getPropertyDecl() == PD) {
2704 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2705 Dynamic = true;
2706 } else {
2707 SynthesizePID = PID;
2708 }
2709 }
2710 }
2711 } else {
Chris Lattner61710852008-10-05 17:34:18 +00002712 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002713 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002714 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00002715 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002716 ObjCPropertyImplDecl *PID = *i;
2717 if (PID->getPropertyDecl() == PD) {
2718 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2719 Dynamic = true;
2720 } else {
2721 SynthesizePID = PID;
2722 }
2723 }
2724 }
2725 }
2726 }
2727
2728 // FIXME: This is not very efficient.
2729 S = "T";
2730
2731 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002732 // GCC has some special rules regarding encoding of properties which
2733 // closely resembles encoding of ivars.
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002734 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002735 true /* outermost type */,
2736 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002737
2738 if (PD->isReadOnly()) {
2739 S += ",R";
2740 } else {
2741 switch (PD->getSetterKind()) {
2742 case ObjCPropertyDecl::Assign: break;
2743 case ObjCPropertyDecl::Copy: S += ",C"; break;
2744 case ObjCPropertyDecl::Retain: S += ",&"; break;
2745 }
2746 }
2747
2748 // It really isn't clear at all what this means, since properties
2749 // are "dynamic by default".
2750 if (Dynamic)
2751 S += ",D";
2752
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002753 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
2754 S += ",N";
2755
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002756 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
2757 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002758 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002759 }
2760
2761 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
2762 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002763 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002764 }
2765
2766 if (SynthesizePID) {
2767 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
2768 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00002769 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002770 }
2771
2772 // FIXME: OBJCGC: weak & strong
2773}
2774
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002775/// getLegacyIntegralTypeEncoding -
2776/// Another legacy compatibility encoding: 32-bit longs are encoded as
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002777/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002778/// 'i' or 'I' instead if encoding a struct field, or a pointer!
2779///
2780void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00002781 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002782 if (const BuiltinType *BT = PointeeTy->getAsBuiltinType()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002783 if (BT->getKind() == BuiltinType::ULong &&
2784 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002785 PointeeTy = UnsignedIntTy;
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002786 else
2787 if (BT->getKind() == BuiltinType::Long &&
2788 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002789 PointeeTy = IntTy;
2790 }
2791 }
2792}
2793
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002794void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002795 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002796 // We follow the behavior of gcc, expanding structures which are
2797 // directly pointed to, and expanding embedded structures. Note that
2798 // these rules are sufficient to prevent recursive encoding of the
2799 // same type.
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00002800 getObjCEncodingForTypeImpl(T, S, true, true, Field,
2801 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002802}
2803
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002804static void EncodeBitField(const ASTContext *Context, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002805 const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002806 const Expr *E = FD->getBitWidth();
2807 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
2808 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Eli Friedman9a901bb2009-04-26 19:19:15 +00002809 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002810 S += 'b';
2811 S += llvm::utostr(N);
2812}
2813
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002814void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
2815 bool ExpandPointedToStructures,
2816 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002817 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002818 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002819 bool EncodingProperty) {
Anders Carlssone8c49532007-10-29 06:33:42 +00002820 if (const BuiltinType *BT = T->getAsBuiltinType()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002821 if (FD && FD->isBitField())
2822 return EncodeBitField(this, S, FD);
2823 char encoding;
2824 switch (BT->getKind()) {
2825 default: assert(0 && "Unhandled builtin type kind");
2826 case BuiltinType::Void: encoding = 'v'; break;
2827 case BuiltinType::Bool: encoding = 'B'; break;
2828 case BuiltinType::Char_U:
2829 case BuiltinType::UChar: encoding = 'C'; break;
2830 case BuiltinType::UShort: encoding = 'S'; break;
2831 case BuiltinType::UInt: encoding = 'I'; break;
2832 case BuiltinType::ULong:
Fariborz Jahanian72696e12009-02-11 22:31:45 +00002833 encoding =
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002834 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
Fariborz Jahanian72696e12009-02-11 22:31:45 +00002835 break;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002836 case BuiltinType::UInt128: encoding = 'T'; break;
2837 case BuiltinType::ULongLong: encoding = 'Q'; break;
2838 case BuiltinType::Char_S:
2839 case BuiltinType::SChar: encoding = 'c'; break;
2840 case BuiltinType::Short: encoding = 's'; break;
2841 case BuiltinType::Int: encoding = 'i'; break;
2842 case BuiltinType::Long:
2843 encoding =
2844 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
2845 break;
2846 case BuiltinType::LongLong: encoding = 'q'; break;
2847 case BuiltinType::Int128: encoding = 't'; break;
2848 case BuiltinType::Float: encoding = 'f'; break;
2849 case BuiltinType::Double: encoding = 'd'; break;
2850 case BuiltinType::LongDouble: encoding = 'd'; break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002851 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002852
2853 S += encoding;
2854 return;
2855 }
2856
2857 if (const ComplexType *CT = T->getAsComplexType()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00002858 S += 'j';
2859 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
2860 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002861 return;
2862 }
2863
Ted Kremenek6217b802009-07-29 21:53:49 +00002864 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002865 QualType PointeeTy = PT->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002866 bool isReadOnly = false;
2867 // For historical/compatibility reasons, the read-only qualifier of the
2868 // pointee gets emitted _before_ the '^'. The read-only qualifier of
2869 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
2870 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00002871 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002872 if (OutermostType && T.isConstQualified()) {
2873 isReadOnly = true;
2874 S += 'r';
2875 }
Mike Stump9fdbab32009-07-31 02:02:20 +00002876 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002877 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00002878 while (P->getAs<PointerType>())
2879 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002880 if (P.isConstQualified()) {
2881 isReadOnly = true;
2882 S += 'r';
2883 }
2884 }
2885 if (isReadOnly) {
2886 // Another legacy compatibility encoding. Some ObjC qualifier and type
2887 // combinations need to be rearranged.
2888 // Rewrite "in const" from "nr" to "rn"
2889 const char * s = S.c_str();
2890 int len = S.length();
2891 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
2892 std::string replace = "rn";
2893 S.replace(S.end()-2, S.end(), replace);
2894 }
2895 }
Steve Naroff14108da2009-07-10 23:34:53 +00002896 if (isObjCSelType(PointeeTy)) {
Anders Carlsson8baaca52007-10-31 02:53:19 +00002897 S += ':';
2898 return;
Fariborz Jahanianc2939bc2007-10-30 17:06:23 +00002899 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002900
2901 if (PointeeTy->isCharType()) {
2902 // char pointer types should be encoded as '*' unless it is a
2903 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00002904 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002905 S += '*';
2906 return;
2907 }
Ted Kremenek6217b802009-07-29 21:53:49 +00002908 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00002909 // GCC binary compat: Need to convert "struct objc_class *" to "#".
2910 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
2911 S += '#';
2912 return;
2913 }
2914 // GCC binary compat: Need to convert "struct objc_object *" to "@".
2915 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
2916 S += '@';
2917 return;
2918 }
2919 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002920 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002921 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002922 getLegacyIntegralTypeEncoding(PointeeTy);
2923
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002924 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002925 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002926 return;
2927 }
2928
2929 if (const ArrayType *AT =
2930 // Ignore type qualifiers etc.
2931 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00002932 if (isa<IncompleteArrayType>(AT)) {
2933 // Incomplete arrays are encoded as a pointer to the array element.
2934 S += '^';
2935
2936 getObjCEncodingForTypeImpl(AT->getElementType(), S,
2937 false, ExpandStructures, FD);
2938 } else {
2939 S += '[';
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002940
Anders Carlsson559a8332009-02-22 01:38:57 +00002941 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
2942 S += llvm::utostr(CAT->getSize().getZExtValue());
2943 else {
2944 //Variable length arrays are encoded as a regular array with 0 elements.
2945 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
2946 S += '0';
2947 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002948
Anders Carlsson559a8332009-02-22 01:38:57 +00002949 getObjCEncodingForTypeImpl(AT->getElementType(), S,
2950 false, ExpandStructures, FD);
2951 S += ']';
2952 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002953 return;
2954 }
2955
2956 if (T->getAsFunctionType()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00002957 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002958 return;
2959 }
2960
Ted Kremenek6217b802009-07-29 21:53:49 +00002961 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002962 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002963 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00002964 // Anonymous structures print as '?'
2965 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
2966 S += II->getName();
2967 } else {
2968 S += '?';
2969 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002970 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002971 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002972 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
2973 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00002974 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002975 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002976 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00002977 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002978 S += '"';
2979 }
2980
2981 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002982 if (Field->isBitField()) {
2983 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
2984 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002985 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002986 QualType qt = Field->getType();
2987 getLegacyIntegralTypeEncoding(qt);
2988 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002989 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002990 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002991 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00002992 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002993 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00002994 return;
2995 }
2996
2997 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002998 if (FD && FD->isBitField())
2999 EncodeBitField(this, S, FD);
3000 else
3001 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003002 return;
3003 }
3004
3005 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00003006 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003007 return;
3008 }
3009
3010 if (T->isObjCInterfaceType()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003011 // @encode(class_name)
3012 ObjCInterfaceDecl *OI = T->getAsObjCInterfaceType()->getDecl();
3013 S += '{';
3014 const IdentifierInfo *II = OI->getIdentifier();
3015 S += II->getName();
3016 S += '=';
Chris Lattnerf1690852009-03-31 08:48:01 +00003017 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003018 CollectObjCIvars(OI, RecFields);
Chris Lattnerf1690852009-03-31 08:48:01 +00003019 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003020 if (RecFields[i]->isBitField())
3021 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
3022 RecFields[i]);
3023 else
3024 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
3025 FD);
3026 }
3027 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003028 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003029 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003030
3031 if (const ObjCObjectPointerType *OPT = T->getAsObjCObjectPointerType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003032 if (OPT->isObjCIdType()) {
3033 S += '@';
3034 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003035 }
3036
3037 if (OPT->isObjCClassType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003038 S += '#';
3039 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003040 }
3041
3042 if (OPT->isObjCQualifiedIdType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003043 getObjCEncodingForTypeImpl(getObjCIdType(), S,
3044 ExpandPointedToStructures,
3045 ExpandStructures, FD);
3046 if (FD || EncodingProperty) {
3047 // Note that we do extended encoding of protocol qualifer list
3048 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00003049 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003050 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3051 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00003052 S += '<';
3053 S += (*I)->getNameAsString();
3054 S += '>';
3055 }
3056 S += '"';
3057 }
3058 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003059 }
3060
3061 QualType PointeeTy = OPT->getPointeeType();
3062 if (!EncodingProperty &&
3063 isa<TypedefType>(PointeeTy.getTypePtr())) {
3064 // Another historical/compatibility reason.
3065 // We encode the underlying type which comes out as
3066 // {...};
3067 S += '^';
3068 getObjCEncodingForTypeImpl(PointeeTy, S,
3069 false, ExpandPointedToStructures,
3070 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00003071 return;
3072 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003073
3074 S += '@';
3075 if (FD || EncodingProperty) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003076 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003077 S += OPT->getInterfaceDecl()->getNameAsCString();
3078 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3079 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003080 S += '<';
3081 S += (*I)->getNameAsString();
3082 S += '>';
3083 }
3084 S += '"';
3085 }
3086 return;
3087 }
3088
3089 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003090}
3091
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003092void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003093 std::string& S) const {
3094 if (QT & Decl::OBJC_TQ_In)
3095 S += 'n';
3096 if (QT & Decl::OBJC_TQ_Inout)
3097 S += 'N';
3098 if (QT & Decl::OBJC_TQ_Out)
3099 S += 'o';
3100 if (QT & Decl::OBJC_TQ_Bycopy)
3101 S += 'O';
3102 if (QT & Decl::OBJC_TQ_Byref)
3103 S += 'R';
3104 if (QT & Decl::OBJC_TQ_Oneway)
3105 S += 'V';
3106}
3107
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003108void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003109 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
3110
3111 BuiltinVaListType = T;
3112}
3113
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003114void ASTContext::setObjCIdType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003115 ObjCIdTypedefType = T;
Steve Naroff7e219e42007-10-15 14:41:52 +00003116}
3117
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003118void ASTContext::setObjCSelType(QualType T) {
Douglas Gregor319ac892009-04-23 22:29:11 +00003119 ObjCSelType = T;
3120
3121 const TypedefType *TT = T->getAsTypedefType();
3122 if (!TT)
3123 return;
3124 TypedefDecl *TD = TT->getDecl();
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003125
3126 // typedef struct objc_selector *SEL;
Ted Kremenek6217b802009-07-29 21:53:49 +00003127 const PointerType *ptr = TD->getUnderlyingType()->getAs<PointerType>();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00003128 if (!ptr)
3129 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003130 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00003131 if (!rec)
3132 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003133 SelStructType = rec;
3134}
3135
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003136void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003137 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00003138}
3139
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003140void ASTContext::setObjCClassType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003141 ObjCClassTypedefType = T;
Anders Carlsson8baaca52007-10-31 02:53:19 +00003142}
3143
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003144void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
3145 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00003146 "'NSConstantString' type already set!");
3147
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003148 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00003149}
3150
Douglas Gregor7532dc62009-03-30 22:58:21 +00003151/// \brief Retrieve the template name that represents a qualified
3152/// template name such as \c std::vector.
3153TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
3154 bool TemplateKeyword,
3155 TemplateDecl *Template) {
3156 llvm::FoldingSetNodeID ID;
3157 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3158
3159 void *InsertPos = 0;
3160 QualifiedTemplateName *QTN =
3161 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3162 if (!QTN) {
3163 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3164 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3165 }
3166
3167 return TemplateName(QTN);
3168}
3169
Douglas Gregord99cbe62009-07-29 18:26:50 +00003170/// \brief Retrieve the template name that represents a qualified
3171/// template name such as \c std::vector.
3172TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
3173 bool TemplateKeyword,
3174 OverloadedFunctionDecl *Template) {
3175 llvm::FoldingSetNodeID ID;
3176 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3177
3178 void *InsertPos = 0;
3179 QualifiedTemplateName *QTN =
3180 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3181 if (!QTN) {
3182 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3183 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3184 }
3185
3186 return TemplateName(QTN);
3187}
3188
Douglas Gregor7532dc62009-03-30 22:58:21 +00003189/// \brief Retrieve the template name that represents a dependent
3190/// template name such as \c MetaFun::template apply.
3191TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
3192 const IdentifierInfo *Name) {
3193 assert(NNS->isDependent() && "Nested name specifier must be dependent");
3194
3195 llvm::FoldingSetNodeID ID;
3196 DependentTemplateName::Profile(ID, NNS, Name);
3197
3198 void *InsertPos = 0;
3199 DependentTemplateName *QTN =
3200 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3201
3202 if (QTN)
3203 return TemplateName(QTN);
3204
3205 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3206 if (CanonNNS == NNS) {
3207 QTN = new (*this,4) DependentTemplateName(NNS, Name);
3208 } else {
3209 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
3210 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
3211 }
3212
3213 DependentTemplateNames.InsertNode(QTN, InsertPos);
3214 return TemplateName(QTN);
3215}
3216
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003217/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00003218/// TargetInfo, produce the corresponding type. The unsigned @p Type
3219/// is actually a value of type @c TargetInfo::IntType.
3220QualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003221 switch (Type) {
3222 case TargetInfo::NoInt: return QualType();
3223 case TargetInfo::SignedShort: return ShortTy;
3224 case TargetInfo::UnsignedShort: return UnsignedShortTy;
3225 case TargetInfo::SignedInt: return IntTy;
3226 case TargetInfo::UnsignedInt: return UnsignedIntTy;
3227 case TargetInfo::SignedLong: return LongTy;
3228 case TargetInfo::UnsignedLong: return UnsignedLongTy;
3229 case TargetInfo::SignedLongLong: return LongLongTy;
3230 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
3231 }
3232
3233 assert(false && "Unhandled TargetInfo::IntType value");
Daniel Dunbarb3ac5432008-11-11 01:16:00 +00003234 return QualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003235}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003236
3237//===----------------------------------------------------------------------===//
3238// Type Predicates.
3239//===----------------------------------------------------------------------===//
3240
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003241/// isObjCNSObjectType - Return true if this is an NSObject object using
3242/// NSObject attribute on a c-style pointer type.
3243/// FIXME - Make it work directly on types.
Steve Narofff4954562009-07-16 15:41:00 +00003244/// FIXME: Move to Type.
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003245///
3246bool ASTContext::isObjCNSObjectType(QualType Ty) const {
3247 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
3248 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003249 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003250 return true;
3251 }
3252 return false;
3253}
3254
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003255/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
3256/// garbage collection attribute.
3257///
3258QualType::GCAttrTypes ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
Chris Lattnerb7d25532009-02-18 22:53:11 +00003259 QualType::GCAttrTypes GCAttrs = QualType::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003260 if (getLangOptions().ObjC1 &&
3261 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00003262 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003263 // Default behavious under objective-c's gc is for objective-c pointers
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003264 // (or pointers to them) be treated as though they were declared
3265 // as __strong.
3266 if (GCAttrs == QualType::GCNone) {
Steve Narofff4954562009-07-16 15:41:00 +00003267 if (Ty->isObjCObjectPointerType())
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003268 GCAttrs = QualType::Strong;
3269 else if (Ty->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00003270 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003271 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00003272 // Non-pointers have none gc'able attribute regardless of the attribute
3273 // set on them.
Steve Narofff4954562009-07-16 15:41:00 +00003274 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
Fariborz Jahanianc2112182009-04-11 00:00:54 +00003275 return QualType::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003276 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00003277 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003278}
3279
Chris Lattner6ac46a42008-04-07 06:51:04 +00003280//===----------------------------------------------------------------------===//
3281// Type Compatibility Testing
3282//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00003283
Chris Lattner6ac46a42008-04-07 06:51:04 +00003284/// areCompatVectorTypes - Return true if the two specified vector types are
3285/// compatible.
3286static bool areCompatVectorTypes(const VectorType *LHS,
3287 const VectorType *RHS) {
3288 assert(LHS->isCanonical() && RHS->isCanonical());
3289 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00003290 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00003291}
3292
Steve Naroff4084c302009-07-23 01:01:38 +00003293//===----------------------------------------------------------------------===//
3294// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
3295//===----------------------------------------------------------------------===//
3296
3297/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
3298/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003299bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
3300 ObjCProtocolDecl *rProto) {
Steve Naroff4084c302009-07-23 01:01:38 +00003301 if (lProto == rProto)
3302 return true;
3303 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
3304 E = rProto->protocol_end(); PI != E; ++PI)
3305 if (ProtocolCompatibleWithProtocol(lProto, *PI))
3306 return true;
3307 return false;
3308}
3309
Steve Naroff4084c302009-07-23 01:01:38 +00003310/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
3311/// return true if lhs's protocols conform to rhs's protocol; false
3312/// otherwise.
3313bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
3314 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
3315 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
3316 return false;
3317}
3318
3319/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
3320/// ObjCQualifiedIDType.
3321bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
3322 bool compare) {
3323 // Allow id<P..> and an 'id' or void* type in all cases.
3324 if (lhs->isVoidPointerType() ||
3325 lhs->isObjCIdType() || lhs->isObjCClassType())
3326 return true;
3327 else if (rhs->isVoidPointerType() ||
3328 rhs->isObjCIdType() || rhs->isObjCClassType())
3329 return true;
3330
3331 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
3332 const ObjCObjectPointerType *rhsOPT = rhs->getAsObjCObjectPointerType();
3333
3334 if (!rhsOPT) return false;
3335
3336 if (rhsOPT->qual_empty()) {
3337 // If the RHS is a unqualified interface pointer "NSString*",
3338 // make sure we check the class hierarchy.
3339 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
3340 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3341 E = lhsQID->qual_end(); I != E; ++I) {
3342 // when comparing an id<P> on lhs with a static type on rhs,
3343 // see if static class implements all of id's protocols, directly or
3344 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003345 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00003346 return false;
3347 }
3348 }
3349 // If there are no qualifiers and no interface, we have an 'id'.
3350 return true;
3351 }
3352 // Both the right and left sides have qualifiers.
3353 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3354 E = lhsQID->qual_end(); I != E; ++I) {
3355 ObjCProtocolDecl *lhsProto = *I;
3356 bool match = false;
3357
3358 // when comparing an id<P> on lhs with a static type on rhs,
3359 // see if static class implements all of id's protocols, directly or
3360 // through its super class and categories.
3361 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
3362 E = rhsOPT->qual_end(); J != E; ++J) {
3363 ObjCProtocolDecl *rhsProto = *J;
3364 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
3365 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
3366 match = true;
3367 break;
3368 }
3369 }
3370 // If the RHS is a qualified interface pointer "NSString<P>*",
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 match = true;
3380 break;
3381 }
3382 }
3383 }
3384 if (!match)
3385 return false;
3386 }
3387
3388 return true;
3389 }
3390
3391 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
3392 assert(rhsQID && "One of the LHS/RHS should be id<x>");
3393
3394 if (const ObjCObjectPointerType *lhsOPT =
3395 lhs->getAsObjCInterfacePointerType()) {
3396 if (lhsOPT->qual_empty()) {
3397 bool match = false;
3398 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
3399 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
3400 E = rhsQID->qual_end(); I != E; ++I) {
3401 // when comparing an id<P> on lhs with a static type on rhs,
3402 // see if static class implements all of id's protocols, directly or
3403 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003404 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00003405 match = true;
3406 break;
3407 }
3408 }
3409 if (!match)
3410 return false;
3411 }
3412 return true;
3413 }
3414 // Both the right and left sides have qualifiers.
3415 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
3416 E = lhsOPT->qual_end(); I != E; ++I) {
3417 ObjCProtocolDecl *lhsProto = *I;
3418 bool match = false;
3419
3420 // when comparing an id<P> on lhs with a static type on rhs,
3421 // see if static class implements all of id's protocols, directly or
3422 // through its super class and categories.
3423 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
3424 E = rhsQID->qual_end(); J != E; ++J) {
3425 ObjCProtocolDecl *rhsProto = *J;
3426 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
3427 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
3428 match = true;
3429 break;
3430 }
3431 }
3432 if (!match)
3433 return false;
3434 }
3435 return true;
3436 }
3437 return false;
3438}
3439
Eli Friedman3d815e72008-08-22 00:56:42 +00003440/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00003441/// compatible for assignment from RHS to LHS. This handles validation of any
3442/// protocol qualifiers on the LHS or RHS.
3443///
Steve Naroff14108da2009-07-10 23:34:53 +00003444bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
3445 const ObjCObjectPointerType *RHSOPT) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003446 // If either type represents the built-in 'id' or 'Class' types, return true.
3447 if (LHSOPT->isObjCBuiltinType() || RHSOPT->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00003448 return true;
3449
Steve Naroff4084c302009-07-23 01:01:38 +00003450 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
3451 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
3452 QualType(RHSOPT,0),
3453 false);
3454
Steve Naroff14108da2009-07-10 23:34:53 +00003455 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
3456 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
Steve Naroff4084c302009-07-23 01:01:38 +00003457 if (LHS && RHS) // We have 2 user-defined types.
3458 return canAssignObjCInterfaces(LHS, RHS);
3459
3460 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00003461}
3462
Eli Friedman3d815e72008-08-22 00:56:42 +00003463bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
3464 const ObjCInterfaceType *RHS) {
Chris Lattner6ac46a42008-04-07 06:51:04 +00003465 // Verify that the base decls are compatible: the RHS must be a subclass of
3466 // the LHS.
3467 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
3468 return false;
3469
3470 // RHS must have a superset of the protocols in the LHS. If the LHS is not
3471 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00003472 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00003473 return true;
3474
3475 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
3476 // isn't a superset.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00003477 if (RHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00003478 return true; // FIXME: should return false!
3479
Steve Naroffc15cb2a2009-07-18 15:33:26 +00003480 for (ObjCInterfaceType::qual_iterator LHSPI = LHS->qual_begin(),
3481 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003482 LHSPI != LHSPE; LHSPI++) {
3483 bool RHSImplementsProtocol = false;
3484
3485 // If the RHS doesn't implement the protocol on the left, the types
3486 // are incompatible.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00003487 for (ObjCInterfaceType::qual_iterator RHSPI = RHS->qual_begin(),
Steve Naroff4084c302009-07-23 01:01:38 +00003488 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00003489 RHSPI != RHSPE; RHSPI++) {
3490 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003491 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00003492 break;
3493 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003494 }
3495 // FIXME: For better diagnostics, consider passing back the protocol name.
3496 if (!RHSImplementsProtocol)
3497 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00003498 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003499 // The RHS implements all protocols listed on the LHS.
3500 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00003501}
3502
Steve Naroff389bf462009-02-12 17:52:19 +00003503bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
3504 // get the "pointed to" types
Steve Naroff14108da2009-07-10 23:34:53 +00003505 const ObjCObjectPointerType *LHSOPT = LHS->getAsObjCObjectPointerType();
3506 const ObjCObjectPointerType *RHSOPT = RHS->getAsObjCObjectPointerType();
Steve Naroff389bf462009-02-12 17:52:19 +00003507
Steve Naroff14108da2009-07-10 23:34:53 +00003508 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00003509 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00003510
3511 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
3512 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00003513}
3514
Steve Naroffec0550f2007-10-15 20:41:53 +00003515/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
3516/// both shall have the identically qualified version of a compatible type.
3517/// C99 6.2.7p1: Two types have compatible types if their types are the
3518/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman3d815e72008-08-22 00:56:42 +00003519bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
3520 return !mergeTypes(LHS, RHS).isNull();
3521}
3522
3523QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
3524 const FunctionType *lbase = lhs->getAsFunctionType();
3525 const FunctionType *rbase = rhs->getAsFunctionType();
Douglas Gregor72564e72009-02-26 23:50:07 +00003526 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
3527 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00003528 bool allLTypes = true;
3529 bool allRTypes = true;
3530
3531 // Check return type
3532 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
3533 if (retType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00003534 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
3535 allLTypes = false;
3536 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
3537 allRTypes = false;
Mike Stump6dcbc292009-07-25 23:24:03 +00003538 // FIXME: double check this
Mike Stump24556362009-07-25 21:26:53 +00003539 bool NoReturn = lbase->getNoReturnAttr() || rbase->getNoReturnAttr();
3540 if (NoReturn != lbase->getNoReturnAttr())
3541 allLTypes = false;
3542 if (NoReturn != rbase->getNoReturnAttr())
3543 allRTypes = false;
3544
Eli Friedman3d815e72008-08-22 00:56:42 +00003545 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00003546 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
3547 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00003548 unsigned lproto_nargs = lproto->getNumArgs();
3549 unsigned rproto_nargs = rproto->getNumArgs();
3550
3551 // Compatible functions must have the same number of arguments
3552 if (lproto_nargs != rproto_nargs)
3553 return QualType();
3554
3555 // Variadic and non-variadic functions aren't compatible
3556 if (lproto->isVariadic() != rproto->isVariadic())
3557 return QualType();
3558
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003559 if (lproto->getTypeQuals() != rproto->getTypeQuals())
3560 return QualType();
3561
Eli Friedman3d815e72008-08-22 00:56:42 +00003562 // Check argument compatibility
3563 llvm::SmallVector<QualType, 10> types;
3564 for (unsigned i = 0; i < lproto_nargs; i++) {
3565 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
3566 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
3567 QualType argtype = mergeTypes(largtype, rargtype);
3568 if (argtype.isNull()) return QualType();
3569 types.push_back(argtype);
Chris Lattner61710852008-10-05 17:34:18 +00003570 if (getCanonicalType(argtype) != getCanonicalType(largtype))
3571 allLTypes = false;
3572 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
3573 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00003574 }
3575 if (allLTypes) return lhs;
3576 if (allRTypes) return rhs;
3577 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump24556362009-07-25 21:26:53 +00003578 lproto->isVariadic(), lproto->getTypeQuals(),
3579 NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00003580 }
3581
3582 if (lproto) allRTypes = false;
3583 if (rproto) allLTypes = false;
3584
Douglas Gregor72564e72009-02-26 23:50:07 +00003585 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00003586 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00003587 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00003588 if (proto->isVariadic()) return QualType();
3589 // Check that the types are compatible with the types that
3590 // would result from default argument promotions (C99 6.7.5.3p15).
3591 // The only types actually affected are promotable integer
3592 // types and floats, which would be passed as a different
3593 // type depending on whether the prototype is visible.
3594 unsigned proto_nargs = proto->getNumArgs();
3595 for (unsigned i = 0; i < proto_nargs; ++i) {
3596 QualType argTy = proto->getArgType(i);
3597 if (argTy->isPromotableIntegerType() ||
3598 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
3599 return QualType();
3600 }
3601
3602 if (allLTypes) return lhs;
3603 if (allRTypes) return rhs;
3604 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump2d3c1912009-07-27 00:44:23 +00003605 proto->getNumArgs(), proto->isVariadic(),
3606 proto->getTypeQuals(), NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00003607 }
3608
3609 if (allLTypes) return lhs;
3610 if (allRTypes) return rhs;
Mike Stump24556362009-07-25 21:26:53 +00003611 return getFunctionNoProtoType(retType, NoReturn);
Eli Friedman3d815e72008-08-22 00:56:42 +00003612}
3613
3614QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
Bill Wendling43d69752007-12-03 07:33:35 +00003615 // C++ [expr]: If an expression initially has the type "reference to T", the
3616 // type is adjusted to "T" prior to any further analysis, the expression
3617 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003618 // expression is an lvalue unless the reference is an rvalue reference and
3619 // the expression is a function call (possibly inside parentheses).
Eli Friedman3d815e72008-08-22 00:56:42 +00003620 // FIXME: C++ shouldn't be going through here! The rules are different
3621 // enough that they should be handled separately.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003622 // FIXME: Merging of lvalue and rvalue references is incorrect. C++ *really*
3623 // shouldn't be going through here!
Ted Kremenek6217b802009-07-29 21:53:49 +00003624 if (const ReferenceType *RT = LHS->getAs<ReferenceType>())
Chris Lattnerc4e40592008-04-07 04:07:56 +00003625 LHS = RT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003626 if (const ReferenceType *RT = RHS->getAs<ReferenceType>())
Chris Lattnerc4e40592008-04-07 04:07:56 +00003627 RHS = RT->getPointeeType();
Chris Lattnerf3692dc2008-04-07 05:37:56 +00003628
Eli Friedman3d815e72008-08-22 00:56:42 +00003629 QualType LHSCan = getCanonicalType(LHS),
3630 RHSCan = getCanonicalType(RHS);
3631
3632 // If two types are identical, they are compatible.
3633 if (LHSCan == RHSCan)
3634 return LHS;
3635
3636 // If the qualifiers are different, the types aren't compatible
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003637 // Note that we handle extended qualifiers later, in the
3638 // case for ExtQualType.
3639 if (LHSCan.getCVRQualifiers() != RHSCan.getCVRQualifiers())
Eli Friedman3d815e72008-08-22 00:56:42 +00003640 return QualType();
3641
Eli Friedman852d63b2009-06-01 01:22:52 +00003642 Type::TypeClass LHSClass = LHSCan->getTypeClass();
3643 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00003644
Chris Lattner1adb8832008-01-14 05:45:46 +00003645 // We want to consider the two function types to be the same for these
3646 // comparisons, just force one to the other.
3647 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
3648 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00003649
Eli Friedman07d25872009-06-02 05:28:56 +00003650 // Strip off objc_gc attributes off the top level so they can be merged.
3651 // This is a complete mess, but the attribute itself doesn't make much sense.
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003652 if (RHSClass == Type::ExtQual) {
Eli Friedman07d25872009-06-02 05:28:56 +00003653 QualType::GCAttrTypes GCAttr = RHSCan.getObjCGCAttr();
3654 if (GCAttr != QualType::GCNone) {
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003655 QualType::GCAttrTypes GCLHSAttr = LHSCan.getObjCGCAttr();
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003656 // __weak attribute must appear on both declarations.
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003657 // __strong attribue is redundant if other decl is an objective-c
3658 // object pointer (or decorated with __strong attribute); otherwise
3659 // issue error.
3660 if ((GCAttr == QualType::Weak && GCLHSAttr != GCAttr) ||
3661 (GCAttr == QualType::Strong && GCLHSAttr != GCAttr &&
Steve Naroff14108da2009-07-10 23:34:53 +00003662 !LHSCan->isObjCObjectPointerType()))
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003663 return QualType();
3664
Eli Friedman07d25872009-06-02 05:28:56 +00003665 RHS = QualType(cast<ExtQualType>(RHS.getDesugaredType())->getBaseType(),
3666 RHS.getCVRQualifiers());
3667 QualType Result = mergeTypes(LHS, RHS);
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003668 if (!Result.isNull()) {
3669 if (Result.getObjCGCAttr() == QualType::GCNone)
3670 Result = getObjCGCQualType(Result, GCAttr);
3671 else if (Result.getObjCGCAttr() != GCAttr)
3672 Result = QualType();
3673 }
Eli Friedman07d25872009-06-02 05:28:56 +00003674 return Result;
3675 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003676 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003677 if (LHSClass == Type::ExtQual) {
Eli Friedman07d25872009-06-02 05:28:56 +00003678 QualType::GCAttrTypes GCAttr = LHSCan.getObjCGCAttr();
3679 if (GCAttr != QualType::GCNone) {
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003680 QualType::GCAttrTypes GCRHSAttr = RHSCan.getObjCGCAttr();
3681 // __weak attribute must appear on both declarations. __strong
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003682 // __strong attribue is redundant if other decl is an objective-c
3683 // object pointer (or decorated with __strong attribute); otherwise
3684 // issue error.
3685 if ((GCAttr == QualType::Weak && GCRHSAttr != GCAttr) ||
3686 (GCAttr == QualType::Strong && GCRHSAttr != GCAttr &&
Steve Naroff14108da2009-07-10 23:34:53 +00003687 !RHSCan->isObjCObjectPointerType()))
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003688 return QualType();
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003689
Eli Friedman07d25872009-06-02 05:28:56 +00003690 LHS = QualType(cast<ExtQualType>(LHS.getDesugaredType())->getBaseType(),
3691 LHS.getCVRQualifiers());
3692 QualType Result = mergeTypes(LHS, RHS);
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003693 if (!Result.isNull()) {
3694 if (Result.getObjCGCAttr() == QualType::GCNone)
3695 Result = getObjCGCQualType(Result, GCAttr);
3696 else if (Result.getObjCGCAttr() != GCAttr)
3697 Result = QualType();
3698 }
Eli Friedman354e53d2009-06-02 07:45:37 +00003699 return Result;
Eli Friedman07d25872009-06-02 05:28:56 +00003700 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003701 }
3702
Eli Friedman4c721d32008-02-12 08:23:06 +00003703 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00003704 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
3705 LHSClass = Type::ConstantArray;
3706 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
3707 RHSClass = Type::ConstantArray;
Steve Naroffec0550f2007-10-15 20:41:53 +00003708
Nate Begeman213541a2008-04-18 23:10:10 +00003709 // Canonicalize ExtVector -> Vector.
3710 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
3711 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Chris Lattnera36a61f2008-04-07 05:43:21 +00003712
3713 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00003714 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00003715 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
3716 // a signed integer type, or an unsigned integer type.
Eli Friedman3d815e72008-08-22 00:56:42 +00003717 if (const EnumType* ETy = LHS->getAsEnumType()) {
3718 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
3719 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00003720 }
Eli Friedman3d815e72008-08-22 00:56:42 +00003721 if (const EnumType* ETy = RHS->getAsEnumType()) {
3722 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
3723 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00003724 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003725
Eli Friedman3d815e72008-08-22 00:56:42 +00003726 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00003727 }
Eli Friedman3d815e72008-08-22 00:56:42 +00003728
Steve Naroff4a746782008-01-09 22:43:08 +00003729 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00003730 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00003731#define TYPE(Class, Base)
3732#define ABSTRACT_TYPE(Class, Base)
3733#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3734#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3735#include "clang/AST/TypeNodes.def"
3736 assert(false && "Non-canonical and dependent types shouldn't get here");
3737 return QualType();
3738
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003739 case Type::LValueReference:
3740 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00003741 case Type::MemberPointer:
3742 assert(false && "C++ should never be in mergeTypes");
3743 return QualType();
3744
3745 case Type::IncompleteArray:
3746 case Type::VariableArray:
3747 case Type::FunctionProto:
3748 case Type::ExtVector:
Douglas Gregor72564e72009-02-26 23:50:07 +00003749 assert(false && "Types are eliminated above");
3750 return QualType();
3751
Chris Lattner1adb8832008-01-14 05:45:46 +00003752 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00003753 {
3754 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00003755 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
3756 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Eli Friedman3d815e72008-08-22 00:56:42 +00003757 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
3758 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00003759 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00003760 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00003761 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00003762 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00003763 return getPointerType(ResultType);
3764 }
Steve Naroffc0febd52008-12-10 17:49:55 +00003765 case Type::BlockPointer:
3766 {
3767 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00003768 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
3769 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Steve Naroffc0febd52008-12-10 17:49:55 +00003770 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
3771 if (ResultType.isNull()) return QualType();
3772 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
3773 return LHS;
3774 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
3775 return RHS;
3776 return getBlockPointerType(ResultType);
3777 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003778 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00003779 {
3780 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
3781 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
3782 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
3783 return QualType();
3784
3785 QualType LHSElem = getAsArrayType(LHS)->getElementType();
3786 QualType RHSElem = getAsArrayType(RHS)->getElementType();
3787 QualType ResultType = mergeTypes(LHSElem, RHSElem);
3788 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00003789 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3790 return LHS;
3791 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3792 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00003793 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
3794 ArrayType::ArraySizeModifier(), 0);
3795 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
3796 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00003797 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
3798 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00003799 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3800 return LHS;
3801 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3802 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00003803 if (LVAT) {
3804 // FIXME: This isn't correct! But tricky to implement because
3805 // the array's size has to be the size of LHS, but the type
3806 // has to be different.
3807 return LHS;
3808 }
3809 if (RVAT) {
3810 // FIXME: This isn't correct! But tricky to implement because
3811 // the array's size has to be the size of RHS, but the type
3812 // has to be different.
3813 return RHS;
3814 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00003815 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
3816 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003817 return getIncompleteArrayType(ResultType,
3818 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00003819 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003820 case Type::FunctionNoProto:
Eli Friedman3d815e72008-08-22 00:56:42 +00003821 return mergeFunctionTypes(LHS, RHS);
Douglas Gregor72564e72009-02-26 23:50:07 +00003822 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00003823 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00003824 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00003825 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00003826 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00003827 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00003828 case Type::Complex:
3829 // Distinct complex types are incompatible.
3830 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00003831 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003832 // FIXME: The merged type should be an ExtVector!
Eli Friedman3d815e72008-08-22 00:56:42 +00003833 if (areCompatVectorTypes(LHS->getAsVectorType(), RHS->getAsVectorType()))
3834 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00003835 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00003836 case Type::ObjCInterface: {
Steve Naroff5fd659d2009-02-21 16:18:07 +00003837 // Check if the interfaces are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003838 // FIXME: This should be type compatibility, e.g. whether
3839 // "LHS x; RHS x;" at global scope is legal.
Steve Naroff5fd659d2009-02-21 16:18:07 +00003840 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
3841 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
3842 if (LHSIface && RHSIface &&
3843 canAssignObjCInterfaces(LHSIface, RHSIface))
3844 return LHS;
3845
Eli Friedman3d815e72008-08-22 00:56:42 +00003846 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00003847 }
Steve Naroff14108da2009-07-10 23:34:53 +00003848 case Type::ObjCObjectPointer: {
Steve Naroff14108da2009-07-10 23:34:53 +00003849 if (canAssignObjCInterfaces(LHS->getAsObjCObjectPointerType(),
3850 RHS->getAsObjCObjectPointerType()))
3851 return LHS;
3852
Steve Naroffbc76dd02008-12-10 22:14:21 +00003853 return QualType();
Steve Naroff14108da2009-07-10 23:34:53 +00003854 }
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003855 case Type::FixedWidthInt:
3856 // Distinct fixed-width integers are not compatible.
3857 return QualType();
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003858 case Type::ExtQual:
3859 // FIXME: ExtQual types can be compatible even if they're not
3860 // identical!
3861 return QualType();
3862 // First attempt at an implementation, but I'm not really sure it's
3863 // right...
3864#if 0
3865 ExtQualType* LQual = cast<ExtQualType>(LHSCan);
3866 ExtQualType* RQual = cast<ExtQualType>(RHSCan);
3867 if (LQual->getAddressSpace() != RQual->getAddressSpace() ||
3868 LQual->getObjCGCAttr() != RQual->getObjCGCAttr())
3869 return QualType();
3870 QualType LHSBase, RHSBase, ResultType, ResCanUnqual;
3871 LHSBase = QualType(LQual->getBaseType(), 0);
3872 RHSBase = QualType(RQual->getBaseType(), 0);
3873 ResultType = mergeTypes(LHSBase, RHSBase);
3874 if (ResultType.isNull()) return QualType();
3875 ResCanUnqual = getCanonicalType(ResultType).getUnqualifiedType();
3876 if (LHSCan.getUnqualifiedType() == ResCanUnqual)
3877 return LHS;
3878 if (RHSCan.getUnqualifiedType() == ResCanUnqual)
3879 return RHS;
3880 ResultType = getAddrSpaceQualType(ResultType, LQual->getAddressSpace());
3881 ResultType = getObjCGCQualType(ResultType, LQual->getObjCGCAttr());
3882 ResultType.setCVRQualifiers(LHSCan.getCVRQualifiers());
3883 return ResultType;
3884#endif
Douglas Gregor7532dc62009-03-30 22:58:21 +00003885
3886 case Type::TemplateSpecialization:
3887 assert(false && "Dependent types have no size");
3888 break;
Steve Naroffec0550f2007-10-15 20:41:53 +00003889 }
Douglas Gregor72564e72009-02-26 23:50:07 +00003890
3891 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00003892}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00003893
Chris Lattner5426bf62008-04-07 07:01:58 +00003894//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00003895// Integer Predicates
3896//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00003897
Eli Friedmanad74a752008-06-28 06:23:08 +00003898unsigned ASTContext::getIntWidth(QualType T) {
3899 if (T == BoolTy)
3900 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00003901 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T)) {
3902 return FWIT->getWidth();
3903 }
3904 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00003905 return (unsigned)getTypeSize(T);
3906}
3907
3908QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
3909 assert(T->isSignedIntegerType() && "Unexpected type");
3910 if (const EnumType* ETy = T->getAsEnumType())
3911 T = ETy->getDecl()->getIntegerType();
3912 const BuiltinType* BTy = T->getAsBuiltinType();
3913 assert (BTy && "Unexpected signed integer type");
3914 switch (BTy->getKind()) {
3915 case BuiltinType::Char_S:
3916 case BuiltinType::SChar:
3917 return UnsignedCharTy;
3918 case BuiltinType::Short:
3919 return UnsignedShortTy;
3920 case BuiltinType::Int:
3921 return UnsignedIntTy;
3922 case BuiltinType::Long:
3923 return UnsignedLongTy;
3924 case BuiltinType::LongLong:
3925 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00003926 case BuiltinType::Int128:
3927 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00003928 default:
3929 assert(0 && "Unexpected signed integer type");
3930 return QualType();
3931 }
3932}
3933
Douglas Gregor2cf26342009-04-09 22:27:44 +00003934ExternalASTSource::~ExternalASTSource() { }
3935
3936void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00003937
3938
3939//===----------------------------------------------------------------------===//
3940// Builtin Type Computation
3941//===----------------------------------------------------------------------===//
3942
3943/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
3944/// pointer over the consumed characters. This returns the resultant type.
3945static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
3946 ASTContext::GetBuiltinTypeError &Error,
3947 bool AllowTypeModifiers = true) {
3948 // Modifiers.
3949 int HowLong = 0;
3950 bool Signed = false, Unsigned = false;
3951
3952 // Read the modifiers first.
3953 bool Done = false;
3954 while (!Done) {
3955 switch (*Str++) {
3956 default: Done = true; --Str; break;
3957 case 'S':
3958 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
3959 assert(!Signed && "Can't use 'S' modifier multiple times!");
3960 Signed = true;
3961 break;
3962 case 'U':
3963 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
3964 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
3965 Unsigned = true;
3966 break;
3967 case 'L':
3968 assert(HowLong <= 2 && "Can't have LLLL modifier");
3969 ++HowLong;
3970 break;
3971 }
3972 }
3973
3974 QualType Type;
3975
3976 // Read the base type.
3977 switch (*Str++) {
3978 default: assert(0 && "Unknown builtin type letter!");
3979 case 'v':
3980 assert(HowLong == 0 && !Signed && !Unsigned &&
3981 "Bad modifiers used with 'v'!");
3982 Type = Context.VoidTy;
3983 break;
3984 case 'f':
3985 assert(HowLong == 0 && !Signed && !Unsigned &&
3986 "Bad modifiers used with 'f'!");
3987 Type = Context.FloatTy;
3988 break;
3989 case 'd':
3990 assert(HowLong < 2 && !Signed && !Unsigned &&
3991 "Bad modifiers used with 'd'!");
3992 if (HowLong)
3993 Type = Context.LongDoubleTy;
3994 else
3995 Type = Context.DoubleTy;
3996 break;
3997 case 's':
3998 assert(HowLong == 0 && "Bad modifiers used with 's'!");
3999 if (Unsigned)
4000 Type = Context.UnsignedShortTy;
4001 else
4002 Type = Context.ShortTy;
4003 break;
4004 case 'i':
4005 if (HowLong == 3)
4006 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
4007 else if (HowLong == 2)
4008 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
4009 else if (HowLong == 1)
4010 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
4011 else
4012 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
4013 break;
4014 case 'c':
4015 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
4016 if (Signed)
4017 Type = Context.SignedCharTy;
4018 else if (Unsigned)
4019 Type = Context.UnsignedCharTy;
4020 else
4021 Type = Context.CharTy;
4022 break;
4023 case 'b': // boolean
4024 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
4025 Type = Context.BoolTy;
4026 break;
4027 case 'z': // size_t.
4028 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
4029 Type = Context.getSizeType();
4030 break;
4031 case 'F':
4032 Type = Context.getCFConstantStringType();
4033 break;
4034 case 'a':
4035 Type = Context.getBuiltinVaListType();
4036 assert(!Type.isNull() && "builtin va list type not initialized!");
4037 break;
4038 case 'A':
4039 // This is a "reference" to a va_list; however, what exactly
4040 // this means depends on how va_list is defined. There are two
4041 // different kinds of va_list: ones passed by value, and ones
4042 // passed by reference. An example of a by-value va_list is
4043 // x86, where va_list is a char*. An example of by-ref va_list
4044 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
4045 // we want this argument to be a char*&; for x86-64, we want
4046 // it to be a __va_list_tag*.
4047 Type = Context.getBuiltinVaListType();
4048 assert(!Type.isNull() && "builtin va list type not initialized!");
4049 if (Type->isArrayType()) {
4050 Type = Context.getArrayDecayedType(Type);
4051 } else {
4052 Type = Context.getLValueReferenceType(Type);
4053 }
4054 break;
4055 case 'V': {
4056 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00004057 unsigned NumElements = strtoul(Str, &End, 10);
4058 assert(End != Str && "Missing vector size");
4059
4060 Str = End;
4061
4062 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4063 Type = Context.getVectorType(ElementType, NumElements);
4064 break;
4065 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004066 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00004067 Type = Context.getFILEType();
4068 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004069 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00004070 return QualType();
4071 }
Mike Stumpfd612db2009-07-28 23:47:15 +00004072 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004073 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00004074 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00004075 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00004076 else
4077 Type = Context.getjmp_bufType();
4078
Mike Stumpfd612db2009-07-28 23:47:15 +00004079 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004080 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00004081 return QualType();
4082 }
4083 break;
Mike Stump782fa302009-07-28 02:25:19 +00004084 }
Chris Lattner86df27b2009-06-14 00:45:47 +00004085
4086 if (!AllowTypeModifiers)
4087 return Type;
4088
4089 Done = false;
4090 while (!Done) {
4091 switch (*Str++) {
4092 default: Done = true; --Str; break;
4093 case '*':
4094 Type = Context.getPointerType(Type);
4095 break;
4096 case '&':
4097 Type = Context.getLValueReferenceType(Type);
4098 break;
4099 // FIXME: There's no way to have a built-in with an rvalue ref arg.
4100 case 'C':
4101 Type = Type.getQualifiedType(QualType::Const);
4102 break;
4103 }
4104 }
4105
4106 return Type;
4107}
4108
4109/// GetBuiltinType - Return the type for the specified builtin.
4110QualType ASTContext::GetBuiltinType(unsigned id,
4111 GetBuiltinTypeError &Error) {
4112 const char *TypeStr = BuiltinInfo.GetTypeString(id);
4113
4114 llvm::SmallVector<QualType, 8> ArgTypes;
4115
4116 Error = GE_None;
4117 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
4118 if (Error != GE_None)
4119 return QualType();
4120 while (TypeStr[0] && TypeStr[0] != '.') {
4121 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
4122 if (Error != GE_None)
4123 return QualType();
4124
4125 // Do array -> pointer decay. The builtin should use the decayed type.
4126 if (Ty->isArrayType())
4127 Ty = getArrayDecayedType(Ty);
4128
4129 ArgTypes.push_back(Ty);
4130 }
4131
4132 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
4133 "'.' should only occur at end of builtin type list!");
4134
4135 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
4136 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
4137 return getFunctionNoProtoType(ResType);
4138 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
4139 TypeStr[0] == '.', 0);
4140}