blob: c59a5d703bb6ce2d61637b006d0c52708153f4f0 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +000015#include "clang/AST/DeclCXX.h"
Steve Naroff980e5082007-10-01 19:00:59 +000016#include "clang/AST/DeclObjC.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000017#include "clang/AST/DeclTemplate.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000018#include "clang/AST/Expr.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000019#include "clang/AST/ExternalASTSource.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000020#include "clang/AST/RecordLayout.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000021#include "clang/Basic/Builtins.h"
Chris Lattnera9376d42009-03-28 03:45:20 +000022#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000023#include "clang/Basic/TargetInfo.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000024#include "llvm/ADT/StringExtras.h"
Nate Begeman6fe7c8a2009-01-18 06:42:49 +000025#include "llvm/Support/MathExtras.h"
Chris Lattner557c5b12009-03-28 04:27:18 +000026#include "llvm/Support/MemoryBuffer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027using namespace clang;
28
29enum FloatingRank {
30 FloatRank, DoubleRank, LongDoubleRank
31};
32
Chris Lattner61710852008-10-05 17:34:18 +000033ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
34 TargetInfo &t,
Daniel Dunbare91593e2008-08-11 04:54:23 +000035 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +000036 Builtin::Context &builtins,
37 bool FreeMem, unsigned size_reserve) :
Douglas Gregorab452ba2009-03-26 23:50:42 +000038 GlobalNestedNameSpecifier(0), CFConstantStringTypeDecl(0),
Douglas Gregorc29f77b2009-07-07 16:35:42 +000039 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0),
40 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregor2e222532009-07-02 17:08:52 +000041 LoadedExternalComments(false), FreeMemory(FreeMem), Target(t),
42 Idents(idents), Selectors(sels),
Chris Lattnere4f21422009-06-30 01:26:17 +000043 BuiltinInfo(builtins), ExternalSource(0), PrintingPolicy(LOpts) {
Daniel Dunbare91593e2008-08-11 04:54:23 +000044 if (size_reserve > 0) Types.reserve(size_reserve);
45 InitBuiltinTypes();
Daniel Dunbare91593e2008-08-11 04:54:23 +000046 TUDecl = TranslationUnitDecl::Create(*this);
47}
48
Reid Spencer5f016e22007-07-11 17:01:13 +000049ASTContext::~ASTContext() {
50 // Deallocate all the types.
51 while (!Types.empty()) {
Ted Kremenek4b05b1d2008-05-21 16:38:54 +000052 Types.back()->Destroy(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +000053 Types.pop_back();
54 }
Eli Friedmanb26153c2008-05-27 03:08:09 +000055
Nuno Lopesb74668e2008-12-17 22:30:25 +000056 {
57 llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
58 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end();
59 while (I != E) {
60 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
61 delete R;
62 }
63 }
64
65 {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +000066 llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>::iterator
67 I = ObjCLayouts.begin(), E = ObjCLayouts.end();
Nuno Lopesb74668e2008-12-17 22:30:25 +000068 while (I != E) {
69 ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
70 delete R;
71 }
72 }
73
Douglas Gregorab452ba2009-03-26 23:50:42 +000074 // Destroy nested-name-specifiers.
Douglas Gregor1ae0afa2009-03-27 23:54:10 +000075 for (llvm::FoldingSet<NestedNameSpecifier>::iterator
76 NNS = NestedNameSpecifiers.begin(),
77 NNSEnd = NestedNameSpecifiers.end();
Douglas Gregore7dcd782009-03-27 23:25:45 +000078 NNS != NNSEnd;
Douglas Gregor1ae0afa2009-03-27 23:54:10 +000079 /* Increment in loop */)
80 (*NNS++).Destroy(*this);
Douglas Gregorab452ba2009-03-26 23:50:42 +000081
82 if (GlobalNestedNameSpecifier)
83 GlobalNestedNameSpecifier->Destroy(*this);
84
Eli Friedmanb26153c2008-05-27 03:08:09 +000085 TUDecl->Destroy(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +000086}
87
Douglas Gregor2cf26342009-04-09 22:27:44 +000088void
89ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
90 ExternalSource.reset(Source.take());
91}
92
Reid Spencer5f016e22007-07-11 17:01:13 +000093void ASTContext::PrintStats() const {
94 fprintf(stderr, "*** AST Context Stats:\n");
95 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl7c80bd62009-03-16 23:22:08 +000096
Douglas Gregordbe833d2009-05-26 14:40:08 +000097 unsigned counts[] = {
98#define TYPE(Name, Parent) 0,
99#define ABSTRACT_TYPE(Name, Parent)
100#include "clang/AST/TypeNodes.def"
101 0 // Extra
102 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000103
Reid Spencer5f016e22007-07-11 17:01:13 +0000104 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
105 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000106 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000107 }
108
Douglas Gregordbe833d2009-05-26 14:40:08 +0000109 unsigned Idx = 0;
110 unsigned TotalBytes = 0;
111#define TYPE(Name, Parent) \
112 if (counts[Idx]) \
113 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
114 TotalBytes += counts[Idx] * sizeof(Name##Type); \
115 ++Idx;
116#define ABSTRACT_TYPE(Name, Parent)
117#include "clang/AST/TypeNodes.def"
118
119 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregor2cf26342009-04-09 22:27:44 +0000120
121 if (ExternalSource.get()) {
122 fprintf(stderr, "\n");
123 ExternalSource->PrintStats();
124 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000125}
126
127
128void ASTContext::InitBuiltinType(QualType &R, BuiltinType::Kind K) {
Steve Narofff83820b2009-01-27 22:08:43 +0000129 Types.push_back((R = QualType(new (*this,8) BuiltinType(K),0)).getTypePtr());
Reid Spencer5f016e22007-07-11 17:01:13 +0000130}
131
Reid Spencer5f016e22007-07-11 17:01:13 +0000132void ASTContext::InitBuiltinTypes() {
133 assert(VoidTy.isNull() && "Context reinitialized?");
134
135 // C99 6.2.5p19.
136 InitBuiltinType(VoidTy, BuiltinType::Void);
137
138 // C99 6.2.5p2.
139 InitBuiltinType(BoolTy, BuiltinType::Bool);
140 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000141 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000142 InitBuiltinType(CharTy, BuiltinType::Char_S);
143 else
144 InitBuiltinType(CharTy, BuiltinType::Char_U);
145 // C99 6.2.5p4.
146 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
147 InitBuiltinType(ShortTy, BuiltinType::Short);
148 InitBuiltinType(IntTy, BuiltinType::Int);
149 InitBuiltinType(LongTy, BuiltinType::Long);
150 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
151
152 // C99 6.2.5p6.
153 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
154 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
155 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
156 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
157 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
158
159 // C99 6.2.5p10.
160 InitBuiltinType(FloatTy, BuiltinType::Float);
161 InitBuiltinType(DoubleTy, BuiltinType::Double);
162 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000163
Chris Lattner2df9ced2009-04-30 02:43:43 +0000164 // GNU extension, 128-bit integers.
165 InitBuiltinType(Int128Ty, BuiltinType::Int128);
166 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
167
Chris Lattner3a250322009-02-26 23:43:47 +0000168 if (LangOpts.CPlusPlus) // C++ 3.9.1p5
169 InitBuiltinType(WCharTy, BuiltinType::WChar);
170 else // C99
171 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000172
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000173 // Placeholder type for functions.
Douglas Gregor898574e2008-12-05 23:32:09 +0000174 InitBuiltinType(OverloadTy, BuiltinType::Overload);
175
176 // Placeholder type for type-dependent expressions whose type is
177 // completely unknown. No code should ever check a type against
178 // DependentTy and users should never see it; however, it is here to
179 // help diagnose failures to properly check for type-dependent
180 // expressions.
181 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000182
Anders Carlssone89d1592009-06-26 18:41:36 +0000183 // Placeholder type for C++0x auto declarations whose real type has
184 // not yet been deduced.
185 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
186
Reid Spencer5f016e22007-07-11 17:01:13 +0000187 // C99 6.2.5p11.
188 FloatComplexTy = getComplexType(FloatTy);
189 DoubleComplexTy = getComplexType(DoubleTy);
190 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000191
Steve Naroff7e219e42007-10-15 14:41:52 +0000192 BuiltinVaListType = QualType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000193 ObjCIdType = QualType();
Steve Naroff7e219e42007-10-15 14:41:52 +0000194 IdStructType = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000195 ObjCClassType = QualType();
Anders Carlsson8baaca52007-10-31 02:53:19 +0000196 ClassStructType = 0;
197
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000198 ObjCConstantStringType = QualType();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000199
200 // void * type
201 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000202
203 // nullptr type (C++0x 2.14.7)
204 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000205}
206
Douglas Gregor2e222532009-07-02 17:08:52 +0000207namespace {
208 class BeforeInTranslationUnit
209 : std::binary_function<SourceRange, SourceRange, bool> {
210 SourceManager *SourceMgr;
211
212 public:
213 explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { }
214
215 bool operator()(SourceRange X, SourceRange Y) {
216 return SourceMgr->isBeforeInTranslationUnit(X.getBegin(), Y.getBegin());
217 }
218 };
219}
220
221/// \brief Determine whether the given comment is a Doxygen-style comment.
222///
223/// \param Start the start of the comment text.
224///
225/// \param End the end of the comment text.
226///
227/// \param Member whether we want to check whether this is a member comment
228/// (which requires a < after the Doxygen-comment delimiter). Otherwise,
229/// we only return true when we find a non-member comment.
230static bool
231isDoxygenComment(SourceManager &SourceMgr, SourceRange Comment,
232 bool Member = false) {
233 const char *BufferStart
234 = SourceMgr.getBufferData(SourceMgr.getFileID(Comment.getBegin())).first;
235 const char *Start = BufferStart + SourceMgr.getFileOffset(Comment.getBegin());
236 const char* End = BufferStart + SourceMgr.getFileOffset(Comment.getEnd());
237
238 if (End - Start < 4)
239 return false;
240
241 assert(Start[0] == '/' && "Not a comment?");
242 if (Start[1] == '*' && !(Start[2] == '!' || Start[2] == '*'))
243 return false;
244 if (Start[1] == '/' && !(Start[2] == '!' || Start[2] == '/'))
245 return false;
246
247 return (Start[3] == '<') == Member;
248}
249
250/// \brief Retrieve the comment associated with the given declaration, if
251/// it has one.
252const char *ASTContext::getCommentForDecl(const Decl *D) {
253 if (!D)
254 return 0;
255
256 // Check whether we have cached a comment string for this declaration
257 // already.
258 llvm::DenseMap<const Decl *, std::string>::iterator Pos
259 = DeclComments.find(D);
260 if (Pos != DeclComments.end())
261 return Pos->second.c_str();
262
263 // If we have an external AST source and have not yet loaded comments from
264 // that source, do so now.
265 if (ExternalSource && !LoadedExternalComments) {
266 std::vector<SourceRange> LoadedComments;
267 ExternalSource->ReadComments(LoadedComments);
268
269 if (!LoadedComments.empty())
270 Comments.insert(Comments.begin(), LoadedComments.begin(),
271 LoadedComments.end());
272
273 LoadedExternalComments = true;
274 }
275
276 // If there are no comments anywhere, we won't find anything.
277 if (Comments.empty())
278 return 0;
279
280 // If the declaration doesn't map directly to a location in a file, we
281 // can't find the comment.
282 SourceLocation DeclStartLoc = D->getLocStart();
283 if (DeclStartLoc.isInvalid() || !DeclStartLoc.isFileID())
284 return 0;
285
286 // Find the comment that occurs just before this declaration.
287 std::vector<SourceRange>::iterator LastComment
288 = std::lower_bound(Comments.begin(), Comments.end(),
289 SourceRange(DeclStartLoc),
290 BeforeInTranslationUnit(&SourceMgr));
291
292 // Decompose the location for the start of the declaration and find the
293 // beginning of the file buffer.
294 std::pair<FileID, unsigned> DeclStartDecomp
295 = SourceMgr.getDecomposedLoc(DeclStartLoc);
296 const char *FileBufferStart
297 = SourceMgr.getBufferData(DeclStartDecomp.first).first;
298
299 // First check whether we have a comment for a member.
300 if (LastComment != Comments.end() &&
301 !isa<TagDecl>(D) && !isa<NamespaceDecl>(D) &&
302 isDoxygenComment(SourceMgr, *LastComment, true)) {
303 std::pair<FileID, unsigned> LastCommentEndDecomp
304 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
305 if (DeclStartDecomp.first == LastCommentEndDecomp.first &&
306 SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second)
307 == SourceMgr.getLineNumber(LastCommentEndDecomp.first,
308 LastCommentEndDecomp.second)) {
309 // The Doxygen member comment comes after the declaration starts and
310 // is on the same line and in the same file as the declaration. This
311 // is the comment we want.
312 std::string &Result = DeclComments[D];
313 Result.append(FileBufferStart +
314 SourceMgr.getFileOffset(LastComment->getBegin()),
315 FileBufferStart + LastCommentEndDecomp.second + 1);
316 return Result.c_str();
317 }
318 }
319
320 if (LastComment == Comments.begin())
321 return 0;
322 --LastComment;
323
324 // Decompose the end of the comment.
325 std::pair<FileID, unsigned> LastCommentEndDecomp
326 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
327
328 // If the comment and the declaration aren't in the same file, then they
329 // aren't related.
330 if (DeclStartDecomp.first != LastCommentEndDecomp.first)
331 return 0;
332
333 // Check that we actually have a Doxygen comment.
334 if (!isDoxygenComment(SourceMgr, *LastComment))
335 return 0;
336
337 // Compute the starting line for the declaration and for the end of the
338 // comment (this is expensive).
339 unsigned DeclStartLine
340 = SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second);
341 unsigned CommentEndLine
342 = SourceMgr.getLineNumber(LastCommentEndDecomp.first,
343 LastCommentEndDecomp.second);
344
345 // If the comment does not end on the line prior to the declaration, then
346 // the comment is not associated with the declaration at all.
347 if (CommentEndLine + 1 != DeclStartLine)
348 return 0;
349
350 // We have a comment, but there may be more comments on the previous lines.
351 // Keep looking so long as the comments are still Doxygen comments and are
352 // still adjacent.
353 unsigned ExpectedLine
354 = SourceMgr.getSpellingLineNumber(LastComment->getBegin()) - 1;
355 std::vector<SourceRange>::iterator FirstComment = LastComment;
356 while (FirstComment != Comments.begin()) {
357 // Look at the previous comment
358 --FirstComment;
359 std::pair<FileID, unsigned> Decomp
360 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
361
362 // If this previous comment is in a different file, we're done.
363 if (Decomp.first != DeclStartDecomp.first) {
364 ++FirstComment;
365 break;
366 }
367
368 // If this comment is not a Doxygen comment, we're done.
369 if (!isDoxygenComment(SourceMgr, *FirstComment)) {
370 ++FirstComment;
371 break;
372 }
373
374 // If the line number is not what we expected, we're done.
375 unsigned Line = SourceMgr.getLineNumber(Decomp.first, Decomp.second);
376 if (Line != ExpectedLine) {
377 ++FirstComment;
378 break;
379 }
380
381 // Set the next expected line number.
382 ExpectedLine
383 = SourceMgr.getSpellingLineNumber(FirstComment->getBegin()) - 1;
384 }
385
386 // The iterator range [FirstComment, LastComment] contains all of the
387 // BCPL comments that, together, are associated with this declaration.
388 // Form a single comment block string for this declaration that concatenates
389 // all of these comments.
390 std::string &Result = DeclComments[D];
391 while (FirstComment != LastComment) {
392 std::pair<FileID, unsigned> DecompStart
393 = SourceMgr.getDecomposedLoc(FirstComment->getBegin());
394 std::pair<FileID, unsigned> DecompEnd
395 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
396 Result.append(FileBufferStart + DecompStart.second,
397 FileBufferStart + DecompEnd.second + 1);
398 ++FirstComment;
399 }
400
401 // Append the last comment line.
402 Result.append(FileBufferStart +
403 SourceMgr.getFileOffset(LastComment->getBegin()),
404 FileBufferStart + LastCommentEndDecomp.second + 1);
405 return Result.c_str();
406}
407
Chris Lattner464175b2007-07-18 17:52:12 +0000408//===----------------------------------------------------------------------===//
409// Type Sizing and Analysis
410//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000411
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000412/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
413/// scalar floating point type.
414const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
415 const BuiltinType *BT = T->getAsBuiltinType();
416 assert(BT && "Not a floating point type!");
417 switch (BT->getKind()) {
418 default: assert(0 && "Not a floating point type!");
419 case BuiltinType::Float: return Target.getFloatFormat();
420 case BuiltinType::Double: return Target.getDoubleFormat();
421 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
422 }
423}
424
Chris Lattneraf707ab2009-01-24 21:53:27 +0000425/// getDeclAlign - Return a conservative estimate of the alignment of the
426/// specified decl. Note that bitfields do not have a valid alignment, so
427/// this method will assert on them.
Daniel Dunbarb7d08442009-02-17 22:16:19 +0000428unsigned ASTContext::getDeclAlignInBytes(const Decl *D) {
Eli Friedmandcdafb62009-02-22 02:56:25 +0000429 unsigned Align = Target.getCharWidth();
430
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000431 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
Eli Friedmandcdafb62009-02-22 02:56:25 +0000432 Align = std::max(Align, AA->getAlignment());
433
Chris Lattneraf707ab2009-01-24 21:53:27 +0000434 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
435 QualType T = VD->getType();
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000436 if (const ReferenceType* RT = T->getAsReferenceType()) {
437 unsigned AS = RT->getPointeeType().getAddressSpace();
Anders Carlssonf0930232009-04-10 04:52:36 +0000438 Align = Target.getPointerAlign(AS);
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000439 } else if (!T->isIncompleteType() && !T->isFunctionType()) {
440 // Incomplete or function types default to 1.
Eli Friedmandcdafb62009-02-22 02:56:25 +0000441 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
442 T = cast<ArrayType>(T)->getElementType();
443
444 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
445 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000446 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000447
448 return Align / Target.getCharWidth();
Chris Lattneraf707ab2009-01-24 21:53:27 +0000449}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000450
Chris Lattnera7674d82007-07-13 22:13:22 +0000451/// getTypeSize - Return the size of the specified type, in bits. This method
452/// does not work on incomplete types.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000453std::pair<uint64_t, unsigned>
Daniel Dunbar1d751182008-11-08 05:48:37 +0000454ASTContext::getTypeInfo(const Type *T) {
Mike Stump5e301002009-02-27 18:32:39 +0000455 uint64_t Width=0;
456 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000457 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000458#define TYPE(Class, Base)
459#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000460#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000461#define DEPENDENT_TYPE(Class, Base) case Type::Class:
462#include "clang/AST/TypeNodes.def"
Douglas Gregor18857642009-04-30 17:32:17 +0000463 assert(false && "Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000464 break;
465
Chris Lattner692233e2007-07-13 22:27:08 +0000466 case Type::FunctionNoProto:
467 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000468 // GCC extension: alignof(function) = 32 bits
469 Width = 0;
470 Align = 32;
471 break;
472
Douglas Gregor72564e72009-02-26 23:50:07 +0000473 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000474 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000475 Width = 0;
476 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
477 break;
478
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +0000479 case Type::ConstantArrayWithExpr:
480 case Type::ConstantArrayWithoutExpr:
Steve Narofffb22d962007-08-30 01:06:46 +0000481 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000482 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Steve Narofffb22d962007-08-30 01:06:46 +0000483
Chris Lattner98be4942008-03-05 18:54:05 +0000484 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000485 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000486 Align = EltInfo.second;
487 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000488 }
Nate Begeman213541a2008-04-18 23:10:10 +0000489 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000490 case Type::Vector: {
491 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000492 getTypeInfo(cast<VectorType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000493 Width = EltInfo.first*cast<VectorType>(T)->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000494 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000495 // If the alignment is not a power of 2, round up to the next power of 2.
496 // This happens for non-power-of-2 length vectors.
497 // FIXME: this should probably be a target property.
498 Align = 1 << llvm::Log2_32_Ceil(Align);
Chris Lattner030d8842007-07-19 22:06:24 +0000499 break;
500 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000501
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000502 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000503 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000504 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000505 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000506 // GCC extension: alignof(void) = 8 bits.
507 Width = 0;
508 Align = 8;
509 break;
510
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000511 case BuiltinType::Bool:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000512 Width = Target.getBoolWidth();
513 Align = Target.getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000514 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000515 case BuiltinType::Char_S:
516 case BuiltinType::Char_U:
517 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000518 case BuiltinType::SChar:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000519 Width = Target.getCharWidth();
520 Align = Target.getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000521 break;
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000522 case BuiltinType::WChar:
523 Width = Target.getWCharWidth();
524 Align = Target.getWCharAlign();
525 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000526 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000527 case BuiltinType::Short:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000528 Width = Target.getShortWidth();
529 Align = Target.getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000530 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000531 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000532 case BuiltinType::Int:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000533 Width = Target.getIntWidth();
534 Align = Target.getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000535 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000536 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000537 case BuiltinType::Long:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000538 Width = Target.getLongWidth();
539 Align = Target.getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000540 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000541 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000542 case BuiltinType::LongLong:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000543 Width = Target.getLongLongWidth();
544 Align = Target.getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000545 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000546 case BuiltinType::Int128:
547 case BuiltinType::UInt128:
548 Width = 128;
549 Align = 128; // int128_t is 128-bit aligned on all targets.
550 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000551 case BuiltinType::Float:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000552 Width = Target.getFloatWidth();
553 Align = Target.getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000554 break;
555 case BuiltinType::Double:
Chris Lattner5426bf62008-04-07 07:01:58 +0000556 Width = Target.getDoubleWidth();
557 Align = Target.getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000558 break;
559 case BuiltinType::LongDouble:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000560 Width = Target.getLongDoubleWidth();
561 Align = Target.getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000562 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000563 case BuiltinType::NullPtr:
564 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
565 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000566 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000567 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000568 break;
Eli Friedmanf98aba32009-02-13 02:31:07 +0000569 case Type::FixedWidthInt:
570 // FIXME: This isn't precisely correct; the width/alignment should depend
571 // on the available types for the target
572 Width = cast<FixedWidthIntType>(T)->getWidth();
Chris Lattner736166b2009-02-15 21:20:13 +0000573 Width = std::max(llvm::NextPowerOf2(Width - 1), (uint64_t)8);
Eli Friedmanf98aba32009-02-13 02:31:07 +0000574 Align = Width;
575 break;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000576 case Type::ExtQual:
Chris Lattner98be4942008-03-05 18:54:05 +0000577 // FIXME: Pointers into different addr spaces could have different sizes and
578 // alignment requirements: getPointerInfo should take an AddrSpace.
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000579 return getTypeInfo(QualType(cast<ExtQualType>(T)->getBaseType(), 0));
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000580 case Type::ObjCObjectPointer:
Douglas Gregor72564e72009-02-26 23:50:07 +0000581 case Type::ObjCQualifiedInterface:
Chris Lattner5426bf62008-04-07 07:01:58 +0000582 Width = Target.getPointerWidth(0);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000583 Align = Target.getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000584 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000585 case Type::BlockPointer: {
586 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
587 Width = Target.getPointerWidth(AS);
588 Align = Target.getPointerAlign(AS);
589 break;
590 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000591 case Type::Pointer: {
592 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner5426bf62008-04-07 07:01:58 +0000593 Width = Target.getPointerWidth(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000594 Align = Target.getPointerAlign(AS);
595 break;
596 }
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000597 case Type::LValueReference:
598 case Type::RValueReference:
Chris Lattner7ab2ed82007-07-13 22:16:13 +0000599 // "When applied to a reference or a reference type, the result is the size
Chris Lattner5d2a6302007-07-18 18:26:58 +0000600 // of the referenced type." C++98 5.3.3p2: expr.sizeof.
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000601 // FIXME: This is wrong for struct layout: a reference in a struct has
602 // pointer size.
Chris Lattnerbdcd6372008-04-02 17:35:06 +0000603 return getTypeInfo(cast<ReferenceType>(T)->getPointeeType());
Sebastian Redlf30208a2009-01-24 21:16:55 +0000604 case Type::MemberPointer: {
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000605 // FIXME: This is ABI dependent. We use the Itanium C++ ABI.
606 // http://www.codesourcery.com/public/cxx-abi/abi.html#member-pointers
607 // If we ever want to support other ABIs this needs to be abstracted.
608
Sebastian Redlf30208a2009-01-24 21:16:55 +0000609 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000610 std::pair<uint64_t, unsigned> PtrDiffInfo =
611 getTypeInfo(getPointerDiffType());
612 Width = PtrDiffInfo.first;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000613 if (Pointee->isFunctionType())
614 Width *= 2;
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000615 Align = PtrDiffInfo.second;
616 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000617 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000618 case Type::Complex: {
619 // Complex types have the same alignment as their elements, but twice the
620 // size.
621 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000622 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000623 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000624 Align = EltInfo.second;
625 break;
626 }
Devang Patel44a3dde2008-06-04 21:54:36 +0000627 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000628 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000629 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
630 Width = Layout.getSize();
631 Align = Layout.getAlignment();
632 break;
633 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000634 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000635 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000636 const TagType *TT = cast<TagType>(T);
637
638 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner8389eab2008-08-09 21:35:13 +0000639 Width = 1;
640 Align = 1;
641 break;
642 }
643
Daniel Dunbar1d751182008-11-08 05:48:37 +0000644 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000645 return getTypeInfo(ET->getDecl()->getIntegerType());
646
Daniel Dunbar1d751182008-11-08 05:48:37 +0000647 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000648 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
649 Width = Layout.getSize();
650 Align = Layout.getAlignment();
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000651 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000652 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000653
Douglas Gregor18857642009-04-30 17:32:17 +0000654 case Type::Typedef: {
655 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000656 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
Douglas Gregor18857642009-04-30 17:32:17 +0000657 Align = Aligned->getAlignment();
658 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
659 } else
660 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregor7532dc62009-03-30 22:58:21 +0000661 break;
Chris Lattner71763312008-04-06 22:05:18 +0000662 }
Douglas Gregor18857642009-04-30 17:32:17 +0000663
664 case Type::TypeOfExpr:
665 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
666 .getTypePtr());
667
668 case Type::TypeOf:
669 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
670
Anders Carlsson395b4752009-06-24 19:06:50 +0000671 case Type::Decltype:
672 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
673 .getTypePtr());
674
Douglas Gregor18857642009-04-30 17:32:17 +0000675 case Type::QualifiedName:
676 return getTypeInfo(cast<QualifiedNameType>(T)->getNamedType().getTypePtr());
677
678 case Type::TemplateSpecialization:
679 assert(getCanonicalType(T) != T &&
680 "Cannot request the size of a dependent type");
681 // FIXME: this is likely to be wrong once we support template
682 // aliases, since a template alias could refer to a typedef that
683 // has an __aligned__ attribute on it.
684 return getTypeInfo(getCanonicalType(T));
685 }
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000686
Chris Lattner464175b2007-07-18 17:52:12 +0000687 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000688 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +0000689}
690
Chris Lattner34ebde42009-01-27 18:08:34 +0000691/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
692/// type for the current target in bits. This can be different than the ABI
693/// alignment in cases where it is beneficial for performance to overalign
694/// a data type.
695unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
696 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +0000697
698 // Double and long long should be naturally aligned if possible.
699 if (const ComplexType* CT = T->getAsComplexType())
700 T = CT->getElementType().getTypePtr();
701 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
702 T->isSpecificBuiltinType(BuiltinType::LongLong))
703 return std::max(ABIAlign, (unsigned)getTypeSize(T));
704
Chris Lattner34ebde42009-01-27 18:08:34 +0000705 return ABIAlign;
706}
707
708
Devang Patel8b277042008-06-04 21:22:16 +0000709/// LayoutField - Field layout.
710void ASTRecordLayout::LayoutField(const FieldDecl *FD, unsigned FieldNo,
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000711 bool IsUnion, unsigned StructPacking,
Devang Patel8b277042008-06-04 21:22:16 +0000712 ASTContext &Context) {
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000713 unsigned FieldPacking = StructPacking;
Devang Patel8b277042008-06-04 21:22:16 +0000714 uint64_t FieldOffset = IsUnion ? 0 : Size;
715 uint64_t FieldSize;
716 unsigned FieldAlign;
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000717
718 // FIXME: Should this override struct packing? Probably we want to
719 // take the minimum?
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000720 if (const PackedAttr *PA = FD->getAttr<PackedAttr>())
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000721 FieldPacking = PA->getAlignment();
Devang Patel8b277042008-06-04 21:22:16 +0000722
723 if (const Expr *BitWidthExpr = FD->getBitWidth()) {
724 // TODO: Need to check this algorithm on other targets!
725 // (tested on Linux-X86)
Eli Friedman9a901bb2009-04-26 19:19:15 +0000726 FieldSize = BitWidthExpr->EvaluateAsInt(Context).getZExtValue();
Devang Patel8b277042008-06-04 21:22:16 +0000727
728 std::pair<uint64_t, unsigned> FieldInfo =
729 Context.getTypeInfo(FD->getType());
730 uint64_t TypeSize = FieldInfo.first;
731
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000732 // Determine the alignment of this bitfield. The packing
733 // attributes define a maximum and the alignment attribute defines
734 // a minimum.
735 // FIXME: What is the right behavior when the specified alignment
736 // is smaller than the specified packing?
Devang Patel8b277042008-06-04 21:22:16 +0000737 FieldAlign = FieldInfo.second;
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000738 if (FieldPacking)
739 FieldAlign = std::min(FieldAlign, FieldPacking);
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000740 if (const AlignedAttr *AA = FD->getAttr<AlignedAttr>())
Devang Patel8b277042008-06-04 21:22:16 +0000741 FieldAlign = std::max(FieldAlign, AA->getAlignment());
742
743 // Check if we need to add padding to give the field the correct
744 // alignment.
745 if (FieldSize == 0 || (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize)
746 FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1);
747
748 // Padding members don't affect overall alignment
749 if (!FD->getIdentifier())
750 FieldAlign = 1;
751 } else {
Chris Lattner8389eab2008-08-09 21:35:13 +0000752 if (FD->getType()->isIncompleteArrayType()) {
753 // This is a flexible array member; we can't directly
Devang Patel8b277042008-06-04 21:22:16 +0000754 // query getTypeInfo about these, so we figure it out here.
755 // Flexible array members don't have any size, but they
756 // have to be aligned appropriately for their element type.
757 FieldSize = 0;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000758 const ArrayType* ATy = Context.getAsArrayType(FD->getType());
Devang Patel8b277042008-06-04 21:22:16 +0000759 FieldAlign = Context.getTypeAlign(ATy->getElementType());
Anders Carlsson2f1169f2009-04-10 05:31:15 +0000760 } else if (const ReferenceType *RT = FD->getType()->getAsReferenceType()) {
761 unsigned AS = RT->getPointeeType().getAddressSpace();
762 FieldSize = Context.Target.getPointerWidth(AS);
763 FieldAlign = Context.Target.getPointerAlign(AS);
Devang Patel8b277042008-06-04 21:22:16 +0000764 } else {
765 std::pair<uint64_t, unsigned> FieldInfo =
766 Context.getTypeInfo(FD->getType());
767 FieldSize = FieldInfo.first;
768 FieldAlign = FieldInfo.second;
769 }
770
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000771 // Determine the alignment of this bitfield. The packing
772 // attributes define a maximum and the alignment attribute defines
773 // a minimum. Additionally, the packing alignment must be at least
774 // a byte for non-bitfields.
775 //
776 // FIXME: What is the right behavior when the specified alignment
777 // is smaller than the specified packing?
778 if (FieldPacking)
779 FieldAlign = std::min(FieldAlign, std::max(8U, FieldPacking));
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000780 if (const AlignedAttr *AA = FD->getAttr<AlignedAttr>())
Devang Patel8b277042008-06-04 21:22:16 +0000781 FieldAlign = std::max(FieldAlign, AA->getAlignment());
782
783 // Round up the current record size to the field's alignment boundary.
784 FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1);
785 }
786
787 // Place this field at the current location.
788 FieldOffsets[FieldNo] = FieldOffset;
789
790 // Reserve space for this field.
791 if (IsUnion) {
792 Size = std::max(Size, FieldSize);
793 } else {
794 Size = FieldOffset + FieldSize;
795 }
796
Daniel Dunbard6884a02009-05-04 05:16:21 +0000797 // Remember the next available offset.
798 NextOffset = Size;
799
Devang Patel8b277042008-06-04 21:22:16 +0000800 // Remember max struct/class alignment.
801 Alignment = std::max(Alignment, FieldAlign);
802}
803
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000804static void CollectLocalObjCIvars(ASTContext *Ctx,
805 const ObjCInterfaceDecl *OI,
806 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000807 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
808 E = OI->ivar_end(); I != E; ++I) {
Chris Lattnerf1690852009-03-31 08:48:01 +0000809 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000810 if (!IVDecl->isInvalidDecl())
811 Fields.push_back(cast<FieldDecl>(IVDecl));
812 }
813}
814
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000815void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
816 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
817 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
818 CollectObjCIvars(SuperClass, Fields);
819 CollectLocalObjCIvars(this, OI, Fields);
820}
821
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000822/// ShallowCollectObjCIvars -
823/// Collect all ivars, including those synthesized, in the current class.
824///
825void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
826 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars,
827 bool CollectSynthesized) {
828 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
829 E = OI->ivar_end(); I != E; ++I) {
830 Ivars.push_back(*I);
831 }
832 if (CollectSynthesized)
833 CollectSynthesizedIvars(OI, Ivars);
834}
835
Fariborz Jahanian98200742009-05-12 18:14:29 +0000836void ASTContext::CollectProtocolSynthesizedIvars(const ObjCProtocolDecl *PD,
837 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000838 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
839 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian98200742009-05-12 18:14:29 +0000840 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
841 Ivars.push_back(Ivar);
842
843 // Also look into nested protocols.
844 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
845 E = PD->protocol_end(); P != E; ++P)
846 CollectProtocolSynthesizedIvars(*P, Ivars);
847}
848
849/// CollectSynthesizedIvars -
850/// This routine collect synthesized ivars for the designated class.
851///
852void ASTContext::CollectSynthesizedIvars(const ObjCInterfaceDecl *OI,
853 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000854 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
855 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian98200742009-05-12 18:14:29 +0000856 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
857 Ivars.push_back(Ivar);
858 }
859 // Also look into interface's protocol list for properties declared
860 // in the protocol and whose ivars are synthesized.
861 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
862 PE = OI->protocol_end(); P != PE; ++P) {
863 ObjCProtocolDecl *PD = (*P);
864 CollectProtocolSynthesizedIvars(PD, Ivars);
865 }
866}
867
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000868unsigned ASTContext::CountProtocolSynthesizedIvars(const ObjCProtocolDecl *PD) {
869 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000870 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
871 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000872 if ((*I)->getPropertyIvarDecl())
873 ++count;
874
875 // Also look into nested protocols.
876 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
877 E = PD->protocol_end(); P != E; ++P)
878 count += CountProtocolSynthesizedIvars(*P);
879 return count;
880}
881
882unsigned ASTContext::CountSynthesizedIvars(const ObjCInterfaceDecl *OI)
883{
884 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000885 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
886 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000887 if ((*I)->getPropertyIvarDecl())
888 ++count;
889 }
890 // Also look into interface's protocol list for properties declared
891 // in the protocol and whose ivars are synthesized.
892 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
893 PE = OI->protocol_end(); P != PE; ++P) {
894 ObjCProtocolDecl *PD = (*P);
895 count += CountProtocolSynthesizedIvars(PD);
896 }
897 return count;
898}
899
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000900/// getInterfaceLayoutImpl - Get or compute information about the
901/// layout of the given interface.
902///
903/// \param Impl - If given, also include the layout of the interface's
904/// implementation. This may differ by including synthesized ivars.
Devang Patel44a3dde2008-06-04 21:54:36 +0000905const ASTRecordLayout &
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000906ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
907 const ObjCImplementationDecl *Impl) {
Daniel Dunbar532d4da2009-05-03 13:15:50 +0000908 assert(!D->isForwardDecl() && "Invalid interface decl!");
909
Devang Patel44a3dde2008-06-04 21:54:36 +0000910 // Look up this layout, if already laid out, return what we have.
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000911 ObjCContainerDecl *Key =
912 Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
913 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
914 return *Entry;
Devang Patel44a3dde2008-06-04 21:54:36 +0000915
Daniel Dunbar453addb2009-05-03 11:16:44 +0000916 unsigned FieldCount = D->ivar_size();
917 // Add in synthesized ivar count if laying out an implementation.
918 if (Impl) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000919 unsigned SynthCount = CountSynthesizedIvars(D);
920 FieldCount += SynthCount;
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000921 // If there aren't any sythesized ivars then reuse the interface
Daniel Dunbar453addb2009-05-03 11:16:44 +0000922 // entry. Note we can't cache this because we simply free all
923 // entries later; however we shouldn't look up implementations
924 // frequently.
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000925 if (SynthCount == 0)
Daniel Dunbar453addb2009-05-03 11:16:44 +0000926 return getObjCLayout(D, 0);
927 }
928
Devang Patel6a5a34c2008-06-06 02:14:01 +0000929 ASTRecordLayout *NewEntry = NULL;
Devang Patel6a5a34c2008-06-06 02:14:01 +0000930 if (ObjCInterfaceDecl *SD = D->getSuperClass()) {
Devang Patel6a5a34c2008-06-06 02:14:01 +0000931 const ASTRecordLayout &SL = getASTObjCInterfaceLayout(SD);
932 unsigned Alignment = SL.getAlignment();
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000933
Daniel Dunbar913af352009-05-07 21:58:26 +0000934 // We start laying out ivars not at the end of the superclass
935 // structure, but at the next byte following the last field.
936 uint64_t Size = llvm::RoundUpToAlignment(SL.NextOffset, 8);
Daniel Dunbard6884a02009-05-04 05:16:21 +0000937
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000938 ObjCLayouts[Key] = NewEntry = new ASTRecordLayout(Size, Alignment);
Devang Patel6a5a34c2008-06-06 02:14:01 +0000939 NewEntry->InitializeLayout(FieldCount);
Devang Patel6a5a34c2008-06-06 02:14:01 +0000940 } else {
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000941 ObjCLayouts[Key] = NewEntry = new ASTRecordLayout();
Devang Patel6a5a34c2008-06-06 02:14:01 +0000942 NewEntry->InitializeLayout(FieldCount);
943 }
Devang Patel44a3dde2008-06-04 21:54:36 +0000944
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000945 unsigned StructPacking = 0;
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000946 if (const PackedAttr *PA = D->getAttr<PackedAttr>())
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000947 StructPacking = PA->getAlignment();
Devang Patel44a3dde2008-06-04 21:54:36 +0000948
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000949 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>())
Devang Patel44a3dde2008-06-04 21:54:36 +0000950 NewEntry->SetAlignment(std::max(NewEntry->getAlignment(),
951 AA->getAlignment()));
952
953 // Layout each ivar sequentially.
954 unsigned i = 0;
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000955 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
956 ShallowCollectObjCIvars(D, Ivars, Impl);
957 for (unsigned k = 0, e = Ivars.size(); k != e; ++k)
958 NewEntry->LayoutField(Ivars[k], i++, false, StructPacking, *this);
959
Devang Patel44a3dde2008-06-04 21:54:36 +0000960 // Finally, round the size of the total struct up to the alignment of the
961 // struct itself.
962 NewEntry->FinalizeLayout();
963 return *NewEntry;
964}
965
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000966const ASTRecordLayout &
967ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
968 return getObjCLayout(D, 0);
969}
970
971const ASTRecordLayout &
972ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
973 return getObjCLayout(D->getClassInterface(), D);
974}
975
Devang Patel88a981b2007-11-01 19:11:01 +0000976/// getASTRecordLayout - Get or compute information about the layout of the
Chris Lattner464175b2007-07-18 17:52:12 +0000977/// specified record (struct/union/class), which indicates its size and field
978/// position information.
Chris Lattner98be4942008-03-05 18:54:05 +0000979const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +0000980 D = D->getDefinition(*this);
981 assert(D && "Cannot get layout of forward declarations!");
Eli Friedman4bd998b2008-05-30 09:31:38 +0000982
Chris Lattner464175b2007-07-18 17:52:12 +0000983 // Look up this layout, if already laid out, return what we have.
Devang Patel88a981b2007-11-01 19:11:01 +0000984 const ASTRecordLayout *&Entry = ASTRecordLayouts[D];
Chris Lattner464175b2007-07-18 17:52:12 +0000985 if (Entry) return *Entry;
Eli Friedman4bd998b2008-05-30 09:31:38 +0000986
Devang Patel88a981b2007-11-01 19:11:01 +0000987 // Allocate and assign into ASTRecordLayouts here. The "Entry" reference can
988 // be invalidated (dangle) if the ASTRecordLayouts hashtable is inserted into.
989 ASTRecordLayout *NewEntry = new ASTRecordLayout();
Chris Lattner464175b2007-07-18 17:52:12 +0000990 Entry = NewEntry;
Eli Friedman4bd998b2008-05-30 09:31:38 +0000991
Douglas Gregore267ff32008-12-11 20:41:00 +0000992 // FIXME: Avoid linear walk through the fields, if possible.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000993 NewEntry->InitializeLayout(std::distance(D->field_begin(), D->field_end()));
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000994 bool IsUnion = D->isUnion();
Chris Lattner464175b2007-07-18 17:52:12 +0000995
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000996 unsigned StructPacking = 0;
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000997 if (const PackedAttr *PA = D->getAttr<PackedAttr>())
Daniel Dunbar3b0db902008-10-16 02:34:03 +0000998 StructPacking = PA->getAlignment();
999
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001000 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>())
Devang Patel8b277042008-06-04 21:22:16 +00001001 NewEntry->SetAlignment(std::max(NewEntry->getAlignment(),
1002 AA->getAlignment()));
Anders Carlsson8af226a2008-02-18 07:13:09 +00001003
Eli Friedman4bd998b2008-05-30 09:31:38 +00001004 // Layout each field, for now, just sequentially, respecting alignment. In
1005 // the future, this will need to be tweakable by targets.
Douglas Gregor44b43212008-12-11 16:49:14 +00001006 unsigned FieldIdx = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001007 for (RecordDecl::field_iterator Field = D->field_begin(),
1008 FieldEnd = D->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00001009 Field != FieldEnd; (void)++Field, ++FieldIdx)
1010 NewEntry->LayoutField(*Field, FieldIdx, IsUnion, StructPacking, *this);
Eli Friedman4bd998b2008-05-30 09:31:38 +00001011
1012 // Finally, round the size of the total struct up to the alignment of the
1013 // struct itself.
Sebastian Redl1590d9c2009-05-27 19:34:06 +00001014 NewEntry->FinalizeLayout(getLangOptions().CPlusPlus);
Chris Lattner5d2a6302007-07-18 18:26:58 +00001015 return *NewEntry;
Chris Lattner464175b2007-07-18 17:52:12 +00001016}
1017
Chris Lattnera7674d82007-07-13 22:13:22 +00001018//===----------------------------------------------------------------------===//
1019// Type creation/memoization methods
1020//===----------------------------------------------------------------------===//
1021
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001022QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001023 QualType CanT = getCanonicalType(T);
1024 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001025 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001026
1027 // If we are composing extended qualifiers together, merge together into one
1028 // ExtQualType node.
1029 unsigned CVRQuals = T.getCVRQualifiers();
1030 QualType::GCAttrTypes GCAttr = QualType::GCNone;
1031 Type *TypeNode = T.getTypePtr();
Chris Lattnerf46699c2008-02-20 20:55:12 +00001032
Chris Lattnerb7d25532009-02-18 22:53:11 +00001033 if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
1034 // If this type already has an address space specified, it cannot get
1035 // another one.
1036 assert(EQT->getAddressSpace() == 0 &&
1037 "Type cannot be in multiple addr spaces!");
1038 GCAttr = EQT->getObjCGCAttr();
1039 TypeNode = EQT->getBaseType();
1040 }
Chris Lattnerf46699c2008-02-20 20:55:12 +00001041
Chris Lattnerb7d25532009-02-18 22:53:11 +00001042 // Check if we've already instantiated this type.
Christopher Lambebb97e92008-02-04 02:31:56 +00001043 llvm::FoldingSetNodeID ID;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001044 ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
Christopher Lambebb97e92008-02-04 02:31:56 +00001045 void *InsertPos = 0;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001046 if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattnerb7d25532009-02-18 22:53:11 +00001047 return QualType(EXTQy, CVRQuals);
1048
Christopher Lambebb97e92008-02-04 02:31:56 +00001049 // If the base type isn't canonical, this won't be a canonical type either,
1050 // so fill in the canonical type field.
1051 QualType Canonical;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001052 if (!TypeNode->isCanonical()) {
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001053 Canonical = getAddrSpaceQualType(CanT, AddressSpace);
Christopher Lambebb97e92008-02-04 02:31:56 +00001054
Chris Lattnerb7d25532009-02-18 22:53:11 +00001055 // Update InsertPos, the previous call could have invalidated it.
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001056 ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001057 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Christopher Lambebb97e92008-02-04 02:31:56 +00001058 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00001059 ExtQualType *New =
1060 new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001061 ExtQualTypes.InsertNode(New, InsertPos);
Christopher Lambebb97e92008-02-04 02:31:56 +00001062 Types.push_back(New);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001063 return QualType(New, CVRQuals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001064}
1065
Chris Lattnerb7d25532009-02-18 22:53:11 +00001066QualType ASTContext::getObjCGCQualType(QualType T,
1067 QualType::GCAttrTypes GCAttr) {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001068 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001069 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001070 return T;
1071
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001072 if (T->isPointerType()) {
1073 QualType Pointee = T->getAsPointerType()->getPointeeType();
1074 if (Pointee->isPointerType()) {
1075 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1076 return getPointerType(ResultType);
1077 }
1078 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00001079 // If we are composing extended qualifiers together, merge together into one
1080 // ExtQualType node.
1081 unsigned CVRQuals = T.getCVRQualifiers();
1082 Type *TypeNode = T.getTypePtr();
1083 unsigned AddressSpace = 0;
1084
1085 if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
1086 // If this type already has an address space specified, it cannot get
1087 // another one.
1088 assert(EQT->getObjCGCAttr() == QualType::GCNone &&
1089 "Type cannot be in multiple addr spaces!");
1090 AddressSpace = EQT->getAddressSpace();
1091 TypeNode = EQT->getBaseType();
1092 }
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001093
1094 // Check if we've already instantiated an gc qual'd type of this type.
1095 llvm::FoldingSetNodeID ID;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001096 ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001097 void *InsertPos = 0;
1098 if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
Chris Lattnerb7d25532009-02-18 22:53:11 +00001099 return QualType(EXTQy, CVRQuals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001100
1101 // If the base type isn't canonical, this won't be a canonical type either,
1102 // so fill in the canonical type field.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00001103 // FIXME: Isn't this also not canonical if the base type is a array
1104 // or pointer type? I can't find any documentation for objc_gc, though...
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001105 QualType Canonical;
1106 if (!T->isCanonical()) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00001107 Canonical = getObjCGCQualType(CanT, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001108
Chris Lattnerb7d25532009-02-18 22:53:11 +00001109 // Update InsertPos, the previous call could have invalidated it.
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001110 ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
1111 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1112 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00001113 ExtQualType *New =
1114 new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001115 ExtQualTypes.InsertNode(New, InsertPos);
1116 Types.push_back(New);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001117 return QualType(New, CVRQuals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001118}
Chris Lattnera7674d82007-07-13 22:13:22 +00001119
Reid Spencer5f016e22007-07-11 17:01:13 +00001120/// getComplexType - Return the uniqued reference to the type for a complex
1121/// number with the specified element type.
1122QualType ASTContext::getComplexType(QualType T) {
1123 // Unique pointers, to guarantee there is only one pointer of a particular
1124 // structure.
1125 llvm::FoldingSetNodeID ID;
1126 ComplexType::Profile(ID, T);
1127
1128 void *InsertPos = 0;
1129 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1130 return QualType(CT, 0);
1131
1132 // If the pointee type isn't canonical, this won't be a canonical type either,
1133 // so fill in the canonical type field.
1134 QualType Canonical;
1135 if (!T->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001136 Canonical = getComplexType(getCanonicalType(T));
Reid Spencer5f016e22007-07-11 17:01:13 +00001137
1138 // Get the new insert position for the node we care about.
1139 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001140 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001141 }
Steve Narofff83820b2009-01-27 22:08:43 +00001142 ComplexType *New = new (*this,8) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001143 Types.push_back(New);
1144 ComplexTypes.InsertNode(New, InsertPos);
1145 return QualType(New, 0);
1146}
1147
Eli Friedmanf98aba32009-02-13 02:31:07 +00001148QualType ASTContext::getFixedWidthIntType(unsigned Width, bool Signed) {
1149 llvm::DenseMap<unsigned, FixedWidthIntType*> &Map = Signed ?
1150 SignedFixedWidthIntTypes : UnsignedFixedWidthIntTypes;
1151 FixedWidthIntType *&Entry = Map[Width];
1152 if (!Entry)
1153 Entry = new FixedWidthIntType(Width, Signed);
1154 return QualType(Entry, 0);
1155}
Reid Spencer5f016e22007-07-11 17:01:13 +00001156
1157/// getPointerType - Return the uniqued reference to the type for a pointer to
1158/// the specified type.
1159QualType ASTContext::getPointerType(QualType T) {
1160 // Unique pointers, to guarantee there is only one pointer of a particular
1161 // structure.
1162 llvm::FoldingSetNodeID ID;
1163 PointerType::Profile(ID, T);
1164
1165 void *InsertPos = 0;
1166 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1167 return QualType(PT, 0);
1168
1169 // If the pointee type isn't canonical, this won't be a canonical type either,
1170 // so fill in the canonical type field.
1171 QualType Canonical;
1172 if (!T->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001173 Canonical = getPointerType(getCanonicalType(T));
Reid Spencer5f016e22007-07-11 17:01:13 +00001174
1175 // Get the new insert position for the node we care about.
1176 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001177 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001178 }
Steve Narofff83820b2009-01-27 22:08:43 +00001179 PointerType *New = new (*this,8) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001180 Types.push_back(New);
1181 PointerTypes.InsertNode(New, InsertPos);
1182 return QualType(New, 0);
1183}
1184
Steve Naroff5618bd42008-08-27 16:04:49 +00001185/// getBlockPointerType - Return the uniqued reference to the type for
1186/// a pointer to the specified block.
1187QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff296e8d52008-08-28 19:20:44 +00001188 assert(T->isFunctionType() && "block of function types only");
1189 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001190 // structure.
1191 llvm::FoldingSetNodeID ID;
1192 BlockPointerType::Profile(ID, T);
1193
1194 void *InsertPos = 0;
1195 if (BlockPointerType *PT =
1196 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1197 return QualType(PT, 0);
1198
Steve Naroff296e8d52008-08-28 19:20:44 +00001199 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001200 // type either so fill in the canonical type field.
1201 QualType Canonical;
1202 if (!T->isCanonical()) {
1203 Canonical = getBlockPointerType(getCanonicalType(T));
1204
1205 // Get the new insert position for the node we care about.
1206 BlockPointerType *NewIP =
1207 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001208 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001209 }
Steve Narofff83820b2009-01-27 22:08:43 +00001210 BlockPointerType *New = new (*this,8) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001211 Types.push_back(New);
1212 BlockPointerTypes.InsertNode(New, InsertPos);
1213 return QualType(New, 0);
1214}
1215
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001216/// getLValueReferenceType - Return the uniqued reference to the type for an
1217/// lvalue reference to the specified type.
1218QualType ASTContext::getLValueReferenceType(QualType T) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001219 // Unique pointers, to guarantee there is only one pointer of a particular
1220 // structure.
1221 llvm::FoldingSetNodeID ID;
1222 ReferenceType::Profile(ID, T);
1223
1224 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001225 if (LValueReferenceType *RT =
1226 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001227 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001228
Reid Spencer5f016e22007-07-11 17:01:13 +00001229 // If the referencee type isn't canonical, this won't be a canonical type
1230 // either, so fill in the canonical type field.
1231 QualType Canonical;
1232 if (!T->isCanonical()) {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001233 Canonical = getLValueReferenceType(getCanonicalType(T));
1234
Reid Spencer5f016e22007-07-11 17:01:13 +00001235 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001236 LValueReferenceType *NewIP =
1237 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001238 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001239 }
1240
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001241 LValueReferenceType *New = new (*this,8) LValueReferenceType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001242 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001243 LValueReferenceTypes.InsertNode(New, InsertPos);
1244 return QualType(New, 0);
1245}
1246
1247/// getRValueReferenceType - Return the uniqued reference to the type for an
1248/// rvalue reference to the specified type.
1249QualType ASTContext::getRValueReferenceType(QualType T) {
1250 // Unique pointers, to guarantee there is only one pointer of a particular
1251 // structure.
1252 llvm::FoldingSetNodeID ID;
1253 ReferenceType::Profile(ID, T);
1254
1255 void *InsertPos = 0;
1256 if (RValueReferenceType *RT =
1257 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1258 return QualType(RT, 0);
1259
1260 // If the referencee type isn't canonical, this won't be a canonical type
1261 // either, so fill in the canonical type field.
1262 QualType Canonical;
1263 if (!T->isCanonical()) {
1264 Canonical = getRValueReferenceType(getCanonicalType(T));
1265
1266 // Get the new insert position for the node we care about.
1267 RValueReferenceType *NewIP =
1268 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1269 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1270 }
1271
1272 RValueReferenceType *New = new (*this,8) RValueReferenceType(T, Canonical);
1273 Types.push_back(New);
1274 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001275 return QualType(New, 0);
1276}
1277
Sebastian Redlf30208a2009-01-24 21:16:55 +00001278/// getMemberPointerType - Return the uniqued reference to the type for a
1279/// member pointer to the specified type, in the specified class.
1280QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls)
1281{
1282 // Unique pointers, to guarantee there is only one pointer of a particular
1283 // structure.
1284 llvm::FoldingSetNodeID ID;
1285 MemberPointerType::Profile(ID, T, Cls);
1286
1287 void *InsertPos = 0;
1288 if (MemberPointerType *PT =
1289 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1290 return QualType(PT, 0);
1291
1292 // If the pointee or class type isn't canonical, this won't be a canonical
1293 // type either, so fill in the canonical type field.
1294 QualType Canonical;
1295 if (!T->isCanonical()) {
1296 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1297
1298 // Get the new insert position for the node we care about.
1299 MemberPointerType *NewIP =
1300 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1301 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1302 }
Steve Narofff83820b2009-01-27 22:08:43 +00001303 MemberPointerType *New = new (*this,8) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001304 Types.push_back(New);
1305 MemberPointerTypes.InsertNode(New, InsertPos);
1306 return QualType(New, 0);
1307}
1308
Steve Narofffb22d962007-08-30 01:06:46 +00001309/// getConstantArrayType - Return the unique reference to the type for an
1310/// array of the specified element type.
1311QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001312 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001313 ArrayType::ArraySizeModifier ASM,
1314 unsigned EltTypeQuals) {
Eli Friedman587cbdf2009-05-29 20:17:55 +00001315 assert((EltTy->isDependentType() || EltTy->isConstantSizeType()) &&
1316 "Constant array of VLAs is illegal!");
1317
Chris Lattner38aeec72009-05-13 04:12:56 +00001318 // Convert the array size into a canonical width matching the pointer size for
1319 // the target.
1320 llvm::APInt ArySize(ArySizeIn);
1321 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1322
Reid Spencer5f016e22007-07-11 17:01:13 +00001323 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001324 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001325
1326 void *InsertPos = 0;
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001327 if (ConstantArrayType *ATP =
1328 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001329 return QualType(ATP, 0);
1330
1331 // If the element type isn't canonical, this won't be a canonical type either,
1332 // so fill in the canonical type field.
1333 QualType Canonical;
1334 if (!EltTy->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001335 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroffc9406122007-08-30 18:10:14 +00001336 ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001337 // Get the new insert position for the node we care about.
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001338 ConstantArrayType *NewIP =
1339 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001340 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001341 }
1342
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001343 ConstantArrayType *New =
Steve Narofff83820b2009-01-27 22:08:43 +00001344 new(*this,8)ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001345 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001346 Types.push_back(New);
1347 return QualType(New, 0);
1348}
1349
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001350/// getConstantArrayWithExprType - Return a reference to the type for
1351/// an array of the specified element type.
1352QualType
1353ASTContext::getConstantArrayWithExprType(QualType EltTy,
1354 const llvm::APInt &ArySizeIn,
1355 Expr *ArySizeExpr,
1356 ArrayType::ArraySizeModifier ASM,
1357 unsigned EltTypeQuals,
1358 SourceRange Brackets) {
1359 // Convert the array size into a canonical width matching the pointer
1360 // size for the target.
1361 llvm::APInt ArySize(ArySizeIn);
1362 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1363
1364 // Compute the canonical ConstantArrayType.
1365 QualType Canonical = getConstantArrayType(getCanonicalType(EltTy),
1366 ArySize, ASM, EltTypeQuals);
1367 // Since we don't unique expressions, it isn't possible to unique VLA's
1368 // that have an expression provided for their size.
1369 ConstantArrayWithExprType *New =
1370 new(*this,8)ConstantArrayWithExprType(EltTy, Canonical,
1371 ArySize, ArySizeExpr,
1372 ASM, EltTypeQuals, Brackets);
1373 Types.push_back(New);
1374 return QualType(New, 0);
1375}
1376
1377/// getConstantArrayWithoutExprType - Return a reference to the type for
1378/// an array of the specified element type.
1379QualType
1380ASTContext::getConstantArrayWithoutExprType(QualType EltTy,
1381 const llvm::APInt &ArySizeIn,
1382 ArrayType::ArraySizeModifier ASM,
1383 unsigned EltTypeQuals) {
1384 // Convert the array size into a canonical width matching the pointer
1385 // size for the target.
1386 llvm::APInt ArySize(ArySizeIn);
1387 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1388
1389 // Compute the canonical ConstantArrayType.
1390 QualType Canonical = getConstantArrayType(getCanonicalType(EltTy),
1391 ArySize, ASM, EltTypeQuals);
1392 ConstantArrayWithoutExprType *New =
1393 new(*this,8)ConstantArrayWithoutExprType(EltTy, Canonical,
1394 ArySize, ASM, EltTypeQuals);
1395 Types.push_back(New);
1396 return QualType(New, 0);
1397}
1398
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001399/// getVariableArrayType - Returns a non-unique reference to the type for a
1400/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001401QualType ASTContext::getVariableArrayType(QualType EltTy,
1402 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001403 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001404 unsigned EltTypeQuals,
1405 SourceRange Brackets) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001406 // Since we don't unique expressions, it isn't possible to unique VLA's
1407 // that have an expression provided for their size.
1408
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001409 VariableArrayType *New =
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001410 new(*this,8)VariableArrayType(EltTy, QualType(),
1411 NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001412
1413 VariableArrayTypes.push_back(New);
1414 Types.push_back(New);
1415 return QualType(New, 0);
1416}
1417
Douglas Gregor898574e2008-12-05 23:32:09 +00001418/// getDependentSizedArrayType - Returns a non-unique reference to
1419/// the type for a dependently-sized array of the specified element
1420/// type. FIXME: We will need these to be uniqued, or at least
1421/// comparable, at some point.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001422QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1423 Expr *NumElts,
Douglas Gregor898574e2008-12-05 23:32:09 +00001424 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001425 unsigned EltTypeQuals,
1426 SourceRange Brackets) {
Douglas Gregor898574e2008-12-05 23:32:09 +00001427 assert((NumElts->isTypeDependent() || NumElts->isValueDependent()) &&
1428 "Size must be type- or value-dependent!");
1429
1430 // Since we don't unique expressions, it isn't possible to unique
1431 // dependently-sized array types.
1432
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001433 DependentSizedArrayType *New =
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001434 new (*this,8) DependentSizedArrayType(EltTy, QualType(),
1435 NumElts, ASM, EltTypeQuals,
1436 Brackets);
Douglas Gregor898574e2008-12-05 23:32:09 +00001437
1438 DependentSizedArrayTypes.push_back(New);
1439 Types.push_back(New);
1440 return QualType(New, 0);
1441}
1442
Eli Friedmanc5773c42008-02-15 18:16:39 +00001443QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1444 ArrayType::ArraySizeModifier ASM,
1445 unsigned EltTypeQuals) {
1446 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001447 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001448
1449 void *InsertPos = 0;
1450 if (IncompleteArrayType *ATP =
1451 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1452 return QualType(ATP, 0);
1453
1454 // If the element type isn't canonical, this won't be a canonical type
1455 // either, so fill in the canonical type field.
1456 QualType Canonical;
1457
1458 if (!EltTy->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001459 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001460 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001461
1462 // Get the new insert position for the node we care about.
1463 IncompleteArrayType *NewIP =
1464 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001465 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001466 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001467
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001468 IncompleteArrayType *New
1469 = new (*this,8) IncompleteArrayType(EltTy, Canonical,
1470 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001471
1472 IncompleteArrayTypes.InsertNode(New, InsertPos);
1473 Types.push_back(New);
1474 return QualType(New, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001475}
1476
Steve Naroff73322922007-07-18 18:00:27 +00001477/// getVectorType - Return the unique reference to a vector type of
1478/// the specified element type and size. VectorType must be a built-in type.
1479QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001480 BuiltinType *baseType;
1481
Chris Lattnerf52ab252008-04-06 22:59:24 +00001482 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff73322922007-07-18 18:00:27 +00001483 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Reid Spencer5f016e22007-07-11 17:01:13 +00001484
1485 // Check if we've already instantiated a vector of this type.
1486 llvm::FoldingSetNodeID ID;
Steve Naroff73322922007-07-18 18:00:27 +00001487 VectorType::Profile(ID, vecType, NumElts, Type::Vector);
Reid Spencer5f016e22007-07-11 17:01:13 +00001488 void *InsertPos = 0;
1489 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1490 return QualType(VTP, 0);
1491
1492 // If the element type isn't canonical, this won't be a canonical type either,
1493 // so fill in the canonical type field.
1494 QualType Canonical;
1495 if (!vecType->isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001496 Canonical = getVectorType(getCanonicalType(vecType), NumElts);
Reid Spencer5f016e22007-07-11 17:01:13 +00001497
1498 // Get the new insert position for the node we care about.
1499 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001500 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001501 }
Steve Narofff83820b2009-01-27 22:08:43 +00001502 VectorType *New = new (*this,8) VectorType(vecType, NumElts, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001503 VectorTypes.InsertNode(New, InsertPos);
1504 Types.push_back(New);
1505 return QualType(New, 0);
1506}
1507
Nate Begeman213541a2008-04-18 23:10:10 +00001508/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001509/// the specified element type and size. VectorType must be a built-in type.
Nate Begeman213541a2008-04-18 23:10:10 +00001510QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff73322922007-07-18 18:00:27 +00001511 BuiltinType *baseType;
1512
Chris Lattnerf52ab252008-04-06 22:59:24 +00001513 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begeman213541a2008-04-18 23:10:10 +00001514 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Steve Naroff73322922007-07-18 18:00:27 +00001515
1516 // Check if we've already instantiated a vector of this type.
1517 llvm::FoldingSetNodeID ID;
Nate Begeman213541a2008-04-18 23:10:10 +00001518 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector);
Steve Naroff73322922007-07-18 18:00:27 +00001519 void *InsertPos = 0;
1520 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1521 return QualType(VTP, 0);
1522
1523 // If the element type isn't canonical, this won't be a canonical type either,
1524 // so fill in the canonical type field.
1525 QualType Canonical;
1526 if (!vecType->isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001527 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Steve Naroff73322922007-07-18 18:00:27 +00001528
1529 // Get the new insert position for the node we care about.
1530 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001531 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001532 }
Steve Narofff83820b2009-01-27 22:08:43 +00001533 ExtVectorType *New = new (*this,8) ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001534 VectorTypes.InsertNode(New, InsertPos);
1535 Types.push_back(New);
1536 return QualType(New, 0);
1537}
1538
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001539QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
1540 Expr *SizeExpr,
1541 SourceLocation AttrLoc) {
1542 DependentSizedExtVectorType *New =
1543 new (*this,8) DependentSizedExtVectorType(vecType, QualType(),
1544 SizeExpr, AttrLoc);
1545
1546 DependentSizedExtVectorTypes.push_back(New);
1547 Types.push_back(New);
1548 return QualType(New, 0);
1549}
1550
Douglas Gregor72564e72009-02-26 23:50:07 +00001551/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001552///
Douglas Gregor72564e72009-02-26 23:50:07 +00001553QualType ASTContext::getFunctionNoProtoType(QualType ResultTy) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001554 // Unique functions, to guarantee there is only one function of a particular
1555 // structure.
1556 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001557 FunctionNoProtoType::Profile(ID, ResultTy);
Reid Spencer5f016e22007-07-11 17:01:13 +00001558
1559 void *InsertPos = 0;
Douglas Gregor72564e72009-02-26 23:50:07 +00001560 if (FunctionNoProtoType *FT =
1561 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001562 return QualType(FT, 0);
1563
1564 QualType Canonical;
1565 if (!ResultTy->isCanonical()) {
Douglas Gregor72564e72009-02-26 23:50:07 +00001566 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy));
Reid Spencer5f016e22007-07-11 17:01:13 +00001567
1568 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001569 FunctionNoProtoType *NewIP =
1570 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001571 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001572 }
1573
Douglas Gregor72564e72009-02-26 23:50:07 +00001574 FunctionNoProtoType *New =new(*this,8)FunctionNoProtoType(ResultTy,Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001575 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001576 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001577 return QualType(New, 0);
1578}
1579
1580/// getFunctionType - Return a normal function type with a typed argument
1581/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner61710852008-10-05 17:34:18 +00001582QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001583 unsigned NumArgs, bool isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001584 unsigned TypeQuals, bool hasExceptionSpec,
1585 bool hasAnyExceptionSpec, unsigned NumExs,
1586 const QualType *ExArray) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001587 // Unique functions, to guarantee there is only one function of a particular
1588 // structure.
1589 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001590 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001591 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
1592 NumExs, ExArray);
Reid Spencer5f016e22007-07-11 17:01:13 +00001593
1594 void *InsertPos = 0;
Douglas Gregor72564e72009-02-26 23:50:07 +00001595 if (FunctionProtoType *FTP =
1596 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001597 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001598
1599 // Determine whether the type being created is already canonical or not.
Reid Spencer5f016e22007-07-11 17:01:13 +00001600 bool isCanonical = ResultTy->isCanonical();
Sebastian Redl465226e2009-05-27 22:11:52 +00001601 if (hasExceptionSpec)
1602 isCanonical = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001603 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
1604 if (!ArgArray[i]->isCanonical())
1605 isCanonical = false;
1606
1607 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001608 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001609 QualType Canonical;
1610 if (!isCanonical) {
1611 llvm::SmallVector<QualType, 16> CanonicalArgs;
1612 CanonicalArgs.reserve(NumArgs);
1613 for (unsigned i = 0; i != NumArgs; ++i)
Chris Lattnerf52ab252008-04-06 22:59:24 +00001614 CanonicalArgs.push_back(getCanonicalType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001615
Chris Lattnerf52ab252008-04-06 22:59:24 +00001616 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001617 CanonicalArgs.data(), NumArgs,
Sebastian Redlbfa2fcb2009-05-06 23:27:55 +00001618 isVariadic, TypeQuals);
Sebastian Redl465226e2009-05-27 22:11:52 +00001619
Reid Spencer5f016e22007-07-11 17:01:13 +00001620 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001621 FunctionProtoType *NewIP =
1622 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001623 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001624 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001625
Douglas Gregor72564e72009-02-26 23:50:07 +00001626 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001627 // for two variable size arrays (for parameter and exception types) at the
1628 // end of them.
Douglas Gregor72564e72009-02-26 23:50:07 +00001629 FunctionProtoType *FTP =
Sebastian Redl465226e2009-05-27 22:11:52 +00001630 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1631 NumArgs*sizeof(QualType) +
1632 NumExs*sizeof(QualType), 8);
Douglas Gregor72564e72009-02-26 23:50:07 +00001633 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001634 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
1635 ExArray, NumExs, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001636 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001637 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001638 return QualType(FTP, 0);
1639}
1640
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001641/// getTypeDeclType - Return the unique reference to the type for the
1642/// specified type declaration.
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001643QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001644 assert(Decl && "Passed null for Decl param");
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001645 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1646
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001647 if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001648 return getTypedefType(Typedef);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001649 else if (isa<TemplateTypeParmDecl>(Decl)) {
1650 assert(false && "Template type parameter types are always available.");
1651 } else if (ObjCInterfaceDecl *ObjCInterface = dyn_cast<ObjCInterfaceDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001652 return getObjCInterfaceType(ObjCInterface);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001653
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001654 if (RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001655 if (PrevDecl)
1656 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001657 else
1658 Decl->TypeForDecl = new (*this,8) RecordType(Record);
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001659 }
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001660 else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
1661 if (PrevDecl)
1662 Decl->TypeForDecl = PrevDecl->TypeForDecl;
Steve Narofff83820b2009-01-27 22:08:43 +00001663 else
1664 Decl->TypeForDecl = new (*this,8) EnumType(Enum);
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001665 }
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001666 else
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001667 assert(false && "TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001668
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001669 if (!PrevDecl) Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001670 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001671}
1672
Reid Spencer5f016e22007-07-11 17:01:13 +00001673/// getTypedefType - Return the unique reference to the type for the
1674/// specified typename decl.
1675QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
1676 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1677
Chris Lattnerf52ab252008-04-06 22:59:24 +00001678 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
Douglas Gregor72564e72009-02-26 23:50:07 +00001679 Decl->TypeForDecl = new(*this,8) TypedefType(Type::Typedef, Decl, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001680 Types.push_back(Decl->TypeForDecl);
1681 return QualType(Decl->TypeForDecl, 0);
1682}
1683
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001684/// getObjCInterfaceType - Return the unique reference to the type for the
Steve Naroff3536b442007-09-06 21:24:23 +00001685/// specified ObjC interface decl.
Daniel Dunbar3b3a4582009-04-22 04:34:53 +00001686QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) {
Steve Naroff3536b442007-09-06 21:24:23 +00001687 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1688
Daniel Dunbar3b3a4582009-04-22 04:34:53 +00001689 ObjCInterfaceDecl *OID = const_cast<ObjCInterfaceDecl*>(Decl);
1690 Decl->TypeForDecl = new(*this,8) ObjCInterfaceType(Type::ObjCInterface, OID);
Steve Naroff3536b442007-09-06 21:24:23 +00001691 Types.push_back(Decl->TypeForDecl);
1692 return QualType(Decl->TypeForDecl, 0);
1693}
1694
Douglas Gregorfab9d672009-02-05 23:33:38 +00001695/// \brief Retrieve the template type parameter type for a template
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001696/// parameter or parameter pack with the given depth, index, and (optionally)
1697/// name.
Douglas Gregorfab9d672009-02-05 23:33:38 +00001698QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001699 bool ParameterPack,
Douglas Gregorfab9d672009-02-05 23:33:38 +00001700 IdentifierInfo *Name) {
1701 llvm::FoldingSetNodeID ID;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001702 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001703 void *InsertPos = 0;
1704 TemplateTypeParmType *TypeParm
1705 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1706
1707 if (TypeParm)
1708 return QualType(TypeParm, 0);
1709
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001710 if (Name) {
1711 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
1712 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, ParameterPack,
1713 Name, Canon);
1714 } else
1715 TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001716
1717 Types.push_back(TypeParm);
1718 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1719
1720 return QualType(TypeParm, 0);
1721}
1722
Douglas Gregor55f6b142009-02-09 18:46:07 +00001723QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00001724ASTContext::getTemplateSpecializationType(TemplateName Template,
1725 const TemplateArgument *Args,
1726 unsigned NumArgs,
1727 QualType Canon) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001728 if (!Canon.isNull())
1729 Canon = getCanonicalType(Canon);
Douglas Gregorfc705b82009-02-26 22:19:44 +00001730
Douglas Gregor55f6b142009-02-09 18:46:07 +00001731 llvm::FoldingSetNodeID ID;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001732 TemplateSpecializationType::Profile(ID, Template, Args, NumArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001733
Douglas Gregor55f6b142009-02-09 18:46:07 +00001734 void *InsertPos = 0;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001735 TemplateSpecializationType *Spec
1736 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001737
1738 if (Spec)
1739 return QualType(Spec, 0);
1740
Douglas Gregor7532dc62009-03-30 22:58:21 +00001741 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00001742 sizeof(TemplateArgument) * NumArgs),
1743 8);
Douglas Gregor7532dc62009-03-30 22:58:21 +00001744 Spec = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, Canon);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001745 Types.push_back(Spec);
Douglas Gregor7532dc62009-03-30 22:58:21 +00001746 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001747
1748 return QualType(Spec, 0);
1749}
1750
Douglas Gregore4e5b052009-03-19 00:18:19 +00001751QualType
Douglas Gregorab452ba2009-03-26 23:50:42 +00001752ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
Douglas Gregore4e5b052009-03-19 00:18:19 +00001753 QualType NamedType) {
1754 llvm::FoldingSetNodeID ID;
Douglas Gregorab452ba2009-03-26 23:50:42 +00001755 QualifiedNameType::Profile(ID, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001756
1757 void *InsertPos = 0;
1758 QualifiedNameType *T
1759 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
1760 if (T)
1761 return QualType(T, 0);
1762
Douglas Gregorab452ba2009-03-26 23:50:42 +00001763 T = new (*this) QualifiedNameType(NNS, NamedType,
1764 getCanonicalType(NamedType));
Douglas Gregore4e5b052009-03-19 00:18:19 +00001765 Types.push_back(T);
1766 QualifiedNameTypes.InsertNode(T, InsertPos);
1767 return QualType(T, 0);
1768}
1769
Douglas Gregord57959a2009-03-27 23:10:48 +00001770QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1771 const IdentifierInfo *Name,
1772 QualType Canon) {
1773 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1774
1775 if (Canon.isNull()) {
1776 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1777 if (CanonNNS != NNS)
1778 Canon = getTypenameType(CanonNNS, Name);
1779 }
1780
1781 llvm::FoldingSetNodeID ID;
1782 TypenameType::Profile(ID, NNS, Name);
1783
1784 void *InsertPos = 0;
1785 TypenameType *T
1786 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1787 if (T)
1788 return QualType(T, 0);
1789
1790 T = new (*this) TypenameType(NNS, Name, Canon);
1791 Types.push_back(T);
1792 TypenameTypes.InsertNode(T, InsertPos);
1793 return QualType(T, 0);
1794}
1795
Douglas Gregor17343172009-04-01 00:28:59 +00001796QualType
1797ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1798 const TemplateSpecializationType *TemplateId,
1799 QualType Canon) {
1800 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1801
1802 if (Canon.isNull()) {
1803 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1804 QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
1805 if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
1806 const TemplateSpecializationType *CanonTemplateId
1807 = CanonType->getAsTemplateSpecializationType();
1808 assert(CanonTemplateId &&
1809 "Canonical type must also be a template specialization type");
1810 Canon = getTypenameType(CanonNNS, CanonTemplateId);
1811 }
1812 }
1813
1814 llvm::FoldingSetNodeID ID;
1815 TypenameType::Profile(ID, NNS, TemplateId);
1816
1817 void *InsertPos = 0;
1818 TypenameType *T
1819 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1820 if (T)
1821 return QualType(T, 0);
1822
1823 T = new (*this) TypenameType(NNS, TemplateId, Canon);
1824 Types.push_back(T);
1825 TypenameTypes.InsertNode(T, InsertPos);
1826 return QualType(T, 0);
1827}
1828
Chris Lattner88cb27a2008-04-07 04:56:42 +00001829/// CmpProtocolNames - Comparison predicate for sorting protocols
1830/// alphabetically.
1831static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
1832 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001833 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00001834}
1835
1836static void SortAndUniqueProtocols(ObjCProtocolDecl **&Protocols,
1837 unsigned &NumProtocols) {
1838 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
1839
1840 // Sort protocols, keyed by name.
1841 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
1842
1843 // Remove duplicates.
1844 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
1845 NumProtocols = ProtocolsEnd-Protocols;
1846}
1847
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001848/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
1849/// the given interface decl and the conforming protocol list.
1850QualType ASTContext::getObjCObjectPointerType(ObjCInterfaceDecl *Decl,
1851 ObjCProtocolDecl **Protocols,
1852 unsigned NumProtocols) {
1853 // Sort the protocol list alphabetically to canonicalize it.
1854 if (NumProtocols)
1855 SortAndUniqueProtocols(Protocols, NumProtocols);
1856
1857 llvm::FoldingSetNodeID ID;
1858 ObjCObjectPointerType::Profile(ID, Decl, Protocols, NumProtocols);
1859
1860 void *InsertPos = 0;
1861 if (ObjCObjectPointerType *QT =
1862 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1863 return QualType(QT, 0);
1864
1865 // No Match;
1866 ObjCObjectPointerType *QType =
1867 new (*this,8) ObjCObjectPointerType(Decl, Protocols, NumProtocols);
1868
1869 Types.push_back(QType);
1870 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
1871 return QualType(QType, 0);
1872}
Chris Lattner88cb27a2008-04-07 04:56:42 +00001873
Chris Lattner065f0d72008-04-07 04:44:08 +00001874/// getObjCQualifiedInterfaceType - Return a ObjCQualifiedInterfaceType type for
1875/// the given interface decl and the conforming protocol list.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001876QualType ASTContext::getObjCQualifiedInterfaceType(ObjCInterfaceDecl *Decl,
1877 ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
Chris Lattner88cb27a2008-04-07 04:56:42 +00001878 // Sort the protocol list alphabetically to canonicalize it.
1879 SortAndUniqueProtocols(Protocols, NumProtocols);
1880
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001881 llvm::FoldingSetNodeID ID;
Chris Lattnerb0489812008-04-07 06:38:24 +00001882 ObjCQualifiedInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001883
1884 void *InsertPos = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001885 if (ObjCQualifiedInterfaceType *QT =
1886 ObjCQualifiedInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001887 return QualType(QT, 0);
1888
1889 // No Match;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001890 ObjCQualifiedInterfaceType *QType =
Steve Narofff83820b2009-01-27 22:08:43 +00001891 new (*this,8) ObjCQualifiedInterfaceType(Decl, Protocols, NumProtocols);
Ted Kremenek566c2ba2009-01-19 21:31:22 +00001892
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001893 Types.push_back(QType);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001894 ObjCQualifiedInterfaceTypes.InsertNode(QType, InsertPos);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00001895 return QualType(QType, 0);
1896}
1897
Douglas Gregor72564e72009-02-26 23:50:07 +00001898/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
1899/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00001900/// multiple declarations that refer to "typeof(x)" all contain different
1901/// DeclRefExpr's. This doesn't effect the type checker, since it operates
1902/// on canonical type's (which are always unique).
Douglas Gregor72564e72009-02-26 23:50:07 +00001903QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001904 QualType Canonical = getCanonicalType(tofExpr->getType());
Douglas Gregor72564e72009-02-26 23:50:07 +00001905 TypeOfExprType *toe = new (*this,8) TypeOfExprType(tofExpr, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00001906 Types.push_back(toe);
1907 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00001908}
1909
Steve Naroff9752f252007-08-01 18:02:17 +00001910/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
1911/// TypeOfType AST's. The only motivation to unique these nodes would be
1912/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
1913/// an issue. This doesn't effect the type checker, since it operates
1914/// on canonical type's (which are always unique).
Steve Naroffd1861fd2007-07-31 12:34:36 +00001915QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001916 QualType Canonical = getCanonicalType(tofType);
Steve Narofff83820b2009-01-27 22:08:43 +00001917 TypeOfType *tot = new (*this,8) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00001918 Types.push_back(tot);
1919 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00001920}
1921
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00001922/// getDecltypeForExpr - Given an expr, will return the decltype for that
1923/// expression, according to the rules in C++0x [dcl.type.simple]p4
1924static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00001925 if (e->isTypeDependent())
1926 return Context.DependentTy;
1927
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00001928 // If e is an id expression or a class member access, decltype(e) is defined
1929 // as the type of the entity named by e.
1930 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
1931 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
1932 return VD->getType();
1933 }
1934 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
1935 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
1936 return FD->getType();
1937 }
1938 // If e is a function call or an invocation of an overloaded operator,
1939 // (parentheses around e are ignored), decltype(e) is defined as the
1940 // return type of that function.
1941 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
1942 return CE->getCallReturnType();
1943
1944 QualType T = e->getType();
1945
1946 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
1947 // defined as T&, otherwise decltype(e) is defined as T.
1948 if (e->isLvalue(Context) == Expr::LV_Valid)
1949 T = Context.getLValueReferenceType(T);
1950
1951 return T;
1952}
1953
Anders Carlsson395b4752009-06-24 19:06:50 +00001954/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
1955/// DecltypeType AST's. The only motivation to unique these nodes would be
1956/// memory savings. Since decltype(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).
1959QualType ASTContext::getDecltypeType(Expr *e) {
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00001960 QualType T = getDecltypeForExpr(e, *this);
1961 DecltypeType *dt = new (*this, 8) DecltypeType(e, getCanonicalType(T));
Anders Carlsson395b4752009-06-24 19:06:50 +00001962 Types.push_back(dt);
1963 return QualType(dt, 0);
1964}
1965
Reid Spencer5f016e22007-07-11 17:01:13 +00001966/// getTagDeclType - Return the unique reference to the type for the
1967/// specified TagDecl (struct/union/class/enum) decl.
1968QualType ASTContext::getTagDeclType(TagDecl *Decl) {
Ted Kremenekd778f882007-11-26 21:16:01 +00001969 assert (Decl);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001970 return getTypeDeclType(Decl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001971}
1972
1973/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
1974/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
1975/// needs to agree with the definition in <stddef.h>.
1976QualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00001977 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00001978}
1979
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00001980/// getSignedWCharType - Return the type of "signed wchar_t".
1981/// Used when in C++, as a GCC extension.
1982QualType ASTContext::getSignedWCharType() const {
1983 // FIXME: derive from "Target" ?
1984 return WCharTy;
1985}
1986
1987/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
1988/// Used when in C++, as a GCC extension.
1989QualType ASTContext::getUnsignedWCharType() const {
1990 // FIXME: derive from "Target" ?
1991 return UnsignedIntTy;
1992}
1993
Chris Lattner8b9023b2007-07-13 03:05:23 +00001994/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
1995/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
1996QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00001997 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00001998}
1999
Chris Lattnere6327742008-04-02 05:18:44 +00002000//===----------------------------------------------------------------------===//
2001// Type Operators
2002//===----------------------------------------------------------------------===//
2003
Chris Lattner77c96472008-04-06 22:41:35 +00002004/// getCanonicalType - Return the canonical (structural) type corresponding to
2005/// the specified potentially non-canonical type. The non-canonical version
2006/// of a type may have many "decorated" versions of types. Decorators can
2007/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2008/// to be free of any of these, allowing two canonical types to be compared
2009/// for exact equality with a simple pointer comparison.
2010QualType ASTContext::getCanonicalType(QualType T) {
2011 QualType CanType = T.getTypePtr()->getCanonicalTypeInternal();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002012
2013 // If the result has type qualifiers, make sure to canonicalize them as well.
2014 unsigned TypeQuals = T.getCVRQualifiers() | CanType.getCVRQualifiers();
2015 if (TypeQuals == 0) return CanType;
2016
2017 // If the type qualifiers are on an array type, get the canonical type of the
2018 // array with the qualifiers applied to the element type.
2019 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2020 if (!AT)
2021 return CanType.getQualifiedType(TypeQuals);
2022
2023 // Get the canonical version of the element with the extra qualifiers on it.
2024 // This can recursively sink qualifiers through multiple levels of arrays.
2025 QualType NewEltTy=AT->getElementType().getWithAdditionalQualifiers(TypeQuals);
2026 NewEltTy = getCanonicalType(NewEltTy);
2027
2028 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
2029 return getConstantArrayType(NewEltTy, CAT->getSize(),CAT->getSizeModifier(),
2030 CAT->getIndexTypeQualifier());
2031 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
2032 return getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
2033 IAT->getIndexTypeQualifier());
2034
Douglas Gregor898574e2008-12-05 23:32:09 +00002035 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002036 return getDependentSizedArrayType(NewEltTy,
2037 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00002038 DSAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002039 DSAT->getIndexTypeQualifier(),
2040 DSAT->getBracketsRange());
Douglas Gregor898574e2008-12-05 23:32:09 +00002041
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002042 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002043 return getVariableArrayType(NewEltTy,
2044 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002045 VAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002046 VAT->getIndexTypeQualifier(),
2047 VAT->getBracketsRange());
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002048}
2049
Douglas Gregor7da97d02009-05-10 22:57:19 +00002050Decl *ASTContext::getCanonicalDecl(Decl *D) {
Douglas Gregorc4ccf012009-05-10 22:59:12 +00002051 if (!D)
2052 return 0;
2053
Douglas Gregor7da97d02009-05-10 22:57:19 +00002054 if (TagDecl *Tag = dyn_cast<TagDecl>(D)) {
2055 QualType T = getTagDeclType(Tag);
2056 return cast<TagDecl>(cast<TagType>(T.getTypePtr()->CanonicalType)
2057 ->getDecl());
2058 }
2059
2060 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(D)) {
2061 while (Template->getPreviousDeclaration())
2062 Template = Template->getPreviousDeclaration();
2063 return Template;
2064 }
2065
2066 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2067 while (Function->getPreviousDeclaration())
2068 Function = Function->getPreviousDeclaration();
2069 return const_cast<FunctionDecl *>(Function);
2070 }
2071
Douglas Gregor127102b2009-06-29 20:59:39 +00002072 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
2073 while (FunTmpl->getPreviousDeclaration())
2074 FunTmpl = FunTmpl->getPreviousDeclaration();
2075 return FunTmpl;
2076 }
2077
Douglas Gregor7da97d02009-05-10 22:57:19 +00002078 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
2079 while (Var->getPreviousDeclaration())
2080 Var = Var->getPreviousDeclaration();
2081 return const_cast<VarDecl *>(Var);
2082 }
2083
2084 return D;
2085}
2086
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002087TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
2088 // If this template name refers to a template, the canonical
2089 // template name merely stores the template itself.
2090 if (TemplateDecl *Template = Name.getAsTemplateDecl())
Douglas Gregor7da97d02009-05-10 22:57:19 +00002091 return TemplateName(cast<TemplateDecl>(getCanonicalDecl(Template)));
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002092
2093 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2094 assert(DTN && "Non-dependent template names must refer to template decls.");
2095 return DTN->CanonicalTemplateName;
2096}
2097
Douglas Gregord57959a2009-03-27 23:10:48 +00002098NestedNameSpecifier *
2099ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
2100 if (!NNS)
2101 return 0;
2102
2103 switch (NNS->getKind()) {
2104 case NestedNameSpecifier::Identifier:
2105 // Canonicalize the prefix but keep the identifier the same.
2106 return NestedNameSpecifier::Create(*this,
2107 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2108 NNS->getAsIdentifier());
2109
2110 case NestedNameSpecifier::Namespace:
2111 // A namespace is canonical; build a nested-name-specifier with
2112 // this namespace and no prefix.
2113 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2114
2115 case NestedNameSpecifier::TypeSpec:
2116 case NestedNameSpecifier::TypeSpecWithTemplate: {
2117 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
2118 NestedNameSpecifier *Prefix = 0;
2119
2120 // FIXME: This isn't the right check!
2121 if (T->isDependentType())
2122 Prefix = getCanonicalNestedNameSpecifier(NNS->getPrefix());
2123
2124 return NestedNameSpecifier::Create(*this, Prefix,
2125 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
2126 T.getTypePtr());
2127 }
2128
2129 case NestedNameSpecifier::Global:
2130 // The global specifier is canonical and unique.
2131 return NNS;
2132 }
2133
2134 // Required to silence a GCC warning
2135 return 0;
2136}
2137
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002138
2139const ArrayType *ASTContext::getAsArrayType(QualType T) {
2140 // Handle the non-qualified case efficiently.
2141 if (T.getCVRQualifiers() == 0) {
2142 // Handle the common positive case fast.
2143 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2144 return AT;
2145 }
2146
2147 // Handle the common negative case fast, ignoring CVR qualifiers.
2148 QualType CType = T->getCanonicalTypeInternal();
2149
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002150 // Make sure to look through type qualifiers (like ExtQuals) for the negative
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002151 // test.
2152 if (!isa<ArrayType>(CType) &&
2153 !isa<ArrayType>(CType.getUnqualifiedType()))
2154 return 0;
2155
2156 // Apply any CVR qualifiers from the array type to the element type. This
2157 // implements C99 6.7.3p8: "If the specification of an array type includes
2158 // any type qualifiers, the element type is so qualified, not the array type."
2159
2160 // If we get here, we either have type qualifiers on the type, or we have
2161 // sugar such as a typedef in the way. If we have type qualifiers on the type
2162 // we must propagate them down into the elemeng type.
2163 unsigned CVRQuals = T.getCVRQualifiers();
2164 unsigned AddrSpace = 0;
2165 Type *Ty = T.getTypePtr();
2166
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002167 // Rip through ExtQualType's and typedefs to get to a concrete type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002168 while (1) {
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002169 if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(Ty)) {
2170 AddrSpace = EXTQT->getAddressSpace();
2171 Ty = EXTQT->getBaseType();
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002172 } else {
2173 T = Ty->getDesugaredType();
2174 if (T.getTypePtr() == Ty && T.getCVRQualifiers() == 0)
2175 break;
2176 CVRQuals |= T.getCVRQualifiers();
2177 Ty = T.getTypePtr();
2178 }
2179 }
2180
2181 // If we have a simple case, just return now.
2182 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
2183 if (ATy == 0 || (AddrSpace == 0 && CVRQuals == 0))
2184 return ATy;
2185
2186 // Otherwise, we have an array and we have qualifiers on it. Push the
2187 // qualifiers into the array element type and return a new array type.
2188 // Get the canonical version of the element with the extra qualifiers on it.
2189 // This can recursively sink qualifiers through multiple levels of arrays.
2190 QualType NewEltTy = ATy->getElementType();
2191 if (AddrSpace)
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00002192 NewEltTy = getAddrSpaceQualType(NewEltTy, AddrSpace);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002193 NewEltTy = NewEltTy.getWithAdditionalQualifiers(CVRQuals);
2194
2195 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2196 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2197 CAT->getSizeModifier(),
2198 CAT->getIndexTypeQualifier()));
2199 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2200 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2201 IAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002202 IAT->getIndexTypeQualifier()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002203
Douglas Gregor898574e2008-12-05 23:32:09 +00002204 if (const DependentSizedArrayType *DSAT
2205 = dyn_cast<DependentSizedArrayType>(ATy))
2206 return cast<ArrayType>(
2207 getDependentSizedArrayType(NewEltTy,
2208 DSAT->getSizeExpr(),
2209 DSAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002210 DSAT->getIndexTypeQualifier(),
2211 DSAT->getBracketsRange()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002212
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002213 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002214 return cast<ArrayType>(getVariableArrayType(NewEltTy,
2215 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002216 VAT->getSizeModifier(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002217 VAT->getIndexTypeQualifier(),
2218 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00002219}
2220
2221
Chris Lattnere6327742008-04-02 05:18:44 +00002222/// getArrayDecayedType - Return the properly qualified result of decaying the
2223/// specified array type to a pointer. This operation is non-trivial when
2224/// handling typedefs etc. The canonical type of "T" must be an array type,
2225/// this returns a pointer to a properly qualified element of the array.
2226///
2227/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2228QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002229 // Get the element type with 'getAsArrayType' so that we don't lose any
2230 // typedefs in the element type of the array. This also handles propagation
2231 // of type qualifiers from the array type into the element type if present
2232 // (C99 6.7.3p8).
2233 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2234 assert(PrettyArrayType && "Not an array type!");
Chris Lattnere6327742008-04-02 05:18:44 +00002235
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002236 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00002237
2238 // int x[restrict 4] -> int *restrict
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002239 return PtrTy.getQualifiedType(PrettyArrayType->getIndexTypeQualifier());
Chris Lattnere6327742008-04-02 05:18:44 +00002240}
2241
Daniel Dunbard786f6a2009-01-05 22:14:37 +00002242QualType ASTContext::getBaseElementType(const VariableArrayType *VAT) {
Anders Carlsson6183a992008-12-21 03:44:36 +00002243 QualType ElemTy = VAT->getElementType();
2244
2245 if (const VariableArrayType *VAT = getAsVariableArrayType(ElemTy))
2246 return getBaseElementType(VAT);
2247
2248 return ElemTy;
2249}
2250
Reid Spencer5f016e22007-07-11 17:01:13 +00002251/// getFloatingRank - Return a relative rank for floating point types.
2252/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00002253static FloatingRank getFloatingRank(QualType T) {
Christopher Lambebb97e92008-02-04 02:31:56 +00002254 if (const ComplexType *CT = T->getAsComplexType())
Reid Spencer5f016e22007-07-11 17:01:13 +00002255 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00002256
Daniel Dunbard786f6a2009-01-05 22:14:37 +00002257 assert(T->getAsBuiltinType() && "getFloatingRank(): not a floating type");
Christopher Lambebb97e92008-02-04 02:31:56 +00002258 switch (T->getAsBuiltinType()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00002259 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002260 case BuiltinType::Float: return FloatRank;
2261 case BuiltinType::Double: return DoubleRank;
2262 case BuiltinType::LongDouble: return LongDoubleRank;
2263 }
2264}
2265
Steve Naroff716c7302007-08-27 01:41:48 +00002266/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2267/// point or a complex type (based on typeDomain/typeSize).
2268/// 'typeDomain' is a real floating point or complex type.
2269/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00002270QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2271 QualType Domain) const {
2272 FloatingRank EltRank = getFloatingRank(Size);
2273 if (Domain->isComplexType()) {
2274 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00002275 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00002276 case FloatRank: return FloatComplexTy;
2277 case DoubleRank: return DoubleComplexTy;
2278 case LongDoubleRank: return LongDoubleComplexTy;
2279 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002280 }
Chris Lattner1361b112008-04-06 23:58:54 +00002281
2282 assert(Domain->isRealFloatingType() && "Unknown domain!");
2283 switch (EltRank) {
2284 default: assert(0 && "getFloatingRank(): illegal value for rank");
2285 case FloatRank: return FloatTy;
2286 case DoubleRank: return DoubleTy;
2287 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00002288 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002289}
2290
Chris Lattner7cfeb082008-04-06 23:55:33 +00002291/// getFloatingTypeOrder - Compare the rank of the two specified floating
2292/// point types, ignoring the domain of the type (i.e. 'double' ==
2293/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
2294/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00002295int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2296 FloatingRank LHSR = getFloatingRank(LHS);
2297 FloatingRank RHSR = getFloatingRank(RHS);
2298
2299 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002300 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00002301 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002302 return 1;
2303 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002304}
2305
Chris Lattnerf52ab252008-04-06 22:59:24 +00002306/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2307/// routine will assert if passed a built-in type that isn't an integer or enum,
2308/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00002309unsigned ASTContext::getIntegerRank(Type *T) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002310 assert(T->isCanonical() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00002311 if (EnumType* ET = dyn_cast<EnumType>(T))
2312 T = ET->getDecl()->getIntegerType().getTypePtr();
2313
Eli Friedmana3426752009-07-05 23:44:27 +00002314 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2315 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2316
Eli Friedmanf98aba32009-02-13 02:31:07 +00002317 // There are two things which impact the integer rank: the width, and
2318 // the ordering of builtins. The builtin ordering is encoded in the
2319 // bottom three bits; the width is encoded in the bits above that.
Chris Lattner1b63e4f2009-06-14 01:54:56 +00002320 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T))
Eli Friedmanf98aba32009-02-13 02:31:07 +00002321 return FWIT->getWidth() << 3;
Eli Friedmanf98aba32009-02-13 02:31:07 +00002322
Chris Lattnerf52ab252008-04-06 22:59:24 +00002323 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00002324 default: assert(0 && "getIntegerRank(): not a built-in integer");
2325 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002326 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002327 case BuiltinType::Char_S:
2328 case BuiltinType::Char_U:
2329 case BuiltinType::SChar:
2330 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002331 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002332 case BuiltinType::Short:
2333 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002334 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002335 case BuiltinType::Int:
2336 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002337 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002338 case BuiltinType::Long:
2339 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002340 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002341 case BuiltinType::LongLong:
2342 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002343 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00002344 case BuiltinType::Int128:
2345 case BuiltinType::UInt128:
2346 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00002347 }
2348}
2349
Chris Lattner7cfeb082008-04-06 23:55:33 +00002350/// getIntegerTypeOrder - Returns the highest ranked integer type:
2351/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
2352/// LHS < RHS, return -1.
2353int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002354 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2355 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00002356 if (LHSC == RHSC) return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00002357
Chris Lattnerf52ab252008-04-06 22:59:24 +00002358 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2359 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002360
Chris Lattner7cfeb082008-04-06 23:55:33 +00002361 unsigned LHSRank = getIntegerRank(LHSC);
2362 unsigned RHSRank = getIntegerRank(RHSC);
Reid Spencer5f016e22007-07-11 17:01:13 +00002363
Chris Lattner7cfeb082008-04-06 23:55:33 +00002364 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2365 if (LHSRank == RHSRank) return 0;
2366 return LHSRank > RHSRank ? 1 : -1;
2367 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002368
Chris Lattner7cfeb082008-04-06 23:55:33 +00002369 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2370 if (LHSUnsigned) {
2371 // If the unsigned [LHS] type is larger, return it.
2372 if (LHSRank >= RHSRank)
2373 return 1;
2374
2375 // If the signed type can represent all values of the unsigned type, it
2376 // wins. Because we are dealing with 2's complement and types that are
2377 // powers of two larger than each other, this is always safe.
2378 return -1;
2379 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00002380
Chris Lattner7cfeb082008-04-06 23:55:33 +00002381 // If the unsigned [RHS] type is larger, return it.
2382 if (RHSRank >= LHSRank)
2383 return -1;
2384
2385 // If the signed type can represent all values of the unsigned type, it
2386 // wins. Because we are dealing with 2's complement and types that are
2387 // powers of two larger than each other, this is always safe.
2388 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002389}
Anders Carlsson71993dd2007-08-17 05:31:46 +00002390
2391// getCFConstantStringType - Return the type used for constant CFStrings.
2392QualType ASTContext::getCFConstantStringType() {
2393 if (!CFConstantStringTypeDecl) {
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002394 CFConstantStringTypeDecl =
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002395 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002396 &Idents.get("NSConstantString"));
Anders Carlssonf06273f2007-11-19 00:25:30 +00002397 QualType FieldTypes[4];
Anders Carlsson71993dd2007-08-17 05:31:46 +00002398
2399 // const int *isa;
2400 FieldTypes[0] = getPointerType(IntTy.getQualifiedType(QualType::Const));
Anders Carlssonf06273f2007-11-19 00:25:30 +00002401 // int flags;
2402 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00002403 // const char *str;
Anders Carlssonf06273f2007-11-19 00:25:30 +00002404 FieldTypes[2] = getPointerType(CharTy.getQualifiedType(QualType::Const));
Anders Carlsson71993dd2007-08-17 05:31:46 +00002405 // long length;
Anders Carlssonf06273f2007-11-19 00:25:30 +00002406 FieldTypes[3] = LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002407
Anders Carlsson71993dd2007-08-17 05:31:46 +00002408 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002409 for (unsigned i = 0; i < 4; ++i) {
2410 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
2411 SourceLocation(), 0,
2412 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002413 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002414 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002415 }
2416
2417 CFConstantStringTypeDecl->completeDefinition(*this);
Anders Carlsson71993dd2007-08-17 05:31:46 +00002418 }
2419
2420 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00002421}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002422
Douglas Gregor319ac892009-04-23 22:29:11 +00002423void ASTContext::setCFConstantStringType(QualType T) {
2424 const RecordType *Rec = T->getAsRecordType();
2425 assert(Rec && "Invalid CFConstantStringType");
2426 CFConstantStringTypeDecl = Rec->getDecl();
2427}
2428
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002429QualType ASTContext::getObjCFastEnumerationStateType()
2430{
2431 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00002432 ObjCFastEnumerationStateTypeDecl =
2433 RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2434 &Idents.get("__objcFastEnumerationState"));
2435
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002436 QualType FieldTypes[] = {
2437 UnsignedLongTy,
2438 getPointerType(ObjCIdType),
2439 getPointerType(UnsignedLongTy),
2440 getConstantArrayType(UnsignedLongTy,
2441 llvm::APInt(32, 5), ArrayType::Normal, 0)
2442 };
2443
Douglas Gregor44b43212008-12-11 16:49:14 +00002444 for (size_t i = 0; i < 4; ++i) {
2445 FieldDecl *Field = FieldDecl::Create(*this,
2446 ObjCFastEnumerationStateTypeDecl,
2447 SourceLocation(), 0,
2448 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002449 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002450 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002451 }
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002452
Douglas Gregor44b43212008-12-11 16:49:14 +00002453 ObjCFastEnumerationStateTypeDecl->completeDefinition(*this);
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002454 }
2455
2456 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2457}
2458
Douglas Gregor319ac892009-04-23 22:29:11 +00002459void ASTContext::setObjCFastEnumerationStateType(QualType T) {
2460 const RecordType *Rec = T->getAsRecordType();
2461 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
2462 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
2463}
2464
Anders Carlssone8c49532007-10-29 06:33:42 +00002465// This returns true if a type has been typedefed to BOOL:
2466// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00002467static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00002468 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00002469 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
2470 return II->isStr("BOOL");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002471
2472 return false;
2473}
2474
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002475/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002476/// purpose.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002477int ASTContext::getObjCEncodingTypeSize(QualType type) {
Chris Lattner98be4942008-03-05 18:54:05 +00002478 uint64_t sz = getTypeSize(type);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002479
2480 // Make all integer and enum types at least as large as an int
2481 if (sz > 0 && type->isIntegralType())
Chris Lattner98be4942008-03-05 18:54:05 +00002482 sz = std::max(sz, getTypeSize(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002483 // Treat arrays as pointers, since that's how they're passed in.
2484 else if (type->isArrayType())
Chris Lattner98be4942008-03-05 18:54:05 +00002485 sz = getTypeSize(VoidPtrTy);
2486 return sz / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002487}
2488
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002489/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002490/// declaration.
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002491void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00002492 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002493 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002494 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002495 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002496 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002497 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002498 // Compute size of all parameters.
2499 // Start with computing size of a pointer in number of bytes.
2500 // FIXME: There might(should) be a better way of doing this computation!
2501 SourceLocation Loc;
Chris Lattner98be4942008-03-05 18:54:05 +00002502 int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002503 // The first two arguments (self and _cmd) are pointers; account for
2504 // their size.
2505 int ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00002506 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2507 E = Decl->param_end(); PI != E; ++PI) {
2508 QualType PType = (*PI)->getType();
2509 int sz = getObjCEncodingTypeSize(PType);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002510 assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002511 ParmOffset += sz;
2512 }
2513 S += llvm::utostr(ParmOffset);
2514 S += "@0:";
2515 S += llvm::utostr(PtrSize);
2516
2517 // Argument types.
2518 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00002519 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2520 E = Decl->param_end(); PI != E; ++PI) {
2521 ParmVarDecl *PVDecl = *PI;
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00002522 QualType PType = PVDecl->getOriginalType();
2523 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00002524 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
2525 // Use array's original type only if it has known number of
2526 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00002527 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00002528 PType = PVDecl->getType();
2529 } else if (PType->isFunctionType())
2530 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002531 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002532 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00002533 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002534 getObjCEncodingForType(PType, S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002535 S += llvm::utostr(ParmOffset);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002536 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002537 }
2538}
2539
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002540/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00002541/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002542/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
2543/// NULL when getting encodings for protocol properties.
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00002544/// Property attributes are stored as a comma-delimited C string. The simple
2545/// attributes readonly and bycopy are encoded as single characters. The
2546/// parametrized attributes, getter=name, setter=name, and ivar=name, are
2547/// encoded as single characters, followed by an identifier. Property types
2548/// are also encoded as a parametrized attribute. The characters used to encode
2549/// these attributes are defined by the following enumeration:
2550/// @code
2551/// enum PropertyAttributes {
2552/// kPropertyReadOnly = 'R', // property is read-only.
2553/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
2554/// kPropertyByref = '&', // property is a reference to the value last assigned
2555/// kPropertyDynamic = 'D', // property is dynamic
2556/// kPropertyGetter = 'G', // followed by getter selector name
2557/// kPropertySetter = 'S', // followed by setter selector name
2558/// kPropertyInstanceVariable = 'V' // followed by instance variable name
2559/// kPropertyType = 't' // followed by old-style type encoding.
2560/// kPropertyWeak = 'W' // 'weak' property
2561/// kPropertyStrong = 'P' // property GC'able
2562/// kPropertyNonAtomic = 'N' // property non-atomic
2563/// };
2564/// @endcode
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002565void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
2566 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00002567 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002568 // Collect information from the property implementation decl(s).
2569 bool Dynamic = false;
2570 ObjCPropertyImplDecl *SynthesizePID = 0;
2571
2572 // FIXME: Duplicated code due to poor abstraction.
2573 if (Container) {
2574 if (const ObjCCategoryImplDecl *CID =
2575 dyn_cast<ObjCCategoryImplDecl>(Container)) {
2576 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002577 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00002578 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002579 ObjCPropertyImplDecl *PID = *i;
2580 if (PID->getPropertyDecl() == PD) {
2581 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2582 Dynamic = true;
2583 } else {
2584 SynthesizePID = PID;
2585 }
2586 }
2587 }
2588 } else {
Chris Lattner61710852008-10-05 17:34:18 +00002589 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002590 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002591 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00002592 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002593 ObjCPropertyImplDecl *PID = *i;
2594 if (PID->getPropertyDecl() == PD) {
2595 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2596 Dynamic = true;
2597 } else {
2598 SynthesizePID = PID;
2599 }
2600 }
2601 }
2602 }
2603 }
2604
2605 // FIXME: This is not very efficient.
2606 S = "T";
2607
2608 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002609 // GCC has some special rules regarding encoding of properties which
2610 // closely resembles encoding of ivars.
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002611 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002612 true /* outermost type */,
2613 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002614
2615 if (PD->isReadOnly()) {
2616 S += ",R";
2617 } else {
2618 switch (PD->getSetterKind()) {
2619 case ObjCPropertyDecl::Assign: break;
2620 case ObjCPropertyDecl::Copy: S += ",C"; break;
2621 case ObjCPropertyDecl::Retain: S += ",&"; break;
2622 }
2623 }
2624
2625 // It really isn't clear at all what this means, since properties
2626 // are "dynamic by default".
2627 if (Dynamic)
2628 S += ",D";
2629
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002630 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
2631 S += ",N";
2632
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002633 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
2634 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002635 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002636 }
2637
2638 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
2639 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002640 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002641 }
2642
2643 if (SynthesizePID) {
2644 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
2645 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00002646 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00002647 }
2648
2649 // FIXME: OBJCGC: weak & strong
2650}
2651
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002652/// getLegacyIntegralTypeEncoding -
2653/// Another legacy compatibility encoding: 32-bit longs are encoded as
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002654/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002655/// 'i' or 'I' instead if encoding a struct field, or a pointer!
2656///
2657void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
2658 if (dyn_cast<TypedefType>(PointeeTy.getTypePtr())) {
2659 if (const BuiltinType *BT = PointeeTy->getAsBuiltinType()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002660 if (BT->getKind() == BuiltinType::ULong &&
2661 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002662 PointeeTy = UnsignedIntTy;
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00002663 else
2664 if (BT->getKind() == BuiltinType::Long &&
2665 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002666 PointeeTy = IntTy;
2667 }
2668 }
2669}
2670
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002671void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002672 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002673 // We follow the behavior of gcc, expanding structures which are
2674 // directly pointed to, and expanding embedded structures. Note that
2675 // these rules are sufficient to prevent recursive encoding of the
2676 // same type.
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00002677 getObjCEncodingForTypeImpl(T, S, true, true, Field,
2678 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002679}
2680
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002681static void EncodeBitField(const ASTContext *Context, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002682 const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002683 const Expr *E = FD->getBitWidth();
2684 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
2685 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Eli Friedman9a901bb2009-04-26 19:19:15 +00002686 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002687 S += 'b';
2688 S += llvm::utostr(N);
2689}
2690
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002691void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
2692 bool ExpandPointedToStructures,
2693 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00002694 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002695 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002696 bool EncodingProperty) {
Anders Carlssone8c49532007-10-29 06:33:42 +00002697 if (const BuiltinType *BT = T->getAsBuiltinType()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002698 if (FD && FD->isBitField()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002699 EncodeBitField(this, S, FD);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002700 }
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002701 else {
2702 char encoding;
2703 switch (BT->getKind()) {
2704 default: assert(0 && "Unhandled builtin type kind");
2705 case BuiltinType::Void: encoding = 'v'; break;
2706 case BuiltinType::Bool: encoding = 'B'; break;
2707 case BuiltinType::Char_U:
2708 case BuiltinType::UChar: encoding = 'C'; break;
2709 case BuiltinType::UShort: encoding = 'S'; break;
2710 case BuiltinType::UInt: encoding = 'I'; break;
Fariborz Jahanian72696e12009-02-11 22:31:45 +00002711 case BuiltinType::ULong:
2712 encoding =
2713 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
2714 break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002715 case BuiltinType::UInt128: encoding = 'T'; break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002716 case BuiltinType::ULongLong: encoding = 'Q'; break;
2717 case BuiltinType::Char_S:
2718 case BuiltinType::SChar: encoding = 'c'; break;
2719 case BuiltinType::Short: encoding = 's'; break;
2720 case BuiltinType::Int: encoding = 'i'; break;
Fariborz Jahanian72696e12009-02-11 22:31:45 +00002721 case BuiltinType::Long:
2722 encoding =
2723 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
2724 break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002725 case BuiltinType::LongLong: encoding = 'q'; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002726 case BuiltinType::Int128: encoding = 't'; break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002727 case BuiltinType::Float: encoding = 'f'; break;
2728 case BuiltinType::Double: encoding = 'd'; break;
2729 case BuiltinType::LongDouble: encoding = 'd'; break;
2730 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002731
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002732 S += encoding;
2733 }
Anders Carlssonc612f7b2009-04-09 21:55:45 +00002734 } else if (const ComplexType *CT = T->getAsComplexType()) {
2735 S += 'j';
2736 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
2737 false);
2738 } else if (T->isObjCQualifiedIdType()) {
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002739 getObjCEncodingForTypeImpl(getObjCIdType(), S,
2740 ExpandPointedToStructures,
2741 ExpandStructures, FD);
2742 if (FD || EncodingProperty) {
2743 // Note that we do extended encoding of protocol qualifer list
2744 // Only when doing ivar or property encoding.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002745 const ObjCObjectPointerType *QIDT = T->getAsObjCQualifiedIdType();
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002746 S += '"';
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002747 for (ObjCObjectPointerType::qual_iterator I = QIDT->qual_begin(),
Steve Naroff446ee4e2009-05-27 16:21:00 +00002748 E = QIDT->qual_end(); I != E; ++I) {
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002749 S += '<';
Steve Naroff446ee4e2009-05-27 16:21:00 +00002750 S += (*I)->getNameAsString();
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002751 S += '>';
2752 }
2753 S += '"';
2754 }
2755 return;
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002756 }
2757 else if (const PointerType *PT = T->getAsPointerType()) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002758 QualType PointeeTy = PT->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002759 bool isReadOnly = false;
2760 // For historical/compatibility reasons, the read-only qualifier of the
2761 // pointee gets emitted _before_ the '^'. The read-only qualifier of
2762 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
2763 // Also, do not emit the 'r' for anything but the outermost type!
2764 if (dyn_cast<TypedefType>(T.getTypePtr())) {
2765 if (OutermostType && T.isConstQualified()) {
2766 isReadOnly = true;
2767 S += 'r';
2768 }
2769 }
2770 else if (OutermostType) {
2771 QualType P = PointeeTy;
2772 while (P->getAsPointerType())
2773 P = P->getAsPointerType()->getPointeeType();
2774 if (P.isConstQualified()) {
2775 isReadOnly = true;
2776 S += 'r';
2777 }
2778 }
2779 if (isReadOnly) {
2780 // Another legacy compatibility encoding. Some ObjC qualifier and type
2781 // combinations need to be rearranged.
2782 // Rewrite "in const" from "nr" to "rn"
2783 const char * s = S.c_str();
2784 int len = S.length();
2785 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
2786 std::string replace = "rn";
2787 S.replace(S.end()-2, S.end(), replace);
2788 }
2789 }
Steve Naroff389bf462009-02-12 17:52:19 +00002790 if (isObjCIdStructType(PointeeTy)) {
Fariborz Jahanianc2939bc2007-10-30 17:06:23 +00002791 S += '@';
2792 return;
Fariborz Jahanianc166d732008-12-19 00:14:49 +00002793 }
2794 else if (PointeeTy->isObjCInterfaceType()) {
Fariborz Jahanianbb99bde2009-02-16 21:41:04 +00002795 if (!EncodingProperty &&
Fariborz Jahanian225dfd72009-02-16 22:09:26 +00002796 isa<TypedefType>(PointeeTy.getTypePtr())) {
Fariborz Jahanian3e1b16c2008-12-23 21:30:15 +00002797 // Another historical/compatibility reason.
2798 // We encode the underlying type which comes out as
2799 // {...};
2800 S += '^';
2801 getObjCEncodingForTypeImpl(PointeeTy, S,
2802 false, ExpandPointedToStructures,
2803 NULL);
2804 return;
2805 }
Fariborz Jahanianc166d732008-12-19 00:14:49 +00002806 S += '@';
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002807 if (FD || EncodingProperty) {
Fariborz Jahanian86f938b2009-02-21 18:23:24 +00002808 const ObjCInterfaceType *OIT =
2809 PointeeTy.getUnqualifiedType()->getAsObjCInterfaceType();
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002810 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanianadcaf542008-12-20 19:17:01 +00002811 S += '"';
2812 S += OI->getNameAsCString();
Steve Naroff446ee4e2009-05-27 16:21:00 +00002813 for (ObjCInterfaceType::qual_iterator I = OIT->qual_begin(),
2814 E = OIT->qual_end(); I != E; ++I) {
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002815 S += '<';
Steve Naroff446ee4e2009-05-27 16:21:00 +00002816 S += (*I)->getNameAsString();
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00002817 S += '>';
2818 }
Fariborz Jahanianadcaf542008-12-20 19:17:01 +00002819 S += '"';
2820 }
Fariborz Jahanianc166d732008-12-19 00:14:49 +00002821 return;
Steve Naroff389bf462009-02-12 17:52:19 +00002822 } else if (isObjCClassStructType(PointeeTy)) {
Anders Carlsson8baaca52007-10-31 02:53:19 +00002823 S += '#';
2824 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002825 } else if (isObjCSelType(PointeeTy)) {
Anders Carlsson8baaca52007-10-31 02:53:19 +00002826 S += ':';
2827 return;
Fariborz Jahanianc2939bc2007-10-30 17:06:23 +00002828 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002829
2830 if (PointeeTy->isCharType()) {
2831 // char pointer types should be encoded as '*' unless it is a
2832 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00002833 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002834 S += '*';
2835 return;
2836 }
2837 }
2838
2839 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002840 getLegacyIntegralTypeEncoding(PointeeTy);
2841
2842 getObjCEncodingForTypeImpl(PointeeTy, S,
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002843 false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002844 NULL);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002845 } else if (const ArrayType *AT =
2846 // Ignore type qualifiers etc.
2847 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00002848 if (isa<IncompleteArrayType>(AT)) {
2849 // Incomplete arrays are encoded as a pointer to the array element.
2850 S += '^';
2851
2852 getObjCEncodingForTypeImpl(AT->getElementType(), S,
2853 false, ExpandStructures, FD);
2854 } else {
2855 S += '[';
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002856
Anders Carlsson559a8332009-02-22 01:38:57 +00002857 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
2858 S += llvm::utostr(CAT->getSize().getZExtValue());
2859 else {
2860 //Variable length arrays are encoded as a regular array with 0 elements.
2861 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
2862 S += '0';
2863 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002864
Anders Carlsson559a8332009-02-22 01:38:57 +00002865 getObjCEncodingForTypeImpl(AT->getElementType(), S,
2866 false, ExpandStructures, FD);
2867 S += ']';
2868 }
Anders Carlssonc0a87b72007-10-30 00:06:20 +00002869 } else if (T->getAsFunctionType()) {
2870 S += '?';
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00002871 } else if (const RecordType *RTy = T->getAsRecordType()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00002872 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002873 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00002874 // Anonymous structures print as '?'
2875 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
2876 S += II->getName();
2877 } else {
2878 S += '?';
2879 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002880 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002881 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002882 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
2883 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00002884 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002885 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002886 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00002887 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002888 S += '"';
2889 }
2890
2891 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002892 if (Field->isBitField()) {
2893 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
2894 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002895 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00002896 QualType qt = Field->getType();
2897 getLegacyIntegralTypeEncoding(qt);
2898 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002899 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002900 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002901 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00002902 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00002903 S += RDecl->isUnion() ? ')' : '}';
Steve Naroff5e711242007-12-12 22:30:11 +00002904 } else if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00002905 if (FD && FD->isBitField())
2906 EncodeBitField(this, S, FD);
2907 else
2908 S += 'i';
Steve Naroff485eeff2008-09-24 15:05:44 +00002909 } else if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00002910 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002911 } else if (T->isObjCInterfaceType()) {
2912 // @encode(class_name)
2913 ObjCInterfaceDecl *OI = T->getAsObjCInterfaceType()->getDecl();
2914 S += '{';
2915 const IdentifierInfo *II = OI->getIdentifier();
2916 S += II->getName();
2917 S += '=';
Chris Lattnerf1690852009-03-31 08:48:01 +00002918 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002919 CollectObjCIvars(OI, RecFields);
Chris Lattnerf1690852009-03-31 08:48:01 +00002920 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00002921 if (RecFields[i]->isBitField())
2922 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2923 RecFields[i]);
2924 else
2925 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2926 FD);
2927 }
2928 S += '}';
2929 }
2930 else
Steve Narofff69cc5d2008-01-30 19:17:43 +00002931 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002932}
2933
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002934void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00002935 std::string& S) const {
2936 if (QT & Decl::OBJC_TQ_In)
2937 S += 'n';
2938 if (QT & Decl::OBJC_TQ_Inout)
2939 S += 'N';
2940 if (QT & Decl::OBJC_TQ_Out)
2941 S += 'o';
2942 if (QT & Decl::OBJC_TQ_Bycopy)
2943 S += 'O';
2944 if (QT & Decl::OBJC_TQ_Byref)
2945 S += 'R';
2946 if (QT & Decl::OBJC_TQ_Oneway)
2947 S += 'V';
2948}
2949
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002950void ASTContext::setBuiltinVaListType(QualType T)
2951{
2952 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
2953
2954 BuiltinVaListType = T;
2955}
2956
Douglas Gregor319ac892009-04-23 22:29:11 +00002957void ASTContext::setObjCIdType(QualType T)
Steve Naroff7e219e42007-10-15 14:41:52 +00002958{
Douglas Gregor319ac892009-04-23 22:29:11 +00002959 ObjCIdType = T;
2960
2961 const TypedefType *TT = T->getAsTypedefType();
2962 if (!TT)
2963 return;
2964
2965 TypedefDecl *TD = TT->getDecl();
Steve Naroff7e219e42007-10-15 14:41:52 +00002966
2967 // typedef struct objc_object *id;
2968 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00002969 // User error - caller will issue diagnostics.
2970 if (!ptr)
2971 return;
Steve Naroff7e219e42007-10-15 14:41:52 +00002972 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00002973 // User error - caller will issue diagnostics.
2974 if (!rec)
2975 return;
Steve Naroff7e219e42007-10-15 14:41:52 +00002976 IdStructType = rec;
2977}
2978
Douglas Gregor319ac892009-04-23 22:29:11 +00002979void ASTContext::setObjCSelType(QualType T)
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002980{
Douglas Gregor319ac892009-04-23 22:29:11 +00002981 ObjCSelType = T;
2982
2983 const TypedefType *TT = T->getAsTypedefType();
2984 if (!TT)
2985 return;
2986 TypedefDecl *TD = TT->getDecl();
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002987
2988 // typedef struct objc_selector *SEL;
2989 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00002990 if (!ptr)
2991 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002992 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +00002993 if (!rec)
2994 return;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00002995 SelStructType = rec;
2996}
2997
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002998void ASTContext::setObjCProtoType(QualType QT)
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00002999{
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003000 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00003001}
3002
Douglas Gregor319ac892009-04-23 22:29:11 +00003003void ASTContext::setObjCClassType(QualType T)
Anders Carlsson8baaca52007-10-31 02:53:19 +00003004{
Douglas Gregor319ac892009-04-23 22:29:11 +00003005 ObjCClassType = T;
3006
3007 const TypedefType *TT = T->getAsTypedefType();
3008 if (!TT)
3009 return;
3010 TypedefDecl *TD = TT->getDecl();
Anders Carlsson8baaca52007-10-31 02:53:19 +00003011
3012 // typedef struct objc_class *Class;
3013 const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
3014 assert(ptr && "'Class' incorrectly typed");
3015 const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
3016 assert(rec && "'Class' incorrectly typed");
3017 ClassStructType = rec;
3018}
3019
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003020void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
3021 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00003022 "'NSConstantString' type already set!");
3023
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003024 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00003025}
3026
Douglas Gregor7532dc62009-03-30 22:58:21 +00003027/// \brief Retrieve the template name that represents a qualified
3028/// template name such as \c std::vector.
3029TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
3030 bool TemplateKeyword,
3031 TemplateDecl *Template) {
3032 llvm::FoldingSetNodeID ID;
3033 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3034
3035 void *InsertPos = 0;
3036 QualifiedTemplateName *QTN =
3037 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3038 if (!QTN) {
3039 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3040 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3041 }
3042
3043 return TemplateName(QTN);
3044}
3045
3046/// \brief Retrieve the template name that represents a dependent
3047/// template name such as \c MetaFun::template apply.
3048TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
3049 const IdentifierInfo *Name) {
3050 assert(NNS->isDependent() && "Nested name specifier must be dependent");
3051
3052 llvm::FoldingSetNodeID ID;
3053 DependentTemplateName::Profile(ID, NNS, Name);
3054
3055 void *InsertPos = 0;
3056 DependentTemplateName *QTN =
3057 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3058
3059 if (QTN)
3060 return TemplateName(QTN);
3061
3062 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3063 if (CanonNNS == NNS) {
3064 QTN = new (*this,4) DependentTemplateName(NNS, Name);
3065 } else {
3066 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
3067 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
3068 }
3069
3070 DependentTemplateNames.InsertNode(QTN, InsertPos);
3071 return TemplateName(QTN);
3072}
3073
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003074/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00003075/// TargetInfo, produce the corresponding type. The unsigned @p Type
3076/// is actually a value of type @c TargetInfo::IntType.
3077QualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003078 switch (Type) {
3079 case TargetInfo::NoInt: return QualType();
3080 case TargetInfo::SignedShort: return ShortTy;
3081 case TargetInfo::UnsignedShort: return UnsignedShortTy;
3082 case TargetInfo::SignedInt: return IntTy;
3083 case TargetInfo::UnsignedInt: return UnsignedIntTy;
3084 case TargetInfo::SignedLong: return LongTy;
3085 case TargetInfo::UnsignedLong: return UnsignedLongTy;
3086 case TargetInfo::SignedLongLong: return LongLongTy;
3087 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
3088 }
3089
3090 assert(false && "Unhandled TargetInfo::IntType value");
Daniel Dunbarb3ac5432008-11-11 01:16:00 +00003091 return QualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003092}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003093
3094//===----------------------------------------------------------------------===//
3095// Type Predicates.
3096//===----------------------------------------------------------------------===//
3097
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003098/// isObjCNSObjectType - Return true if this is an NSObject object using
3099/// NSObject attribute on a c-style pointer type.
3100/// FIXME - Make it work directly on types.
3101///
3102bool ASTContext::isObjCNSObjectType(QualType Ty) const {
3103 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
3104 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003105 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003106 return true;
3107 }
3108 return false;
3109}
3110
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003111/// isObjCObjectPointerType - Returns true if type is an Objective-C pointer
3112/// to an object type. This includes "id" and "Class" (two 'special' pointers
3113/// to struct), Interface* (pointer to ObjCInterfaceType) and id<P> (qualified
3114/// ID type).
3115bool ASTContext::isObjCObjectPointerType(QualType Ty) const {
Steve Naroffd4617772009-02-23 18:36:16 +00003116 if (Ty->isObjCQualifiedIdType())
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003117 return true;
3118
Steve Naroff6ae98502008-10-21 18:24:04 +00003119 // Blocks are objects.
3120 if (Ty->isBlockPointerType())
3121 return true;
3122
3123 // All other object types are pointers.
Chris Lattner16ede0e2009-04-12 23:51:02 +00003124 const PointerType *PT = Ty->getAsPointerType();
3125 if (PT == 0)
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003126 return false;
3127
Chris Lattner16ede0e2009-04-12 23:51:02 +00003128 // If this a pointer to an interface (e.g. NSString*), it is ok.
3129 if (PT->getPointeeType()->isObjCInterfaceType() ||
3130 // If is has NSObject attribute, OK as well.
3131 isObjCNSObjectType(Ty))
3132 return true;
3133
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003134 // Check to see if this is 'id' or 'Class', both of which are typedefs for
3135 // pointer types. This looks for the typedef specifically, not for the
Chris Lattner16ede0e2009-04-12 23:51:02 +00003136 // underlying type. Iteratively strip off typedefs so that we can handle
3137 // typedefs of typedefs.
3138 while (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
3139 if (Ty.getUnqualifiedType() == getObjCIdType() ||
3140 Ty.getUnqualifiedType() == getObjCClassType())
3141 return true;
3142
3143 Ty = TDT->getDecl()->getUnderlyingType();
3144 }
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003145
Chris Lattner16ede0e2009-04-12 23:51:02 +00003146 return false;
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003147}
3148
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003149/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
3150/// garbage collection attribute.
3151///
3152QualType::GCAttrTypes ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
Chris Lattnerb7d25532009-02-18 22:53:11 +00003153 QualType::GCAttrTypes GCAttrs = QualType::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003154 if (getLangOptions().ObjC1 &&
3155 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00003156 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003157 // Default behavious under objective-c's gc is for objective-c pointers
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003158 // (or pointers to them) be treated as though they were declared
3159 // as __strong.
3160 if (GCAttrs == QualType::GCNone) {
3161 if (isObjCObjectPointerType(Ty))
3162 GCAttrs = QualType::Strong;
3163 else if (Ty->isPointerType())
3164 return getObjCGCAttrKind(Ty->getAsPointerType()->getPointeeType());
3165 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00003166 // Non-pointers have none gc'able attribute regardless of the attribute
3167 // set on them.
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003168 else if (!Ty->isPointerType() && !isObjCObjectPointerType(Ty))
Fariborz Jahanianc2112182009-04-11 00:00:54 +00003169 return QualType::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003170 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00003171 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003172}
3173
Chris Lattner6ac46a42008-04-07 06:51:04 +00003174//===----------------------------------------------------------------------===//
3175// Type Compatibility Testing
3176//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00003177
Chris Lattner6ac46a42008-04-07 06:51:04 +00003178/// areCompatVectorTypes - Return true if the two specified vector types are
3179/// compatible.
3180static bool areCompatVectorTypes(const VectorType *LHS,
3181 const VectorType *RHS) {
3182 assert(LHS->isCanonical() && RHS->isCanonical());
3183 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00003184 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00003185}
3186
Eli Friedman3d815e72008-08-22 00:56:42 +00003187/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00003188/// compatible for assignment from RHS to LHS. This handles validation of any
3189/// protocol qualifiers on the LHS or RHS.
3190///
Eli Friedman3d815e72008-08-22 00:56:42 +00003191bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
3192 const ObjCInterfaceType *RHS) {
Chris Lattner6ac46a42008-04-07 06:51:04 +00003193 // Verify that the base decls are compatible: the RHS must be a subclass of
3194 // the LHS.
3195 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
3196 return false;
3197
3198 // RHS must have a superset of the protocols in the LHS. If the LHS is not
3199 // protocol qualified at all, then we are good.
3200 if (!isa<ObjCQualifiedInterfaceType>(LHS))
3201 return true;
3202
3203 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
3204 // isn't a superset.
3205 if (!isa<ObjCQualifiedInterfaceType>(RHS))
3206 return true; // FIXME: should return false!
3207
3208 // Finally, we must have two protocol-qualified interfaces.
3209 const ObjCQualifiedInterfaceType *LHSP =cast<ObjCQualifiedInterfaceType>(LHS);
3210 const ObjCQualifiedInterfaceType *RHSP =cast<ObjCQualifiedInterfaceType>(RHS);
Chris Lattner6ac46a42008-04-07 06:51:04 +00003211
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003212 // All LHS protocols must have a presence on the RHS.
3213 assert(LHSP->qual_begin() != LHSP->qual_end() && "Empty LHS protocol list?");
Chris Lattner6ac46a42008-04-07 06:51:04 +00003214
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003215 for (ObjCQualifiedInterfaceType::qual_iterator LHSPI = LHSP->qual_begin(),
3216 LHSPE = LHSP->qual_end();
3217 LHSPI != LHSPE; LHSPI++) {
3218 bool RHSImplementsProtocol = false;
3219
3220 // If the RHS doesn't implement the protocol on the left, the types
3221 // are incompatible.
3222 for (ObjCQualifiedInterfaceType::qual_iterator RHSPI = RHSP->qual_begin(),
3223 RHSPE = RHSP->qual_end();
3224 !RHSImplementsProtocol && (RHSPI != RHSPE); RHSPI++) {
3225 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier()))
3226 RHSImplementsProtocol = true;
3227 }
3228 // FIXME: For better diagnostics, consider passing back the protocol name.
3229 if (!RHSImplementsProtocol)
3230 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00003231 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00003232 // The RHS implements all protocols listed on the LHS.
3233 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00003234}
3235
Steve Naroff389bf462009-02-12 17:52:19 +00003236bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
3237 // get the "pointed to" types
3238 const PointerType *LHSPT = LHS->getAsPointerType();
3239 const PointerType *RHSPT = RHS->getAsPointerType();
3240
3241 if (!LHSPT || !RHSPT)
3242 return false;
3243
3244 QualType lhptee = LHSPT->getPointeeType();
3245 QualType rhptee = RHSPT->getPointeeType();
3246 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
3247 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
3248 // ID acts sort of like void* for ObjC interfaces
3249 if (LHSIface && isObjCIdStructType(rhptee))
3250 return true;
3251 if (RHSIface && isObjCIdStructType(lhptee))
3252 return true;
3253 if (!LHSIface || !RHSIface)
3254 return false;
3255 return canAssignObjCInterfaces(LHSIface, RHSIface) ||
3256 canAssignObjCInterfaces(RHSIface, LHSIface);
3257}
3258
Steve Naroffec0550f2007-10-15 20:41:53 +00003259/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
3260/// both shall have the identically qualified version of a compatible type.
3261/// C99 6.2.7p1: Two types have compatible types if their types are the
3262/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman3d815e72008-08-22 00:56:42 +00003263bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
3264 return !mergeTypes(LHS, RHS).isNull();
3265}
3266
3267QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
3268 const FunctionType *lbase = lhs->getAsFunctionType();
3269 const FunctionType *rbase = rhs->getAsFunctionType();
Douglas Gregor72564e72009-02-26 23:50:07 +00003270 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
3271 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00003272 bool allLTypes = true;
3273 bool allRTypes = true;
3274
3275 // Check return type
3276 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
3277 if (retType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00003278 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
3279 allLTypes = false;
3280 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
3281 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00003282
3283 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00003284 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
3285 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00003286 unsigned lproto_nargs = lproto->getNumArgs();
3287 unsigned rproto_nargs = rproto->getNumArgs();
3288
3289 // Compatible functions must have the same number of arguments
3290 if (lproto_nargs != rproto_nargs)
3291 return QualType();
3292
3293 // Variadic and non-variadic functions aren't compatible
3294 if (lproto->isVariadic() != rproto->isVariadic())
3295 return QualType();
3296
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003297 if (lproto->getTypeQuals() != rproto->getTypeQuals())
3298 return QualType();
3299
Eli Friedman3d815e72008-08-22 00:56:42 +00003300 // Check argument compatibility
3301 llvm::SmallVector<QualType, 10> types;
3302 for (unsigned i = 0; i < lproto_nargs; i++) {
3303 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
3304 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
3305 QualType argtype = mergeTypes(largtype, rargtype);
3306 if (argtype.isNull()) return QualType();
3307 types.push_back(argtype);
Chris Lattner61710852008-10-05 17:34:18 +00003308 if (getCanonicalType(argtype) != getCanonicalType(largtype))
3309 allLTypes = false;
3310 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
3311 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00003312 }
3313 if (allLTypes) return lhs;
3314 if (allRTypes) return rhs;
3315 return getFunctionType(retType, types.begin(), types.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003316 lproto->isVariadic(), lproto->getTypeQuals());
Eli Friedman3d815e72008-08-22 00:56:42 +00003317 }
3318
3319 if (lproto) allRTypes = false;
3320 if (rproto) allLTypes = false;
3321
Douglas Gregor72564e72009-02-26 23:50:07 +00003322 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00003323 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00003324 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00003325 if (proto->isVariadic()) return QualType();
3326 // Check that the types are compatible with the types that
3327 // would result from default argument promotions (C99 6.7.5.3p15).
3328 // The only types actually affected are promotable integer
3329 // types and floats, which would be passed as a different
3330 // type depending on whether the prototype is visible.
3331 unsigned proto_nargs = proto->getNumArgs();
3332 for (unsigned i = 0; i < proto_nargs; ++i) {
3333 QualType argTy = proto->getArgType(i);
3334 if (argTy->isPromotableIntegerType() ||
3335 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
3336 return QualType();
3337 }
3338
3339 if (allLTypes) return lhs;
3340 if (allRTypes) return rhs;
3341 return getFunctionType(retType, proto->arg_type_begin(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003342 proto->getNumArgs(), lproto->isVariadic(),
3343 lproto->getTypeQuals());
Eli Friedman3d815e72008-08-22 00:56:42 +00003344 }
3345
3346 if (allLTypes) return lhs;
3347 if (allRTypes) return rhs;
Douglas Gregor72564e72009-02-26 23:50:07 +00003348 return getFunctionNoProtoType(retType);
Eli Friedman3d815e72008-08-22 00:56:42 +00003349}
3350
3351QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
Bill Wendling43d69752007-12-03 07:33:35 +00003352 // C++ [expr]: If an expression initially has the type "reference to T", the
3353 // type is adjusted to "T" prior to any further analysis, the expression
3354 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003355 // expression is an lvalue unless the reference is an rvalue reference and
3356 // the expression is a function call (possibly inside parentheses).
Eli Friedman3d815e72008-08-22 00:56:42 +00003357 // FIXME: C++ shouldn't be going through here! The rules are different
3358 // enough that they should be handled separately.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003359 // FIXME: Merging of lvalue and rvalue references is incorrect. C++ *really*
3360 // shouldn't be going through here!
Eli Friedman3d815e72008-08-22 00:56:42 +00003361 if (const ReferenceType *RT = LHS->getAsReferenceType())
Chris Lattnerc4e40592008-04-07 04:07:56 +00003362 LHS = RT->getPointeeType();
Eli Friedman3d815e72008-08-22 00:56:42 +00003363 if (const ReferenceType *RT = RHS->getAsReferenceType())
Chris Lattnerc4e40592008-04-07 04:07:56 +00003364 RHS = RT->getPointeeType();
Chris Lattnerf3692dc2008-04-07 05:37:56 +00003365
Eli Friedman3d815e72008-08-22 00:56:42 +00003366 QualType LHSCan = getCanonicalType(LHS),
3367 RHSCan = getCanonicalType(RHS);
3368
3369 // If two types are identical, they are compatible.
3370 if (LHSCan == RHSCan)
3371 return LHS;
3372
3373 // If the qualifiers are different, the types aren't compatible
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003374 // Note that we handle extended qualifiers later, in the
3375 // case for ExtQualType.
3376 if (LHSCan.getCVRQualifiers() != RHSCan.getCVRQualifiers())
Eli Friedman3d815e72008-08-22 00:56:42 +00003377 return QualType();
3378
Eli Friedman852d63b2009-06-01 01:22:52 +00003379 Type::TypeClass LHSClass = LHSCan->getTypeClass();
3380 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00003381
Chris Lattner1adb8832008-01-14 05:45:46 +00003382 // We want to consider the two function types to be the same for these
3383 // comparisons, just force one to the other.
3384 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
3385 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00003386
Eli Friedman07d25872009-06-02 05:28:56 +00003387 // Strip off objc_gc attributes off the top level so they can be merged.
3388 // This is a complete mess, but the attribute itself doesn't make much sense.
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003389 if (RHSClass == Type::ExtQual) {
Eli Friedman07d25872009-06-02 05:28:56 +00003390 QualType::GCAttrTypes GCAttr = RHSCan.getObjCGCAttr();
3391 if (GCAttr != QualType::GCNone) {
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003392 QualType::GCAttrTypes GCLHSAttr = LHSCan.getObjCGCAttr();
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003393 // __weak attribute must appear on both declarations.
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003394 // __strong attribue is redundant if other decl is an objective-c
3395 // object pointer (or decorated with __strong attribute); otherwise
3396 // issue error.
3397 if ((GCAttr == QualType::Weak && GCLHSAttr != GCAttr) ||
3398 (GCAttr == QualType::Strong && GCLHSAttr != GCAttr &&
3399 LHSCan->isPointerType() && !isObjCObjectPointerType(LHSCan) &&
3400 !isObjCIdStructType(LHSCan->getAsPointerType()->getPointeeType())))
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003401 return QualType();
3402
Eli Friedman07d25872009-06-02 05:28:56 +00003403 RHS = QualType(cast<ExtQualType>(RHS.getDesugaredType())->getBaseType(),
3404 RHS.getCVRQualifiers());
3405 QualType Result = mergeTypes(LHS, RHS);
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003406 if (!Result.isNull()) {
3407 if (Result.getObjCGCAttr() == QualType::GCNone)
3408 Result = getObjCGCQualType(Result, GCAttr);
3409 else if (Result.getObjCGCAttr() != GCAttr)
3410 Result = QualType();
3411 }
Eli Friedman07d25872009-06-02 05:28:56 +00003412 return Result;
3413 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003414 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003415 if (LHSClass == Type::ExtQual) {
Eli Friedman07d25872009-06-02 05:28:56 +00003416 QualType::GCAttrTypes GCAttr = LHSCan.getObjCGCAttr();
3417 if (GCAttr != QualType::GCNone) {
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003418 QualType::GCAttrTypes GCRHSAttr = RHSCan.getObjCGCAttr();
3419 // __weak attribute must appear on both declarations. __strong
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003420 // __strong attribue is redundant if other decl is an objective-c
3421 // object pointer (or decorated with __strong attribute); otherwise
3422 // issue error.
3423 if ((GCAttr == QualType::Weak && GCRHSAttr != GCAttr) ||
3424 (GCAttr == QualType::Strong && GCRHSAttr != GCAttr &&
3425 RHSCan->isPointerType() && !isObjCObjectPointerType(RHSCan) &&
3426 !isObjCIdStructType(RHSCan->getAsPointerType()->getPointeeType())))
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003427 return QualType();
Fariborz Jahanian86f43852009-06-02 20:58:58 +00003428
Eli Friedman07d25872009-06-02 05:28:56 +00003429 LHS = QualType(cast<ExtQualType>(LHS.getDesugaredType())->getBaseType(),
3430 LHS.getCVRQualifiers());
3431 QualType Result = mergeTypes(LHS, RHS);
Fariborz Jahanian8df7a282009-06-02 18:32:00 +00003432 if (!Result.isNull()) {
3433 if (Result.getObjCGCAttr() == QualType::GCNone)
3434 Result = getObjCGCQualType(Result, GCAttr);
3435 else if (Result.getObjCGCAttr() != GCAttr)
3436 Result = QualType();
3437 }
Eli Friedman354e53d2009-06-02 07:45:37 +00003438 return Result;
Eli Friedman07d25872009-06-02 05:28:56 +00003439 }
Fariborz Jahanian585f7b22009-06-02 01:40:22 +00003440 }
3441
Eli Friedman4c721d32008-02-12 08:23:06 +00003442 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00003443 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
3444 LHSClass = Type::ConstantArray;
3445 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
3446 RHSClass = Type::ConstantArray;
Steve Naroffec0550f2007-10-15 20:41:53 +00003447
Nate Begeman213541a2008-04-18 23:10:10 +00003448 // Canonicalize ExtVector -> Vector.
3449 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
3450 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Chris Lattnera36a61f2008-04-07 05:43:21 +00003451
Chris Lattnerb0489812008-04-07 06:38:24 +00003452 // Consider qualified interfaces and interfaces the same.
3453 if (LHSClass == Type::ObjCQualifiedInterface) LHSClass = Type::ObjCInterface;
3454 if (RHSClass == Type::ObjCQualifiedInterface) RHSClass = Type::ObjCInterface;
Eli Friedman3d815e72008-08-22 00:56:42 +00003455
Chris Lattnera36a61f2008-04-07 05:43:21 +00003456 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00003457 if (LHSClass != RHSClass) {
Steve Naroff5fd659d2009-02-21 16:18:07 +00003458 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
3459 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
Fariborz Jahanianc8d2e772009-04-15 21:54:48 +00003460
Steve Naroffd824c9c2009-04-14 15:11:46 +00003461 // 'id' and 'Class' act sort of like void* for ObjC interfaces
3462 if (LHSIface && (isObjCIdStructType(RHS) || isObjCClassStructType(RHS)))
Steve Naroff5fd659d2009-02-21 16:18:07 +00003463 return LHS;
Steve Naroffd824c9c2009-04-14 15:11:46 +00003464 if (RHSIface && (isObjCIdStructType(LHS) || isObjCClassStructType(LHS)))
Steve Naroff5fd659d2009-02-21 16:18:07 +00003465 return RHS;
3466
Steve Naroffbc76dd02008-12-10 22:14:21 +00003467 // ID is compatible with all qualified id types.
3468 if (LHS->isObjCQualifiedIdType()) {
3469 if (const PointerType *PT = RHS->getAsPointerType()) {
3470 QualType pType = PT->getPointeeType();
Steve Naroffd824c9c2009-04-14 15:11:46 +00003471 if (isObjCIdStructType(pType) || isObjCClassStructType(pType))
Steve Naroffbc76dd02008-12-10 22:14:21 +00003472 return LHS;
3473 // FIXME: need to use ObjCQualifiedIdTypesAreCompatible(LHS, RHS, true).
3474 // Unfortunately, this API is part of Sema (which we don't have access
3475 // to. Need to refactor. The following check is insufficient, since we
3476 // need to make sure the class implements the protocol.
3477 if (pType->isObjCInterfaceType())
3478 return LHS;
3479 }
3480 }
3481 if (RHS->isObjCQualifiedIdType()) {
3482 if (const PointerType *PT = LHS->getAsPointerType()) {
3483 QualType pType = PT->getPointeeType();
Steve Naroffd824c9c2009-04-14 15:11:46 +00003484 if (isObjCIdStructType(pType) || isObjCClassStructType(pType))
Steve Naroffbc76dd02008-12-10 22:14:21 +00003485 return RHS;
3486 // FIXME: need to use ObjCQualifiedIdTypesAreCompatible(LHS, RHS, true).
3487 // Unfortunately, this API is part of Sema (which we don't have access
3488 // to. Need to refactor. The following check is insufficient, since we
3489 // need to make sure the class implements the protocol.
3490 if (pType->isObjCInterfaceType())
3491 return RHS;
3492 }
3493 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003494 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
3495 // a signed integer type, or an unsigned integer type.
Eli Friedman3d815e72008-08-22 00:56:42 +00003496 if (const EnumType* ETy = LHS->getAsEnumType()) {
3497 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
3498 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00003499 }
Eli Friedman3d815e72008-08-22 00:56:42 +00003500 if (const EnumType* ETy = RHS->getAsEnumType()) {
3501 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
3502 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00003503 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003504
Eli Friedman3d815e72008-08-22 00:56:42 +00003505 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00003506 }
Eli Friedman3d815e72008-08-22 00:56:42 +00003507
Steve Naroff4a746782008-01-09 22:43:08 +00003508 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00003509 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00003510#define TYPE(Class, Base)
3511#define ABSTRACT_TYPE(Class, Base)
3512#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3513#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3514#include "clang/AST/TypeNodes.def"
3515 assert(false && "Non-canonical and dependent types shouldn't get here");
3516 return QualType();
3517
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003518 case Type::LValueReference:
3519 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00003520 case Type::MemberPointer:
3521 assert(false && "C++ should never be in mergeTypes");
3522 return QualType();
3523
3524 case Type::IncompleteArray:
3525 case Type::VariableArray:
3526 case Type::FunctionProto:
3527 case Type::ExtVector:
3528 case Type::ObjCQualifiedInterface:
3529 assert(false && "Types are eliminated above");
3530 return QualType();
3531
Chris Lattner1adb8832008-01-14 05:45:46 +00003532 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00003533 {
3534 // Merge two pointer types, while trying to preserve typedef info
3535 QualType LHSPointee = LHS->getAsPointerType()->getPointeeType();
3536 QualType RHSPointee = RHS->getAsPointerType()->getPointeeType();
3537 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
3538 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00003539 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00003540 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00003541 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00003542 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00003543 return getPointerType(ResultType);
3544 }
Steve Naroffc0febd52008-12-10 17:49:55 +00003545 case Type::BlockPointer:
3546 {
3547 // Merge two block pointer types, while trying to preserve typedef info
3548 QualType LHSPointee = LHS->getAsBlockPointerType()->getPointeeType();
3549 QualType RHSPointee = RHS->getAsBlockPointerType()->getPointeeType();
3550 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
3551 if (ResultType.isNull()) return QualType();
3552 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
3553 return LHS;
3554 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
3555 return RHS;
3556 return getBlockPointerType(ResultType);
3557 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003558 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00003559 {
3560 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
3561 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
3562 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
3563 return QualType();
3564
3565 QualType LHSElem = getAsArrayType(LHS)->getElementType();
3566 QualType RHSElem = getAsArrayType(RHS)->getElementType();
3567 QualType ResultType = mergeTypes(LHSElem, RHSElem);
3568 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00003569 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3570 return LHS;
3571 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3572 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00003573 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
3574 ArrayType::ArraySizeModifier(), 0);
3575 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
3576 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00003577 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
3578 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00003579 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3580 return LHS;
3581 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3582 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00003583 if (LVAT) {
3584 // FIXME: This isn't correct! But tricky to implement because
3585 // the array's size has to be the size of LHS, but the type
3586 // has to be different.
3587 return LHS;
3588 }
3589 if (RVAT) {
3590 // FIXME: This isn't correct! But tricky to implement because
3591 // the array's size has to be the size of RHS, but the type
3592 // has to be different.
3593 return RHS;
3594 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00003595 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
3596 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003597 return getIncompleteArrayType(ResultType,
3598 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00003599 }
Chris Lattner1adb8832008-01-14 05:45:46 +00003600 case Type::FunctionNoProto:
Eli Friedman3d815e72008-08-22 00:56:42 +00003601 return mergeFunctionTypes(LHS, RHS);
Douglas Gregor72564e72009-02-26 23:50:07 +00003602 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00003603 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00003604 // FIXME: Why are these compatible?
Steve Naroff389bf462009-02-12 17:52:19 +00003605 if (isObjCIdStructType(LHS) && isObjCClassStructType(RHS)) return LHS;
3606 if (isObjCClassStructType(LHS) && isObjCIdStructType(RHS)) return LHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00003607 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00003608 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00003609 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00003610 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00003611 case Type::Complex:
3612 // Distinct complex types are incompatible.
3613 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00003614 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003615 // FIXME: The merged type should be an ExtVector!
Eli Friedman3d815e72008-08-22 00:56:42 +00003616 if (areCompatVectorTypes(LHS->getAsVectorType(), RHS->getAsVectorType()))
3617 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00003618 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00003619 case Type::ObjCInterface: {
Steve Naroff5fd659d2009-02-21 16:18:07 +00003620 // Check if the interfaces are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003621 // FIXME: This should be type compatibility, e.g. whether
3622 // "LHS x; RHS x;" at global scope is legal.
Steve Naroff5fd659d2009-02-21 16:18:07 +00003623 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
3624 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
3625 if (LHSIface && RHSIface &&
3626 canAssignObjCInterfaces(LHSIface, RHSIface))
3627 return LHS;
3628
Eli Friedman3d815e72008-08-22 00:56:42 +00003629 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00003630 }
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003631 case Type::ObjCObjectPointer:
3632 // FIXME: finish
Steve Naroffbc76dd02008-12-10 22:14:21 +00003633 // Distinct qualified id's are not compatible.
3634 return QualType();
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003635 case Type::FixedWidthInt:
3636 // Distinct fixed-width integers are not compatible.
3637 return QualType();
Eli Friedman5a61f0e2009-02-27 23:04:43 +00003638 case Type::ExtQual:
3639 // FIXME: ExtQual types can be compatible even if they're not
3640 // identical!
3641 return QualType();
3642 // First attempt at an implementation, but I'm not really sure it's
3643 // right...
3644#if 0
3645 ExtQualType* LQual = cast<ExtQualType>(LHSCan);
3646 ExtQualType* RQual = cast<ExtQualType>(RHSCan);
3647 if (LQual->getAddressSpace() != RQual->getAddressSpace() ||
3648 LQual->getObjCGCAttr() != RQual->getObjCGCAttr())
3649 return QualType();
3650 QualType LHSBase, RHSBase, ResultType, ResCanUnqual;
3651 LHSBase = QualType(LQual->getBaseType(), 0);
3652 RHSBase = QualType(RQual->getBaseType(), 0);
3653 ResultType = mergeTypes(LHSBase, RHSBase);
3654 if (ResultType.isNull()) return QualType();
3655 ResCanUnqual = getCanonicalType(ResultType).getUnqualifiedType();
3656 if (LHSCan.getUnqualifiedType() == ResCanUnqual)
3657 return LHS;
3658 if (RHSCan.getUnqualifiedType() == ResCanUnqual)
3659 return RHS;
3660 ResultType = getAddrSpaceQualType(ResultType, LQual->getAddressSpace());
3661 ResultType = getObjCGCQualType(ResultType, LQual->getObjCGCAttr());
3662 ResultType.setCVRQualifiers(LHSCan.getCVRQualifiers());
3663 return ResultType;
3664#endif
Douglas Gregor7532dc62009-03-30 22:58:21 +00003665
3666 case Type::TemplateSpecialization:
3667 assert(false && "Dependent types have no size");
3668 break;
Steve Naroffec0550f2007-10-15 20:41:53 +00003669 }
Douglas Gregor72564e72009-02-26 23:50:07 +00003670
3671 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00003672}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00003673
Chris Lattner5426bf62008-04-07 07:01:58 +00003674//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00003675// Integer Predicates
3676//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00003677
Eli Friedmanad74a752008-06-28 06:23:08 +00003678unsigned ASTContext::getIntWidth(QualType T) {
3679 if (T == BoolTy)
3680 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00003681 if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T)) {
3682 return FWIT->getWidth();
3683 }
3684 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00003685 return (unsigned)getTypeSize(T);
3686}
3687
3688QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
3689 assert(T->isSignedIntegerType() && "Unexpected type");
3690 if (const EnumType* ETy = T->getAsEnumType())
3691 T = ETy->getDecl()->getIntegerType();
3692 const BuiltinType* BTy = T->getAsBuiltinType();
3693 assert (BTy && "Unexpected signed integer type");
3694 switch (BTy->getKind()) {
3695 case BuiltinType::Char_S:
3696 case BuiltinType::SChar:
3697 return UnsignedCharTy;
3698 case BuiltinType::Short:
3699 return UnsignedShortTy;
3700 case BuiltinType::Int:
3701 return UnsignedIntTy;
3702 case BuiltinType::Long:
3703 return UnsignedLongTy;
3704 case BuiltinType::LongLong:
3705 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00003706 case BuiltinType::Int128:
3707 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00003708 default:
3709 assert(0 && "Unexpected signed integer type");
3710 return QualType();
3711 }
3712}
3713
Douglas Gregor2cf26342009-04-09 22:27:44 +00003714ExternalASTSource::~ExternalASTSource() { }
3715
3716void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00003717
3718
3719//===----------------------------------------------------------------------===//
3720// Builtin Type Computation
3721//===----------------------------------------------------------------------===//
3722
3723/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
3724/// pointer over the consumed characters. This returns the resultant type.
3725static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
3726 ASTContext::GetBuiltinTypeError &Error,
3727 bool AllowTypeModifiers = true) {
3728 // Modifiers.
3729 int HowLong = 0;
3730 bool Signed = false, Unsigned = false;
3731
3732 // Read the modifiers first.
3733 bool Done = false;
3734 while (!Done) {
3735 switch (*Str++) {
3736 default: Done = true; --Str; break;
3737 case 'S':
3738 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
3739 assert(!Signed && "Can't use 'S' modifier multiple times!");
3740 Signed = true;
3741 break;
3742 case 'U':
3743 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
3744 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
3745 Unsigned = true;
3746 break;
3747 case 'L':
3748 assert(HowLong <= 2 && "Can't have LLLL modifier");
3749 ++HowLong;
3750 break;
3751 }
3752 }
3753
3754 QualType Type;
3755
3756 // Read the base type.
3757 switch (*Str++) {
3758 default: assert(0 && "Unknown builtin type letter!");
3759 case 'v':
3760 assert(HowLong == 0 && !Signed && !Unsigned &&
3761 "Bad modifiers used with 'v'!");
3762 Type = Context.VoidTy;
3763 break;
3764 case 'f':
3765 assert(HowLong == 0 && !Signed && !Unsigned &&
3766 "Bad modifiers used with 'f'!");
3767 Type = Context.FloatTy;
3768 break;
3769 case 'd':
3770 assert(HowLong < 2 && !Signed && !Unsigned &&
3771 "Bad modifiers used with 'd'!");
3772 if (HowLong)
3773 Type = Context.LongDoubleTy;
3774 else
3775 Type = Context.DoubleTy;
3776 break;
3777 case 's':
3778 assert(HowLong == 0 && "Bad modifiers used with 's'!");
3779 if (Unsigned)
3780 Type = Context.UnsignedShortTy;
3781 else
3782 Type = Context.ShortTy;
3783 break;
3784 case 'i':
3785 if (HowLong == 3)
3786 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
3787 else if (HowLong == 2)
3788 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
3789 else if (HowLong == 1)
3790 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
3791 else
3792 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
3793 break;
3794 case 'c':
3795 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
3796 if (Signed)
3797 Type = Context.SignedCharTy;
3798 else if (Unsigned)
3799 Type = Context.UnsignedCharTy;
3800 else
3801 Type = Context.CharTy;
3802 break;
3803 case 'b': // boolean
3804 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
3805 Type = Context.BoolTy;
3806 break;
3807 case 'z': // size_t.
3808 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
3809 Type = Context.getSizeType();
3810 break;
3811 case 'F':
3812 Type = Context.getCFConstantStringType();
3813 break;
3814 case 'a':
3815 Type = Context.getBuiltinVaListType();
3816 assert(!Type.isNull() && "builtin va list type not initialized!");
3817 break;
3818 case 'A':
3819 // This is a "reference" to a va_list; however, what exactly
3820 // this means depends on how va_list is defined. There are two
3821 // different kinds of va_list: ones passed by value, and ones
3822 // passed by reference. An example of a by-value va_list is
3823 // x86, where va_list is a char*. An example of by-ref va_list
3824 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
3825 // we want this argument to be a char*&; for x86-64, we want
3826 // it to be a __va_list_tag*.
3827 Type = Context.getBuiltinVaListType();
3828 assert(!Type.isNull() && "builtin va list type not initialized!");
3829 if (Type->isArrayType()) {
3830 Type = Context.getArrayDecayedType(Type);
3831 } else {
3832 Type = Context.getLValueReferenceType(Type);
3833 }
3834 break;
3835 case 'V': {
3836 char *End;
3837
3838 unsigned NumElements = strtoul(Str, &End, 10);
3839 assert(End != Str && "Missing vector size");
3840
3841 Str = End;
3842
3843 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
3844 Type = Context.getVectorType(ElementType, NumElements);
3845 break;
3846 }
3847 case 'P': {
Douglas Gregorc29f77b2009-07-07 16:35:42 +00003848 Type = Context.getFILEType();
3849 if (Type.isNull()) {
Chris Lattner86df27b2009-06-14 00:45:47 +00003850 Error = ASTContext::GE_Missing_FILE;
3851 return QualType();
Douglas Gregorc29f77b2009-07-07 16:35:42 +00003852 } else {
3853 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00003854 }
3855 }
3856 }
3857
3858 if (!AllowTypeModifiers)
3859 return Type;
3860
3861 Done = false;
3862 while (!Done) {
3863 switch (*Str++) {
3864 default: Done = true; --Str; break;
3865 case '*':
3866 Type = Context.getPointerType(Type);
3867 break;
3868 case '&':
3869 Type = Context.getLValueReferenceType(Type);
3870 break;
3871 // FIXME: There's no way to have a built-in with an rvalue ref arg.
3872 case 'C':
3873 Type = Type.getQualifiedType(QualType::Const);
3874 break;
3875 }
3876 }
3877
3878 return Type;
3879}
3880
3881/// GetBuiltinType - Return the type for the specified builtin.
3882QualType ASTContext::GetBuiltinType(unsigned id,
3883 GetBuiltinTypeError &Error) {
3884 const char *TypeStr = BuiltinInfo.GetTypeString(id);
3885
3886 llvm::SmallVector<QualType, 8> ArgTypes;
3887
3888 Error = GE_None;
3889 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
3890 if (Error != GE_None)
3891 return QualType();
3892 while (TypeStr[0] && TypeStr[0] != '.') {
3893 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
3894 if (Error != GE_None)
3895 return QualType();
3896
3897 // Do array -> pointer decay. The builtin should use the decayed type.
3898 if (Ty->isArrayType())
3899 Ty = getArrayDecayedType(Ty);
3900
3901 ArgTypes.push_back(Ty);
3902 }
3903
3904 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
3905 "'.' should only occur at end of builtin type list!");
3906
3907 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
3908 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
3909 return getFunctionNoProtoType(ResType);
3910 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
3911 TypeStr[0] == '.', 0);
3912}