blob: 85ac734a45c073b04435b41bd8dae7d39ded82f3 [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"
Chandler Carruth55fc8732012-12-04 09:13:33 +000015#include "CXXABI.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000016#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/Attr.h"
Ken Dyckbdc601b2009-12-22 14:23:30 +000018#include "clang/AST/CharUnits.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000019#include "clang/AST/Comment.h"
Dmitri Gribenkoaa580812012-08-09 00:03:17 +000020#include "clang/AST/CommentCommandTraits.h"
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +000021#include "clang/AST/DeclCXX.h"
Steve Naroff980e5082007-10-01 19:00:59 +000022#include "clang/AST/DeclObjC.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000023#include "clang/AST/DeclTemplate.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000024#include "clang/AST/Expr.h"
John McCallea1471e2010-05-20 01:18:31 +000025#include "clang/AST/ExprCXX.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000026#include "clang/AST/ExternalASTSource.h"
Peter Collingbourne14110472011-01-13 18:57:25 +000027#include "clang/AST/Mangle.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000028#include "clang/AST/RecordLayout.h"
Reid Klecknercff15122013-06-17 12:56:08 +000029#include "clang/AST/RecursiveASTVisitor.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000030#include "clang/AST/TypeLoc.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000031#include "clang/Basic/Builtins.h"
Chris Lattnera9376d42009-03-28 03:45:20 +000032#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000033#include "clang/Basic/TargetInfo.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000034#include "llvm/ADT/SmallString.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000035#include "llvm/ADT/StringExtras.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000036#include "llvm/Support/Capacity.h"
Nate Begeman6fe7c8a2009-01-18 06:42:49 +000037#include "llvm/Support/MathExtras.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000038#include "llvm/Support/raw_ostream.h"
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +000039#include <map>
Anders Carlsson29445a02009-07-18 21:19:52 +000040
Reid Spencer5f016e22007-07-11 17:01:13 +000041using namespace clang;
42
Douglas Gregor18274032010-07-03 00:47:00 +000043unsigned ASTContext::NumImplicitDefaultConstructors;
44unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregor22584312010-07-02 23:41:54 +000045unsigned ASTContext::NumImplicitCopyConstructors;
46unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Sean Huntffe37fd2011-05-25 20:50:04 +000047unsigned ASTContext::NumImplicitMoveConstructors;
48unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregora376d102010-07-02 21:50:04 +000049unsigned ASTContext::NumImplicitCopyAssignmentOperators;
50unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Huntffe37fd2011-05-25 20:50:04 +000051unsigned ASTContext::NumImplicitMoveAssignmentOperators;
52unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor4923aa22010-07-02 20:37:36 +000053unsigned ASTContext::NumImplicitDestructors;
54unsigned ASTContext::NumImplicitDestructorsDeclared;
55
Reid Spencer5f016e22007-07-11 17:01:13 +000056enum FloatingRank {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +000057 HalfRank, FloatRank, DoubleRank, LongDoubleRank
Reid Spencer5f016e22007-07-11 17:01:13 +000058};
59
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +000060RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +000061 if (!CommentsLoaded && ExternalSource) {
62 ExternalSource->ReadComments();
63 CommentsLoaded = true;
64 }
65
66 assert(D);
67
Dmitri Gribenkoc3fee352012-06-28 16:19:39 +000068 // User can not attach documentation to implicit declarations.
69 if (D->isImplicit())
70 return NULL;
71
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +000072 // User can not attach documentation to implicit instantiations.
73 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
74 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
75 return NULL;
76 }
77
Dmitri Gribenkodce750b2012-08-20 22:36:31 +000078 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
79 if (VD->isStaticDataMember() &&
80 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
81 return NULL;
82 }
83
84 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
85 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
86 return NULL;
87 }
88
Dmitri Gribenkod1e5c0d2013-01-27 21:18:39 +000089 if (const ClassTemplateSpecializationDecl *CTSD =
90 dyn_cast<ClassTemplateSpecializationDecl>(D)) {
91 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
92 if (TSK == TSK_ImplicitInstantiation ||
93 TSK == TSK_Undeclared)
94 return NULL;
95 }
96
Dmitri Gribenkodce750b2012-08-20 22:36:31 +000097 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
98 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
99 return NULL;
100 }
Fariborz Jahanian099ecfb2013-04-17 21:05:20 +0000101 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
102 // When tag declaration (but not definition!) is part of the
103 // decl-specifier-seq of some other declaration, it doesn't get comment
104 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
105 return NULL;
106 }
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000107 // TODO: handle comments for function parameters properly.
108 if (isa<ParmVarDecl>(D))
109 return NULL;
110
Dmitri Gribenko96b09862012-07-31 22:37:06 +0000111 // TODO: we could look up template parameter documentation in the template
112 // documentation.
113 if (isa<TemplateTypeParmDecl>(D) ||
114 isa<NonTypeTemplateParmDecl>(D) ||
115 isa<TemplateTemplateParmDecl>(D))
116 return NULL;
117
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000118 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000119
120 // If there are no comments anywhere, we won't find anything.
121 if (RawComments.empty())
122 return NULL;
123
Dmitri Gribenkoabd56c82012-07-13 01:06:46 +0000124 // Find declaration location.
125 // For Objective-C declarations we generally don't expect to have multiple
126 // declarators, thus use declaration starting location as the "declaration
127 // location".
128 // For all other declarations multiple declarators are used quite frequently,
129 // so we use the location of the identifier as the "declaration location".
130 SourceLocation DeclLoc;
131 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko96b09862012-07-31 22:37:06 +0000132 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +0000133 isa<RedeclarableTemplateDecl>(D) ||
134 isa<ClassTemplateSpecializationDecl>(D))
Dmitri Gribenkoabd56c82012-07-13 01:06:46 +0000135 DeclLoc = D->getLocStart();
Fariborz Jahanianceaa1ec2013-07-24 22:58:51 +0000136 else {
Dmitri Gribenkoabd56c82012-07-13 01:06:46 +0000137 DeclLoc = D->getLocation();
Fariborz Jahanianceaa1ec2013-07-24 22:58:51 +0000138 // If location of the typedef name is in a macro, it is because being
139 // declared via a macro. Try using declaration's starting location
140 // as the "declaration location".
141 if (DeclLoc.isMacroID() && isa<TypedefDecl>(D))
142 DeclLoc = D->getLocStart();
143 }
Dmitri Gribenkoabd56c82012-07-13 01:06:46 +0000144
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000145 // If the declaration doesn't map directly to a location in a file, we
146 // can't find the comment.
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000147 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
148 return NULL;
149
150 // Find the comment that occurs just after this declaration.
Dmitri Gribenkoa444f182012-07-17 22:01:09 +0000151 ArrayRef<RawComment *>::iterator Comment;
152 {
153 // When searching for comments during parsing, the comment we are looking
154 // for is usually among the last two comments we parsed -- check them
155 // first.
Dmitri Gribenko6fd7d302013-04-10 15:35:17 +0000156 RawComment CommentAtDeclLoc(
157 SourceMgr, SourceRange(DeclLoc), false,
158 LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenkoa444f182012-07-17 22:01:09 +0000159 BeforeThanCompare<RawComment> Compare(SourceMgr);
160 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
161 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
162 if (!Found && RawComments.size() >= 2) {
163 MaybeBeforeDecl--;
164 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
165 }
166
167 if (Found) {
168 Comment = MaybeBeforeDecl + 1;
169 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
170 &CommentAtDeclLoc, Compare));
171 } else {
172 // Slow path.
173 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
174 &CommentAtDeclLoc, Compare);
175 }
176 }
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000177
178 // Decompose the location for the declaration and find the beginning of the
179 // file buffer.
180 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
181
182 // First check whether we have a trailing comment.
183 if (Comment != RawComments.end() &&
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000184 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
Fariborz Jahanian8c238be2013-08-06 23:29:00 +0000185 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
Fariborz Jahanian15c8e562013-08-07 16:40:29 +0000186 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000187 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000188 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000189 // Check that Doxygen trailing comment comes after the declaration, starts
190 // on the same line and in the same file as the declaration.
191 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
192 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
193 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
194 CommentBeginDecomp.second)) {
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000195 return *Comment;
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000196 }
197 }
198
199 // The comment just after the declaration was not a trailing comment.
200 // Let's look at the previous comment.
201 if (Comment == RawComments.begin())
202 return NULL;
203 --Comment;
204
205 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000206 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000207 return NULL;
208
209 // Decompose the end of the comment.
210 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000211 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000212
213 // If the comment and the declaration aren't in the same file, then they
214 // aren't related.
215 if (DeclLocDecomp.first != CommentEndDecomp.first)
216 return NULL;
217
218 // Get the corresponding buffer.
219 bool Invalid = false;
220 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
221 &Invalid).data();
222 if (Invalid)
223 return NULL;
224
225 // Extract text between the comment and declaration.
226 StringRef Text(Buffer + CommentEndDecomp.second,
227 DeclLocDecomp.second - CommentEndDecomp.second);
228
Dmitri Gribenko8bdb58a2012-06-27 23:43:37 +0000229 // There should be no other declarations or preprocessor directives between
230 // comment and declaration.
Argyrios Kyrtzidisdc663262013-07-26 18:38:12 +0000231 if (Text.find_first_of(";{}#@") != StringRef::npos)
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000232 return NULL;
233
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000234 return *Comment;
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000235}
236
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000237namespace {
238/// If we have a 'templated' declaration for a template, adjust 'D' to
239/// refer to the actual template.
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000240/// If we have an implicit instantiation, adjust 'D' to refer to template.
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000241const Decl *adjustDeclToTemplate(const Decl *D) {
Douglas Gregorcd81df22012-08-13 16:37:30 +0000242 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000243 // Is this function declaration part of a function template?
Douglas Gregorcd81df22012-08-13 16:37:30 +0000244 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000245 return FTD;
246
247 // Nothing to do if function is not an implicit instantiation.
248 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
249 return D;
250
251 // Function is an implicit instantiation of a function template?
252 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
253 return FTD;
254
255 // Function is instantiated from a member definition of a class template?
256 if (const FunctionDecl *MemberDecl =
257 FD->getInstantiatedFromMemberFunction())
258 return MemberDecl;
259
260 return D;
Douglas Gregorcd81df22012-08-13 16:37:30 +0000261 }
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000262 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
263 // Static data member is instantiated from a member definition of a class
264 // template?
265 if (VD->isStaticDataMember())
266 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
267 return MemberDecl;
268
269 return D;
270 }
271 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
272 // Is this class declaration part of a class template?
273 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
274 return CTD;
275
276 // Class is an implicit instantiation of a class template or partial
277 // specialization?
278 if (const ClassTemplateSpecializationDecl *CTSD =
279 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
280 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
281 return D;
282 llvm::PointerUnion<ClassTemplateDecl *,
283 ClassTemplatePartialSpecializationDecl *>
284 PU = CTSD->getSpecializedTemplateOrPartial();
285 return PU.is<ClassTemplateDecl*>() ?
286 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
287 static_cast<const Decl*>(
288 PU.get<ClassTemplatePartialSpecializationDecl *>());
289 }
290
291 // Class is instantiated from a member definition of a class template?
292 if (const MemberSpecializationInfo *Info =
293 CRD->getMemberSpecializationInfo())
294 return Info->getInstantiatedFrom();
295
296 return D;
297 }
298 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
299 // Enum is instantiated from a member definition of a class template?
300 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
301 return MemberDecl;
302
303 return D;
304 }
305 // FIXME: Adjust alias templates?
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000306 return D;
307}
308} // unnamed namespace
309
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000310const RawComment *ASTContext::getRawCommentForAnyRedecl(
311 const Decl *D,
312 const Decl **OriginalDecl) const {
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000313 D = adjustDeclToTemplate(D);
Douglas Gregorcd81df22012-08-13 16:37:30 +0000314
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000315 // Check whether we have cached a comment for this declaration already.
316 {
317 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
318 RedeclComments.find(D);
319 if (Pos != RedeclComments.end()) {
320 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000321 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
322 if (OriginalDecl)
323 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000324 return Raw.getRaw();
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000325 }
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000326 }
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000327 }
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000328
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000329 // Search for comments attached to declarations in the redeclaration chain.
330 const RawComment *RC = NULL;
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000331 const Decl *OriginalDeclForRC = NULL;
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000332 for (Decl::redecl_iterator I = D->redecls_begin(),
333 E = D->redecls_end();
334 I != E; ++I) {
335 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
336 RedeclComments.find(*I);
337 if (Pos != RedeclComments.end()) {
338 const RawCommentAndCacheFlags &Raw = Pos->second;
339 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
340 RC = Raw.getRaw();
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000341 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000342 break;
343 }
344 } else {
345 RC = getRawCommentForDeclNoCache(*I);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000346 OriginalDeclForRC = *I;
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000347 RawCommentAndCacheFlags Raw;
348 if (RC) {
349 Raw.setRaw(RC);
350 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
351 } else
352 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000353 Raw.setOriginalDecl(*I);
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000354 RedeclComments[*I] = Raw;
355 if (RC)
356 break;
357 }
358 }
359
Dmitri Gribenko8376f592012-06-28 16:25:36 +0000360 // If we found a comment, it should be a documentation comment.
361 assert(!RC || RC->isDocumentation());
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000362
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000363 if (OriginalDecl)
364 *OriginalDecl = OriginalDeclForRC;
365
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000366 // Update cache for every declaration in the redeclaration chain.
367 RawCommentAndCacheFlags Raw;
368 Raw.setRaw(RC);
369 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000370 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000371
372 for (Decl::redecl_iterator I = D->redecls_begin(),
373 E = D->redecls_end();
374 I != E; ++I) {
375 RawCommentAndCacheFlags &R = RedeclComments[*I];
376 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
377 R = Raw;
378 }
379
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000380 return RC;
381}
382
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000383static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
384 SmallVectorImpl<const NamedDecl *> &Redeclared) {
385 const DeclContext *DC = ObjCMethod->getDeclContext();
386 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
387 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
388 if (!ID)
389 return;
390 // Add redeclared method here.
Douglas Gregord3297242013-01-16 23:00:23 +0000391 for (ObjCInterfaceDecl::known_extensions_iterator
392 Ext = ID->known_extensions_begin(),
393 ExtEnd = ID->known_extensions_end();
394 Ext != ExtEnd; ++Ext) {
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000395 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregord3297242013-01-16 23:00:23 +0000396 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000397 ObjCMethod->isInstanceMethod()))
398 Redeclared.push_back(RedeclaredMethod);
399 }
400 }
401}
402
Fariborz Jahanian749ace62012-10-11 23:52:50 +0000403comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
404 const Decl *D) const {
405 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
406 ThisDeclInfo->CommentDecl = D;
407 ThisDeclInfo->IsFilled = false;
408 ThisDeclInfo->fill();
409 ThisDeclInfo->CommentDecl = FC->getDecl();
410 comments::FullComment *CFC =
411 new (*this) comments::FullComment(FC->getBlocks(),
412 ThisDeclInfo);
413 return CFC;
414
415}
416
Richard Smith0a74a4c2013-05-21 05:24:00 +0000417comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
418 const RawComment *RC = getRawCommentForDeclNoCache(D);
419 return RC ? RC->parse(*this, 0, D) : 0;
420}
421
Dmitri Gribenko19523542012-09-29 11:40:46 +0000422comments::FullComment *ASTContext::getCommentForDecl(
423 const Decl *D,
424 const Preprocessor *PP) const {
Fariborz Jahanianfbff0c42013-05-13 17:27:00 +0000425 if (D->isInvalidDecl())
426 return NULL;
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000427 D = adjustDeclToTemplate(D);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000428
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000429 const Decl *Canonical = D->getCanonicalDecl();
430 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
431 ParsedComments.find(Canonical);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000432
433 if (Pos != ParsedComments.end()) {
Fariborz Jahanian749ace62012-10-11 23:52:50 +0000434 if (Canonical != D) {
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000435 comments::FullComment *FC = Pos->second;
Fariborz Jahanian749ace62012-10-11 23:52:50 +0000436 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000437 return CFC;
438 }
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000439 return Pos->second;
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000440 }
441
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000442 const Decl *OriginalDecl;
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000443
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000444 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000445 if (!RC) {
446 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko1e905da2012-11-03 14:24:57 +0000447 SmallVector<const NamedDecl*, 8> Overridden;
Fariborz Jahanianc328d9c2013-01-12 00:28:34 +0000448 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian23799e32013-01-25 23:08:39 +0000449 if (OMD && OMD->isPropertyAccessor())
450 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
451 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
452 return cloneFullComment(FC, D);
Fariborz Jahanianc328d9c2013-01-12 00:28:34 +0000453 if (OMD)
Dmitri Gribenko1e905da2012-11-03 14:24:57 +0000454 addRedeclaredMethods(OMD, Overridden);
455 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian23799e32013-01-25 23:08:39 +0000456 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
457 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
458 return cloneFullComment(FC, D);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000459 }
Fariborz Jahanian4857fdc2013-05-02 15:44:16 +0000460 else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenkod1e5c0d2013-01-27 21:18:39 +0000461 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian23799e32013-01-25 23:08:39 +0000462 // does not have one of its own.
Fariborz Jahanian41170b52013-01-25 22:48:32 +0000463 QualType QT = TD->getUnderlyingType();
Dmitri Gribenkod1e5c0d2013-01-27 21:18:39 +0000464 if (const TagType *TT = QT->getAs<TagType>())
465 if (const Decl *TD = TT->getDecl())
466 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian23799e32013-01-25 23:08:39 +0000467 return cloneFullComment(FC, D);
Fariborz Jahanian41170b52013-01-25 22:48:32 +0000468 }
Fariborz Jahanian622bb4a2013-04-26 20:55:38 +0000469 else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
470 while (IC->getSuperClass()) {
471 IC = IC->getSuperClass();
472 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
473 return cloneFullComment(FC, D);
474 }
475 }
476 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
477 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
478 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
479 return cloneFullComment(FC, D);
480 }
481 else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
482 if (!(RD = RD->getDefinition()))
483 return NULL;
484 // Check non-virtual bases.
485 for (CXXRecordDecl::base_class_const_iterator I =
486 RD->bases_begin(), E = RD->bases_end(); I != E; ++I) {
Fariborz Jahanian91efca02013-04-26 23:34:36 +0000487 if (I->isVirtual() || (I->getAccessSpecifier() != AS_public))
Fariborz Jahanian622bb4a2013-04-26 20:55:38 +0000488 continue;
489 QualType Ty = I->getType();
490 if (Ty.isNull())
491 continue;
492 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
493 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
494 continue;
495
496 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
497 return cloneFullComment(FC, D);
498 }
499 }
500 // Check virtual bases.
501 for (CXXRecordDecl::base_class_const_iterator I =
502 RD->vbases_begin(), E = RD->vbases_end(); I != E; ++I) {
Fariborz Jahanian91efca02013-04-26 23:34:36 +0000503 if (I->getAccessSpecifier() != AS_public)
504 continue;
Fariborz Jahanian622bb4a2013-04-26 20:55:38 +0000505 QualType Ty = I->getType();
506 if (Ty.isNull())
507 continue;
508 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
509 if (!(VirtualBase= VirtualBase->getDefinition()))
510 continue;
511 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
512 return cloneFullComment(FC, D);
513 }
514 }
515 }
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000516 return NULL;
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000517 }
518
Dmitri Gribenko4b41c652012-08-22 18:12:19 +0000519 // If the RawComment was attached to other redeclaration of this Decl, we
520 // should parse the comment in context of that other Decl. This is important
521 // because comments can contain references to parameter names which can be
522 // different across redeclarations.
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000523 if (D != OriginalDecl)
Dmitri Gribenko19523542012-09-29 11:40:46 +0000524 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000525
Dmitri Gribenko19523542012-09-29 11:40:46 +0000526 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000527 ParsedComments[Canonical] = FC;
528 return FC;
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000529}
530
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000531void
532ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
533 TemplateTemplateParmDecl *Parm) {
534 ID.AddInteger(Parm->getDepth());
535 ID.AddInteger(Parm->getPosition());
Douglas Gregor61c4d282011-01-05 15:48:55 +0000536 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000537
538 TemplateParameterList *Params = Parm->getTemplateParameters();
539 ID.AddInteger(Params->size());
540 for (TemplateParameterList::const_iterator P = Params->begin(),
541 PEnd = Params->end();
542 P != PEnd; ++P) {
543 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
544 ID.AddInteger(0);
545 ID.AddBoolean(TTP->isParameterPack());
546 continue;
547 }
548
549 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
550 ID.AddInteger(1);
Douglas Gregor61c4d282011-01-05 15:48:55 +0000551 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman9e9c4542012-03-07 01:09:33 +0000552 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000553 if (NTTP->isExpandedParameterPack()) {
554 ID.AddBoolean(true);
555 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman9e9c4542012-03-07 01:09:33 +0000556 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
557 QualType T = NTTP->getExpansionType(I);
558 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
559 }
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000560 } else
561 ID.AddBoolean(false);
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000562 continue;
563 }
564
565 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
566 ID.AddInteger(2);
567 Profile(ID, TTP);
568 }
569}
570
571TemplateTemplateParmDecl *
572ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad4ba2a172011-01-12 09:06:06 +0000573 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000574 // Check if we already have a canonical template template parameter.
575 llvm::FoldingSetNodeID ID;
576 CanonicalTemplateTemplateParm::Profile(ID, TTP);
577 void *InsertPos = 0;
578 CanonicalTemplateTemplateParm *Canonical
579 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
580 if (Canonical)
581 return Canonical->getParam();
582
583 // Build a canonical template parameter list.
584 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000585 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000586 CanonParams.reserve(Params->size());
587 for (TemplateParameterList::const_iterator P = Params->begin(),
588 PEnd = Params->end();
589 P != PEnd; ++P) {
590 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
591 CanonParams.push_back(
592 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnara344577e2011-03-06 15:48:19 +0000593 SourceLocation(),
594 SourceLocation(),
595 TTP->getDepth(),
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000596 TTP->getIndex(), 0, false,
597 TTP->isParameterPack()));
598 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000599 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
600 QualType T = getCanonicalType(NTTP->getType());
601 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
602 NonTypeTemplateParmDecl *Param;
603 if (NTTP->isExpandedParameterPack()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000604 SmallVector<QualType, 2> ExpandedTypes;
605 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000606 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
607 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
608 ExpandedTInfos.push_back(
609 getTrivialTypeSourceInfo(ExpandedTypes.back()));
610 }
611
612 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000613 SourceLocation(),
614 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000615 NTTP->getDepth(),
616 NTTP->getPosition(), 0,
617 T,
618 TInfo,
619 ExpandedTypes.data(),
620 ExpandedTypes.size(),
621 ExpandedTInfos.data());
622 } else {
623 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000624 SourceLocation(),
625 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000626 NTTP->getDepth(),
627 NTTP->getPosition(), 0,
628 T,
629 NTTP->isParameterPack(),
630 TInfo);
631 }
632 CanonParams.push_back(Param);
633
634 } else
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000635 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
636 cast<TemplateTemplateParmDecl>(*P)));
637 }
638
639 TemplateTemplateParmDecl *CanonTTP
640 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
641 SourceLocation(), TTP->getDepth(),
Douglas Gregor61c4d282011-01-05 15:48:55 +0000642 TTP->getPosition(),
643 TTP->isParameterPack(),
644 0,
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000645 TemplateParameterList::Create(*this, SourceLocation(),
646 SourceLocation(),
647 CanonParams.data(),
648 CanonParams.size(),
649 SourceLocation()));
650
651 // Get the new insert position for the node we care about.
652 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
653 assert(Canonical == 0 && "Shouldn't be in the map!");
654 (void)Canonical;
655
656 // Create the canonical template template parameter entry.
657 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
658 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
659 return CanonTTP;
660}
661
Charles Davis071cc7d2010-08-16 03:33:14 +0000662CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCallee79a4c2010-08-21 22:46:04 +0000663 if (!LangOpts.CPlusPlus) return 0;
664
John McCallb8b2c9d2013-01-25 22:30:49 +0000665 switch (T.getCXXABI().getKind()) {
666 case TargetCXXABI::GenericARM:
667 case TargetCXXABI::iOS:
John McCallee79a4c2010-08-21 22:46:04 +0000668 return CreateARMCXXABI(*this);
Tim Northoverc264e162013-01-31 12:13:10 +0000669 case TargetCXXABI::GenericAArch64: // Same as Itanium at this level
John McCallb8b2c9d2013-01-25 22:30:49 +0000670 case TargetCXXABI::GenericItanium:
Charles Davis071cc7d2010-08-16 03:33:14 +0000671 return CreateItaniumCXXABI(*this);
John McCallb8b2c9d2013-01-25 22:30:49 +0000672 case TargetCXXABI::Microsoft:
Charles Davis20cf7172010-08-19 02:18:14 +0000673 return CreateMicrosoftCXXABI(*this);
674 }
David Blaikie7530c032012-01-17 06:56:22 +0000675 llvm_unreachable("Invalid CXXABI type!");
Charles Davis071cc7d2010-08-16 03:33:14 +0000676}
677
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000678static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000679 const LangOptions &LOpts) {
680 if (LOpts.FakeAddressSpaceMap) {
681 // The fake address space map must have a distinct entry for each
682 // language-specific address space.
683 static const unsigned FakeAddrSpaceMap[] = {
684 1, // opencl_global
685 2, // opencl_local
Peter Collingbourne4dc34eb2012-05-20 21:08:35 +0000686 3, // opencl_constant
687 4, // cuda_device
688 5, // cuda_constant
689 6 // cuda_shared
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000690 };
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000691 return &FakeAddrSpaceMap;
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000692 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000693 return &T.getAddressSpaceMap();
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000694 }
695}
696
Douglas Gregor3e3cd932011-09-01 20:23:19 +0000697ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000698 const TargetInfo *t,
Daniel Dunbare91593e2008-08-11 04:54:23 +0000699 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000700 Builtin::Context &builtins,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000701 unsigned size_reserve,
702 bool DelayInitialization)
703 : FunctionProtoTypes(this_()),
704 TemplateSpecializationTypes(this_()),
705 DependentTemplateSpecializationTypes(this_()),
706 SubstTemplateTemplateParmPacks(this_()),
707 GlobalNestedNameSpecifier(0),
Nico Webercac18ad2013-06-20 21:44:55 +0000708 Int128Decl(0), UInt128Decl(0), Float128StubDecl(0),
Meador Ingec5613b22012-06-16 03:34:49 +0000709 BuiltinVaListDecl(0),
Douglas Gregora6ea10e2012-01-17 18:09:05 +0000710 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Fariborz Jahanian96171302012-08-30 18:49:41 +0000711 BOOLDecl(0),
Douglas Gregore97179c2011-09-08 01:46:34 +0000712 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000713 FILEDecl(0),
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +0000714 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
715 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
716 cudaConfigureCallDecl(0),
Douglas Gregore6649772011-12-03 00:30:27 +0000717 NullTypeSourceInfo(QualType()),
718 FirstLocalImport(), LastLocalImport(),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000719 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregor30c42402011-09-27 22:38:19 +0000720 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000721 Idents(idents), Selectors(sels),
722 BuiltinInfo(builtins),
723 DeclarationNames(*this),
Douglas Gregor30c42402011-09-27 22:38:19 +0000724 ExternalSource(0), Listener(0),
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000725 Comments(SM), CommentsLoaded(false),
Dmitri Gribenko6ebf0912013-02-22 14:21:27 +0000726 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
Rafael Espindola42b78612013-05-29 19:51:12 +0000727 LastSDM(0, 0)
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000728{
Mike Stump1eb44332009-09-09 15:08:12 +0000729 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +0000730 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000731
732 if (!DelayInitialization) {
733 assert(t && "No target supplied for ASTContext initialization");
734 InitBuiltinTypes(*t);
735 }
Daniel Dunbare91593e2008-08-11 04:54:23 +0000736}
737
Reid Spencer5f016e22007-07-11 17:01:13 +0000738ASTContext::~ASTContext() {
Ted Kremenek3478eb62010-02-11 07:12:28 +0000739 // Release the DenseMaps associated with DeclContext objects.
740 // FIXME: Is this the ideal solution?
741 ReleaseDeclContextMaps();
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000742
Manuel Klimekf0f353b2013-06-03 13:51:33 +0000743 // Call all of the deallocation functions on all of their targets.
744 for (DeallocationMap::const_iterator I = Deallocations.begin(),
745 E = Deallocations.end(); I != E; ++I)
746 for (unsigned J = 0, N = I->second.size(); J != N; ++J)
747 (I->first)((I->second)[J]);
748
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000749 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000750 // because they can contain DenseMaps.
751 for (llvm::DenseMap<const ObjCContainerDecl*,
752 const ASTRecordLayout*>::iterator
753 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
754 // Increment in loop to prevent using deallocated memory.
755 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
756 R->Destroy(*this);
757
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000758 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
759 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
760 // Increment in loop to prevent using deallocated memory.
761 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
762 R->Destroy(*this);
763 }
Douglas Gregor63200642010-08-30 16:49:28 +0000764
765 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
766 AEnd = DeclAttrs.end();
767 A != AEnd; ++A)
768 A->second->~AttrVec();
769}
Douglas Gregorab452ba2009-03-26 23:50:42 +0000770
Douglas Gregor00545312010-05-23 18:26:36 +0000771void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Manuel Klimekf0f353b2013-06-03 13:51:33 +0000772 Deallocations[Callback].push_back(Data);
Douglas Gregor00545312010-05-23 18:26:36 +0000773}
774
Mike Stump1eb44332009-09-09 15:08:12 +0000775void
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000776ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregor2cf26342009-04-09 22:27:44 +0000777 ExternalSource.reset(Source.take());
778}
779
Reid Spencer5f016e22007-07-11 17:01:13 +0000780void ASTContext::PrintStats() const {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000781 llvm::errs() << "\n*** AST Context Stats:\n";
782 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000783
Douglas Gregordbe833d2009-05-26 14:40:08 +0000784 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000785#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000786#define ABSTRACT_TYPE(Name, Parent)
787#include "clang/AST/TypeNodes.def"
788 0 // Extra
789 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000790
Reid Spencer5f016e22007-07-11 17:01:13 +0000791 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
792 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000793 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000794 }
795
Douglas Gregordbe833d2009-05-26 14:40:08 +0000796 unsigned Idx = 0;
797 unsigned TotalBytes = 0;
798#define TYPE(Name, Parent) \
799 if (counts[Idx]) \
Chandler Carruthcd92a652011-07-04 05:32:14 +0000800 llvm::errs() << " " << counts[Idx] << " " << #Name \
801 << " types\n"; \
Douglas Gregordbe833d2009-05-26 14:40:08 +0000802 TotalBytes += counts[Idx] * sizeof(Name##Type); \
803 ++Idx;
804#define ABSTRACT_TYPE(Name, Parent)
805#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000806
Chandler Carruthcd92a652011-07-04 05:32:14 +0000807 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
808
Douglas Gregor4923aa22010-07-02 20:37:36 +0000809 // Implicit special member functions.
Chandler Carruthcd92a652011-07-04 05:32:14 +0000810 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
811 << NumImplicitDefaultConstructors
812 << " implicit default constructors created\n";
813 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
814 << NumImplicitCopyConstructors
815 << " implicit copy constructors created\n";
David Blaikie4e4d0842012-03-11 07:00:24 +0000816 if (getLangOpts().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000817 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
818 << NumImplicitMoveConstructors
819 << " implicit move constructors created\n";
820 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
821 << NumImplicitCopyAssignmentOperators
822 << " implicit copy assignment operators created\n";
David Blaikie4e4d0842012-03-11 07:00:24 +0000823 if (getLangOpts().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000824 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
825 << NumImplicitMoveAssignmentOperators
826 << " implicit move assignment operators created\n";
827 llvm::errs() << NumImplicitDestructorsDeclared << "/"
828 << NumImplicitDestructors
829 << " implicit destructors created\n";
830
Douglas Gregor2cf26342009-04-09 22:27:44 +0000831 if (ExternalSource.get()) {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000832 llvm::errs() << "\n";
Douglas Gregor2cf26342009-04-09 22:27:44 +0000833 ExternalSource->PrintStats();
834 }
Chandler Carruthcd92a652011-07-04 05:32:14 +0000835
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000836 BumpAlloc.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000837}
838
Douglas Gregor772eeae2011-08-12 06:49:56 +0000839TypedefDecl *ASTContext::getInt128Decl() const {
840 if (!Int128Decl) {
841 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
842 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
843 getTranslationUnitDecl(),
844 SourceLocation(),
845 SourceLocation(),
846 &Idents.get("__int128_t"),
847 TInfo);
848 }
849
850 return Int128Decl;
851}
852
853TypedefDecl *ASTContext::getUInt128Decl() const {
854 if (!UInt128Decl) {
855 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
856 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
857 getTranslationUnitDecl(),
858 SourceLocation(),
859 SourceLocation(),
860 &Idents.get("__uint128_t"),
861 TInfo);
862 }
863
864 return UInt128Decl;
865}
Reid Spencer5f016e22007-07-11 17:01:13 +0000866
Nico Webercac18ad2013-06-20 21:44:55 +0000867TypeDecl *ASTContext::getFloat128StubType() const {
Nico Weber3f7c1b12013-06-21 01:29:36 +0000868 assert(LangOpts.CPlusPlus && "should only be called for c++");
Nico Webercac18ad2013-06-20 21:44:55 +0000869 if (!Float128StubDecl) {
Nico Weber9b9bdba2013-06-20 23:30:30 +0000870 Float128StubDecl = CXXRecordDecl::Create(const_cast<ASTContext &>(*this),
871 TTK_Struct,
872 getTranslationUnitDecl(),
873 SourceLocation(),
874 SourceLocation(),
875 &Idents.get("__float128"));
Nico Webercac18ad2013-06-20 21:44:55 +0000876 }
877
878 return Float128StubDecl;
879}
880
John McCalle27ec8a2009-10-23 23:03:21 +0000881void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000882 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000883 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000884 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000885}
886
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000887void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
888 assert((!this->Target || this->Target == &Target) &&
889 "Incorrect target reinitialization");
Reid Spencer5f016e22007-07-11 17:01:13 +0000890 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000891
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000892 this->Target = &Target;
893
894 ABI.reset(createCXXABI(Target));
895 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
896
Reid Spencer5f016e22007-07-11 17:01:13 +0000897 // C99 6.2.5p19.
898 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000899
Reid Spencer5f016e22007-07-11 17:01:13 +0000900 // C99 6.2.5p2.
901 InitBuiltinType(BoolTy, BuiltinType::Bool);
902 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000903 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000904 InitBuiltinType(CharTy, BuiltinType::Char_S);
905 else
906 InitBuiltinType(CharTy, BuiltinType::Char_U);
907 // C99 6.2.5p4.
908 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
909 InitBuiltinType(ShortTy, BuiltinType::Short);
910 InitBuiltinType(IntTy, BuiltinType::Int);
911 InitBuiltinType(LongTy, BuiltinType::Long);
912 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000913
Reid Spencer5f016e22007-07-11 17:01:13 +0000914 // C99 6.2.5p6.
915 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
916 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
917 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
918 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
919 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000920
Reid Spencer5f016e22007-07-11 17:01:13 +0000921 // C99 6.2.5p10.
922 InitBuiltinType(FloatTy, BuiltinType::Float);
923 InitBuiltinType(DoubleTy, BuiltinType::Double);
924 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000925
Chris Lattner2df9ced2009-04-30 02:43:43 +0000926 // GNU extension, 128-bit integers.
927 InitBuiltinType(Int128Ty, BuiltinType::Int128);
928 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
929
Hans Wennborg15f92ba2013-05-10 10:08:40 +0000930 // C++ 3.9.1p5
931 if (TargetInfo::isTypeSigned(Target.getWCharType()))
932 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
933 else // -fshort-wchar makes wchar_t be unsigned.
934 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
935 if (LangOpts.CPlusPlus && LangOpts.WChar)
936 WideCharTy = WCharTy;
937 else {
938 // C99 (or C++ using -fno-wchar).
939 WideCharTy = getFromTargetType(Target.getWCharType());
940 }
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000941
James Molloy392da482012-05-04 10:55:22 +0000942 WIntTy = getFromTargetType(Target.getWIntType());
943
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000944 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
945 InitBuiltinType(Char16Ty, BuiltinType::Char16);
946 else // C99
947 Char16Ty = getFromTargetType(Target.getChar16Type());
948
949 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
950 InitBuiltinType(Char32Ty, BuiltinType::Char32);
951 else // C99
952 Char32Ty = getFromTargetType(Target.getChar32Type());
953
Douglas Gregor898574e2008-12-05 23:32:09 +0000954 // Placeholder type for type-dependent expressions whose type is
955 // completely unknown. No code should ever check a type against
956 // DependentTy and users should never see it; however, it is here to
957 // help diagnose failures to properly check for type-dependent
958 // expressions.
959 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000960
John McCall2a984ca2010-10-12 00:20:44 +0000961 // Placeholder type for functions.
962 InitBuiltinType(OverloadTy, BuiltinType::Overload);
963
John McCall864c0412011-04-26 20:42:42 +0000964 // Placeholder type for bound members.
965 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
966
John McCall3c3b7f92011-10-25 17:37:35 +0000967 // Placeholder type for pseudo-objects.
968 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
969
John McCall1de4d4e2011-04-07 08:22:57 +0000970 // "any" type; useful for debugger-like clients.
971 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
972
John McCall0ddaeb92011-10-17 18:09:15 +0000973 // Placeholder type for unbridged ARC casts.
974 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
975
Eli Friedmana6c66ce2012-08-31 00:14:07 +0000976 // Placeholder type for builtin functions.
977 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
978
Reid Spencer5f016e22007-07-11 17:01:13 +0000979 // C99 6.2.5p11.
980 FloatComplexTy = getComplexType(FloatTy);
981 DoubleComplexTy = getComplexType(DoubleTy);
982 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000983
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000984 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000985 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
986 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000987 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeib13621d2012-12-18 14:38:23 +0000988
989 if (LangOpts.OpenCL) {
990 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
991 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
992 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
993 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
994 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
995 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
Guy Benyeie6b9d802013-01-20 12:31:11 +0000996
Guy Benyei21f18c42013-02-07 10:55:47 +0000997 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyeie6b9d802013-01-20 12:31:11 +0000998 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Guy Benyeib13621d2012-12-18 14:38:23 +0000999 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001000
1001 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian93a49942012-04-16 21:03:30 +00001002 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1003 SignedCharTy : BoolTy);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001004
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001005 ObjCConstantStringType = QualType();
Fariborz Jahanianf7992132013-01-04 18:45:40 +00001006
1007 ObjCSuperType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00001008
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001009 // void * type
1010 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001011
1012 // nullptr type (C++0x 2.14.7)
1013 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001014
1015 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1016 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingefb40e3f2012-07-01 15:57:25 +00001017
1018 // Builtin type used to help define __builtin_va_list.
1019 VaListTagTy = QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001020}
1021
David Blaikied6471f72011-09-25 23:23:43 +00001022DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00001023 return SourceMgr.getDiagnostics();
1024}
1025
Douglas Gregor63200642010-08-30 16:49:28 +00001026AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1027 AttrVec *&Result = DeclAttrs[D];
1028 if (!Result) {
1029 void *Mem = Allocate(sizeof(AttrVec));
1030 Result = new (Mem) AttrVec;
1031 }
1032
1033 return *Result;
1034}
1035
1036/// \brief Erase the attributes corresponding to the given declaration.
1037void ASTContext::eraseDeclAttrs(const Decl *D) {
1038 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1039 if (Pos != DeclAttrs.end()) {
1040 Pos->second->~AttrVec();
1041 DeclAttrs.erase(Pos);
1042 }
1043}
1044
Larisse Voufoef4579c2013-08-06 01:03:05 +00001045// FIXME: Remove ?
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001046MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +00001047ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001048 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufoef4579c2013-08-06 01:03:05 +00001049 return getTemplateOrSpecializationInfo(Var)
1050 .dyn_cast<MemberSpecializationInfo *>();
1051}
1052
1053ASTContext::TemplateOrSpecializationInfo
1054ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1055 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1056 TemplateOrInstantiation.find(Var);
1057 if (Pos == TemplateOrInstantiation.end())
1058 return TemplateOrSpecializationInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00001059
Douglas Gregor7caa6822009-07-24 20:34:43 +00001060 return Pos->second;
1061}
1062
Mike Stump1eb44332009-09-09 15:08:12 +00001063void
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001064ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +00001065 TemplateSpecializationKind TSK,
1066 SourceLocation PointOfInstantiation) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001067 assert(Inst->isStaticDataMember() && "Not a static data member");
1068 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufoef4579c2013-08-06 01:03:05 +00001069 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1070 Tmpl, TSK, PointOfInstantiation));
1071}
1072
1073void
1074ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1075 TemplateOrSpecializationInfo TSI) {
1076 assert(!TemplateOrInstantiation[Inst] &&
1077 "Already noted what the variable was instantiated from");
1078 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregor7caa6822009-07-24 20:34:43 +00001079}
1080
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001081FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1082 const FunctionDecl *FD){
1083 assert(FD && "Specialization is 0");
1084 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet0d95f0d2011-08-14 14:28:49 +00001085 = ClassScopeSpecializationPattern.find(FD);
1086 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001087 return 0;
1088
1089 return Pos->second;
1090}
1091
1092void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1093 FunctionDecl *Pattern) {
1094 assert(FD && "Specialization is 0");
1095 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet0d95f0d2011-08-14 14:28:49 +00001096 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001097}
1098
John McCall7ba107a2009-11-18 02:36:19 +00001099NamedDecl *
John McCalled976492009-12-04 22:46:56 +00001100ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +00001101 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +00001102 = InstantiatedFromUsingDecl.find(UUD);
1103 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +00001104 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001105
Anders Carlsson0d8df782009-08-29 19:37:28 +00001106 return Pos->second;
1107}
1108
1109void
John McCalled976492009-12-04 22:46:56 +00001110ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1111 assert((isa<UsingDecl>(Pattern) ||
1112 isa<UnresolvedUsingValueDecl>(Pattern) ||
1113 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1114 "pattern decl is not a using decl");
1115 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1116 InstantiatedFromUsingDecl[Inst] = Pattern;
1117}
1118
1119UsingShadowDecl *
1120ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1121 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1122 = InstantiatedFromUsingShadowDecl.find(Inst);
1123 if (Pos == InstantiatedFromUsingShadowDecl.end())
1124 return 0;
1125
1126 return Pos->second;
1127}
1128
1129void
1130ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1131 UsingShadowDecl *Pattern) {
1132 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1133 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00001134}
1135
Anders Carlssond8b285f2009-09-01 04:26:58 +00001136FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1137 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1138 = InstantiatedFromUnnamedFieldDecl.find(Field);
1139 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1140 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001141
Anders Carlssond8b285f2009-09-01 04:26:58 +00001142 return Pos->second;
1143}
1144
1145void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1146 FieldDecl *Tmpl) {
1147 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1148 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1149 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1150 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +00001151
Anders Carlssond8b285f2009-09-01 04:26:58 +00001152 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1153}
1154
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001155ASTContext::overridden_cxx_method_iterator
1156ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1157 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001158 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001159 if (Pos == OverriddenMethods.end())
1160 return 0;
1161
1162 return Pos->second.begin();
1163}
1164
1165ASTContext::overridden_cxx_method_iterator
1166ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1167 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001168 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001169 if (Pos == OverriddenMethods.end())
1170 return 0;
1171
1172 return Pos->second.end();
1173}
1174
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +00001175unsigned
1176ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1177 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001178 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +00001179 if (Pos == OverriddenMethods.end())
1180 return 0;
1181
1182 return Pos->second.size();
1183}
1184
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001185void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1186 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001187 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001188 OverriddenMethods[Method].push_back(Overridden);
1189}
1190
Dmitri Gribenko1e905da2012-11-03 14:24:57 +00001191void ASTContext::getOverriddenMethods(
1192 const NamedDecl *D,
1193 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001194 assert(D);
1195
1196 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis685d1042013-04-17 00:09:03 +00001197 Overridden.append(overridden_methods_begin(CXXMethod),
1198 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001199 return;
1200 }
1201
1202 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1203 if (!Method)
1204 return;
1205
Argyrios Kyrtzidis740ae672012-10-09 18:19:01 +00001206 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1207 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisbc0a2bb2012-10-09 20:08:43 +00001208 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001209}
1210
Douglas Gregore6649772011-12-03 00:30:27 +00001211void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1212 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1213 assert(!Import->isFromASTFile() && "Non-local import declaration");
1214 if (!FirstLocalImport) {
1215 FirstLocalImport = Import;
1216 LastLocalImport = Import;
1217 return;
1218 }
1219
1220 LastLocalImport->NextLocalImport = Import;
1221 LastLocalImport = Import;
1222}
1223
Chris Lattner464175b2007-07-18 17:52:12 +00001224//===----------------------------------------------------------------------===//
1225// Type Sizing and Analysis
1226//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +00001227
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001228/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1229/// scalar floating point type.
1230const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +00001231 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001232 assert(BT && "Not a floating point type!");
1233 switch (BT->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001234 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001235 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001236 case BuiltinType::Float: return Target->getFloatFormat();
1237 case BuiltinType::Double: return Target->getDoubleFormat();
1238 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001239 }
1240}
1241
Rafael Espindola1c56c9d2013-08-08 19:53:46 +00001242CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001243 unsigned Align = Target->getCharWidth();
Eli Friedmandcdafb62009-02-22 02:56:25 +00001244
John McCall4081a5c2010-10-08 18:24:19 +00001245 bool UseAlignAttrOnly = false;
1246 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1247 Align = AlignFromAttr;
Eli Friedmandcdafb62009-02-22 02:56:25 +00001248
John McCall4081a5c2010-10-08 18:24:19 +00001249 // __attribute__((aligned)) can increase or decrease alignment
1250 // *except* on a struct or struct member, where it only increases
1251 // alignment unless 'packed' is also specified.
1252 //
Peter Collingbourne82d0b0a2011-09-29 18:04:28 +00001253 // It is an error for alignas to decrease alignment, so we can
John McCall4081a5c2010-10-08 18:24:19 +00001254 // ignore that possibility; Sema should diagnose it.
1255 if (isa<FieldDecl>(D)) {
1256 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1257 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1258 } else {
1259 UseAlignAttrOnly = true;
1260 }
1261 }
Fariborz Jahanian78a7d7d2011-05-05 21:19:14 +00001262 else if (isa<FieldDecl>(D))
1263 UseAlignAttrOnly =
1264 D->hasAttr<PackedAttr>() ||
1265 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall4081a5c2010-10-08 18:24:19 +00001266
John McCallba4f5d52011-01-20 07:57:12 +00001267 // If we're using the align attribute only, just ignore everything
1268 // else about the declaration and its type.
John McCall4081a5c2010-10-08 18:24:19 +00001269 if (UseAlignAttrOnly) {
John McCallba4f5d52011-01-20 07:57:12 +00001270 // do nothing
1271
John McCall4081a5c2010-10-08 18:24:19 +00001272 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00001273 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001274 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Rafael Espindola1c56c9d2013-08-08 19:53:46 +00001275 if (ForAlignof)
Sebastian Redl5d484e82009-11-23 17:18:46 +00001276 T = RT->getPointeeType();
1277 else
1278 T = getPointerType(RT->getPointeeType());
1279 }
1280 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall3b657512011-01-19 10:06:00 +00001281 // Adjust alignments of declarations with array type by the
1282 // large-array alignment on the target.
Rafael Espindolab82f77f2013-08-07 18:08:19 +00001283 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola1c56c9d2013-08-08 19:53:46 +00001284 unsigned MinWidth = Target->getLargeArrayMinWidth();
1285 if (!ForAlignof && MinWidth) {
Rafael Espindolab82f77f2013-08-07 18:08:19 +00001286 if (isa<VariableArrayType>(arrayType))
1287 Align = std::max(Align, Target->getLargeArrayAlign());
1288 else if (isa<ConstantArrayType>(arrayType) &&
1289 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1290 Align = std::max(Align, Target->getLargeArrayAlign());
1291 }
Eli Friedmandcdafb62009-02-22 02:56:25 +00001292
John McCall3b657512011-01-19 10:06:00 +00001293 // Walk through any array types while we're at it.
1294 T = getBaseElementType(arrayType);
1295 }
Chad Rosier9f1210c2011-07-26 07:03:04 +00001296 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Ulrich Weigand6b203512013-05-06 16:23:57 +00001297 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1298 if (VD->hasGlobalStorage())
1299 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1300 }
Eli Friedmandcdafb62009-02-22 02:56:25 +00001301 }
John McCallba4f5d52011-01-20 07:57:12 +00001302
1303 // Fields can be subject to extra alignment constraints, like if
1304 // the field is packed, the struct is packed, or the struct has a
1305 // a max-field-alignment constraint (#pragma pack). So calculate
1306 // the actual alignment of the field within the struct, and then
1307 // (as we're expected to) constrain that by the alignment of the type.
Matt Beaumont-Gay147fab92013-06-25 22:19:15 +00001308 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1309 const RecordDecl *Parent = Field->getParent();
1310 // We can only produce a sensible answer if the record is valid.
1311 if (!Parent->isInvalidDecl()) {
1312 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCallba4f5d52011-01-20 07:57:12 +00001313
Matt Beaumont-Gay147fab92013-06-25 22:19:15 +00001314 // Start with the record's overall alignment.
1315 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCallba4f5d52011-01-20 07:57:12 +00001316
Matt Beaumont-Gay147fab92013-06-25 22:19:15 +00001317 // Use the GCD of that and the offset within the record.
1318 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1319 if (Offset > 0) {
1320 // Alignment is always a power of 2, so the GCD will be a power of 2,
1321 // which means we get to do this crazy thing instead of Euclid's.
1322 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1323 if (LowBitOfOffset < FieldAlign)
1324 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1325 }
1326
1327 Align = std::min(Align, FieldAlign);
John McCallba4f5d52011-01-20 07:57:12 +00001328 }
Charles Davis05f62472010-02-23 04:52:00 +00001329 }
Chris Lattneraf707ab2009-01-24 21:53:27 +00001330 }
Eli Friedmandcdafb62009-02-22 02:56:25 +00001331
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001332 return toCharUnitsFromBits(Align);
Chris Lattneraf707ab2009-01-24 21:53:27 +00001333}
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001334
John McCall929bbfb2012-08-21 04:10:00 +00001335// getTypeInfoDataSizeInChars - Return the size of a type, in
1336// chars. If the type is a record, its data size is returned. This is
1337// the size of the memcpy that's performed when assigning this type
1338// using a trivial copy/move assignment operator.
1339std::pair<CharUnits, CharUnits>
1340ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1341 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1342
1343 // In C++, objects can sometimes be allocated into the tail padding
1344 // of a base-class subobject. We decide whether that's possible
1345 // during class layout, so here we can just trust the layout results.
1346 if (getLangOpts().CPlusPlus) {
1347 if (const RecordType *RT = T->getAs<RecordType>()) {
1348 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1349 sizeAndAlign.first = layout.getDataSize();
1350 }
1351 }
1352
1353 return sizeAndAlign;
1354}
1355
Richard Trieu910f17e2013-05-14 21:59:17 +00001356/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1357/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1358std::pair<CharUnits, CharUnits>
1359static getConstantArrayInfoInChars(const ASTContext &Context,
1360 const ConstantArrayType *CAT) {
1361 std::pair<CharUnits, CharUnits> EltInfo =
1362 Context.getTypeInfoInChars(CAT->getElementType());
1363 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieu1069b732013-05-14 23:41:50 +00001364 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1365 (uint64_t)(-1)/Size) &&
Richard Trieu910f17e2013-05-14 21:59:17 +00001366 "Overflow in array type char size evaluation");
1367 uint64_t Width = EltInfo.first.getQuantity() * Size;
1368 unsigned Align = EltInfo.second.getQuantity();
1369 Width = llvm::RoundUpToAlignment(Width, Align);
1370 return std::make_pair(CharUnits::fromQuantity(Width),
1371 CharUnits::fromQuantity(Align));
1372}
1373
John McCallea1471e2010-05-20 01:18:31 +00001374std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +00001375ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu910f17e2013-05-14 21:59:17 +00001376 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1377 return getConstantArrayInfoInChars(*this, CAT);
John McCallea1471e2010-05-20 01:18:31 +00001378 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001379 return std::make_pair(toCharUnitsFromBits(Info.first),
1380 toCharUnitsFromBits(Info.second));
John McCallea1471e2010-05-20 01:18:31 +00001381}
1382
1383std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +00001384ASTContext::getTypeInfoInChars(QualType T) const {
John McCallea1471e2010-05-20 01:18:31 +00001385 return getTypeInfoInChars(T.getTypePtr());
1386}
1387
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001388std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1389 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1390 if (it != MemoizedTypeInfo.end())
1391 return it->second;
1392
1393 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1394 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1395 return Info;
1396}
1397
1398/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1399/// method does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +00001400///
1401/// FIXME: Pointers into different addr spaces could have different sizes and
1402/// alignment requirements: getPointerInfo should take an AddrSpace, this
1403/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +00001404std::pair<uint64_t, unsigned>
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001405ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5e301002009-02-27 18:32:39 +00001406 uint64_t Width=0;
1407 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +00001408 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +00001409#define TYPE(Class, Base)
1410#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +00001411#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +00001412#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikiedc809782013-07-13 21:08:03 +00001413#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1414 case Type::Class: \
1415 assert(!T->isDependentType() && "should not see dependent types here"); \
1416 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregor72564e72009-02-26 23:50:07 +00001417#include "clang/AST/TypeNodes.def"
John McCalld3d49bb2011-06-28 16:49:23 +00001418 llvm_unreachable("Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +00001419
Chris Lattner692233e2007-07-13 22:27:08 +00001420 case Type::FunctionNoProto:
1421 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +00001422 // GCC extension: alignof(function) = 32 bits
1423 Width = 0;
1424 Align = 32;
1425 break;
1426
Douglas Gregor72564e72009-02-26 23:50:07 +00001427 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +00001428 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +00001429 Width = 0;
1430 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1431 break;
1432
Steve Narofffb22d962007-08-30 01:06:46 +00001433 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001434 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001435
Chris Lattner98be4942008-03-05 18:54:05 +00001436 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarafea966a2011-12-13 11:23:52 +00001437 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001438 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1439 "Overflow in array type bit size evaluation");
Abramo Bagnarafea966a2011-12-13 11:23:52 +00001440 Width = EltInfo.first*Size;
Chris Lattner030d8842007-07-19 22:06:24 +00001441 Align = EltInfo.second;
Argyrios Kyrtzidiscd88b412011-04-26 21:05:39 +00001442 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattner030d8842007-07-19 22:06:24 +00001443 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +00001444 }
Nate Begeman213541a2008-04-18 23:10:10 +00001445 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +00001446 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +00001447 const VectorType *VT = cast<VectorType>(T);
1448 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1449 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +00001450 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +00001451 // If the alignment is not a power of 2, round up to the next power of 2.
1452 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +00001453 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +00001454 Align = llvm::NextPowerOf2(Align);
1455 Width = llvm::RoundUpToAlignment(Width, Align);
1456 }
Chad Rosierf9e9af72012-07-13 23:57:43 +00001457 // Adjust the alignment based on the target max.
1458 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1459 if (TargetVectorAlign && TargetVectorAlign < Align)
1460 Align = TargetVectorAlign;
Chris Lattner030d8842007-07-19 22:06:24 +00001461 break;
1462 }
Chris Lattner5d2a6302007-07-18 18:26:58 +00001463
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001464 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +00001465 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001466 default: llvm_unreachable("Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +00001467 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +00001468 // GCC extension: alignof(void) = 8 bits.
1469 Width = 0;
1470 Align = 8;
1471 break;
1472
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001473 case BuiltinType::Bool:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001474 Width = Target->getBoolWidth();
1475 Align = Target->getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001476 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001477 case BuiltinType::Char_S:
1478 case BuiltinType::Char_U:
1479 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001480 case BuiltinType::SChar:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001481 Width = Target->getCharWidth();
1482 Align = Target->getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001483 break;
Chris Lattner3f59c972010-12-25 23:25:43 +00001484 case BuiltinType::WChar_S:
1485 case BuiltinType::WChar_U:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001486 Width = Target->getWCharWidth();
1487 Align = Target->getWCharAlign();
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00001488 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001489 case BuiltinType::Char16:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001490 Width = Target->getChar16Width();
1491 Align = Target->getChar16Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001492 break;
1493 case BuiltinType::Char32:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001494 Width = Target->getChar32Width();
1495 Align = Target->getChar32Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001496 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001497 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001498 case BuiltinType::Short:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001499 Width = Target->getShortWidth();
1500 Align = Target->getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001501 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001502 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001503 case BuiltinType::Int:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001504 Width = Target->getIntWidth();
1505 Align = Target->getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001506 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001507 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001508 case BuiltinType::Long:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001509 Width = Target->getLongWidth();
1510 Align = Target->getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001511 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001512 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001513 case BuiltinType::LongLong:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001514 Width = Target->getLongLongWidth();
1515 Align = Target->getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001516 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +00001517 case BuiltinType::Int128:
1518 case BuiltinType::UInt128:
1519 Width = 128;
1520 Align = 128; // int128_t is 128-bit aligned on all targets.
1521 break;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001522 case BuiltinType::Half:
1523 Width = Target->getHalfWidth();
1524 Align = Target->getHalfAlign();
1525 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001526 case BuiltinType::Float:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001527 Width = Target->getFloatWidth();
1528 Align = Target->getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001529 break;
1530 case BuiltinType::Double:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001531 Width = Target->getDoubleWidth();
1532 Align = Target->getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001533 break;
1534 case BuiltinType::LongDouble:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001535 Width = Target->getLongDoubleWidth();
1536 Align = Target->getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001537 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001538 case BuiltinType::NullPtr:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001539 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1540 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +00001541 break;
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +00001542 case BuiltinType::ObjCId:
1543 case BuiltinType::ObjCClass:
1544 case BuiltinType::ObjCSel:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001545 Width = Target->getPointerWidth(0);
1546 Align = Target->getPointerAlign(0);
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +00001547 break;
Guy Benyei21f18c42013-02-07 10:55:47 +00001548 case BuiltinType::OCLSampler:
1549 // Samplers are modeled as integers.
1550 Width = Target->getIntWidth();
1551 Align = Target->getIntAlign();
1552 break;
Guy Benyeie6b9d802013-01-20 12:31:11 +00001553 case BuiltinType::OCLEvent:
Guy Benyeib13621d2012-12-18 14:38:23 +00001554 case BuiltinType::OCLImage1d:
1555 case BuiltinType::OCLImage1dArray:
1556 case BuiltinType::OCLImage1dBuffer:
1557 case BuiltinType::OCLImage2d:
1558 case BuiltinType::OCLImage2dArray:
1559 case BuiltinType::OCLImage3d:
1560 // Currently these types are pointers to opaque types.
1561 Width = Target->getPointerWidth(0);
1562 Align = Target->getPointerAlign(0);
1563 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001564 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +00001565 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001566 case Type::ObjCObjectPointer:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001567 Width = Target->getPointerWidth(0);
1568 Align = Target->getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001569 break;
Steve Naroff485eeff2008-09-24 15:05:44 +00001570 case Type::BlockPointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001571 unsigned AS = getTargetAddressSpace(
1572 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001573 Width = Target->getPointerWidth(AS);
1574 Align = Target->getPointerAlign(AS);
Steve Naroff485eeff2008-09-24 15:05:44 +00001575 break;
1576 }
Sebastian Redl5d484e82009-11-23 17:18:46 +00001577 case Type::LValueReference:
1578 case Type::RValueReference: {
1579 // alignof and sizeof should never enter this code path here, so we go
1580 // the pointer route.
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001581 unsigned AS = getTargetAddressSpace(
1582 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001583 Width = Target->getPointerWidth(AS);
1584 Align = Target->getPointerAlign(AS);
Sebastian Redl5d484e82009-11-23 17:18:46 +00001585 break;
1586 }
Chris Lattnerf72a4432008-03-08 08:34:58 +00001587 case Type::Pointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001588 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001589 Width = Target->getPointerWidth(AS);
1590 Align = Target->getPointerAlign(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +00001591 break;
1592 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00001593 case Type::MemberPointer: {
Charles Davis071cc7d2010-08-16 03:33:14 +00001594 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Reid Kleckner84e9ab42013-03-28 20:02:56 +00001595 llvm::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson1cca74e2009-05-17 02:06:04 +00001596 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +00001597 }
Chris Lattner5d2a6302007-07-18 18:26:58 +00001598 case Type::Complex: {
1599 // Complex types have the same alignment as their elements, but twice the
1600 // size.
Mike Stump1eb44332009-09-09 15:08:12 +00001601 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +00001602 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001603 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +00001604 Align = EltInfo.second;
1605 break;
1606 }
John McCallc12c5bb2010-05-15 11:32:37 +00001607 case Type::ObjCObject:
1608 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner12df2462013-06-24 17:51:48 +00001609 case Type::Decayed:
1610 return getTypeInfo(cast<DecayedType>(T)->getDecayedType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +00001611 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001612 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +00001613 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001614 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001615 Align = toBits(Layout.getAlignment());
Devang Patel44a3dde2008-06-04 21:54:36 +00001616 break;
1617 }
Douglas Gregor72564e72009-02-26 23:50:07 +00001618 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00001619 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001620 const TagType *TT = cast<TagType>(T);
1621
1622 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor22ce41d2011-04-20 17:29:44 +00001623 Width = 8;
1624 Align = 8;
Chris Lattner8389eab2008-08-09 21:35:13 +00001625 break;
1626 }
Mike Stump1eb44332009-09-09 15:08:12 +00001627
Daniel Dunbar1d751182008-11-08 05:48:37 +00001628 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +00001629 return getTypeInfo(ET->getDecl()->getIntegerType());
1630
Daniel Dunbar1d751182008-11-08 05:48:37 +00001631 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +00001632 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001633 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001634 Align = toBits(Layout.getAlignment());
Chris Lattnerdc0d73e2007-07-23 22:46:22 +00001635 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001636 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001637
Chris Lattner9fcfe922009-10-22 05:17:15 +00001638 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +00001639 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1640 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +00001641
Richard Smith34b41d92011-02-20 03:19:35 +00001642 case Type::Auto: {
1643 const AutoType *A = cast<AutoType>(T);
Richard Smithdc7a4f52013-04-30 13:56:41 +00001644 assert(!A->getDeducedType().isNull() &&
1645 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gaydc856af2011-02-22 20:00:16 +00001646 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith34b41d92011-02-20 03:19:35 +00001647 }
1648
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001649 case Type::Paren:
1650 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1651
Douglas Gregor18857642009-04-30 17:32:17 +00001652 case Type::Typedef: {
Richard Smith162e1c12011-04-15 14:24:37 +00001653 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregordf1367a2010-08-27 00:11:28 +00001654 std::pair<uint64_t, unsigned> Info
1655 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattnerc1de52d2011-02-19 22:55:41 +00001656 // If the typedef has an aligned attribute on it, it overrides any computed
1657 // alignment we have. This violates the GCC documentation (which says that
1658 // attribute(aligned) can only round up) but matches its implementation.
1659 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1660 Align = AttrAlign;
1661 else
1662 Align = Info.second;
Douglas Gregordf1367a2010-08-27 00:11:28 +00001663 Width = Info.first;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001664 break;
Chris Lattner71763312008-04-06 22:05:18 +00001665 }
Douglas Gregor18857642009-04-30 17:32:17 +00001666
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001667 case Type::Elaborated:
1668 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +00001669
John McCall9d156a72011-01-06 01:58:22 +00001670 case Type::Attributed:
1671 return getTypeInfo(
1672 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1673
Eli Friedmanb001de72011-10-06 23:00:33 +00001674 case Type::Atomic: {
John McCall9eda3ab2013-03-07 21:37:17 +00001675 // Start with the base type information.
Eli Friedman2be46072011-10-14 20:59:01 +00001676 std::pair<uint64_t, unsigned> Info
1677 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1678 Width = Info.first;
1679 Align = Info.second;
John McCall9eda3ab2013-03-07 21:37:17 +00001680
1681 // If the size of the type doesn't exceed the platform's max
1682 // atomic promotion width, make the size and alignment more
1683 // favorable to atomic operations:
1684 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1685 // Round the size up to a power of 2.
1686 if (!llvm::isPowerOf2_64(Width))
1687 Width = llvm::NextPowerOf2(Width);
1688
1689 // Set the alignment equal to the size.
Eli Friedman2be46072011-10-14 20:59:01 +00001690 Align = static_cast<unsigned>(Width);
1691 }
Eli Friedmanb001de72011-10-06 23:00:33 +00001692 }
1693
Douglas Gregor18857642009-04-30 17:32:17 +00001694 }
Mike Stump1eb44332009-09-09 15:08:12 +00001695
Eli Friedman2be46072011-10-14 20:59:01 +00001696 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001697 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +00001698}
1699
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001700/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1701CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1702 return CharUnits::fromQuantity(BitSize / getCharWidth());
1703}
1704
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001705/// toBits - Convert a size in characters to a size in characters.
1706int64_t ASTContext::toBits(CharUnits CharSize) const {
1707 return CharSize.getQuantity() * getCharWidth();
1708}
1709
Ken Dyckbdc601b2009-12-22 14:23:30 +00001710/// getTypeSizeInChars - Return the size of the specified type, in characters.
1711/// This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001712CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu910f17e2013-05-14 21:59:17 +00001713 return getTypeInfoInChars(T).first;
Ken Dyckbdc601b2009-12-22 14:23:30 +00001714}
Jay Foad4ba2a172011-01-12 09:06:06 +00001715CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu910f17e2013-05-14 21:59:17 +00001716 return getTypeInfoInChars(T).first;
Ken Dyckbdc601b2009-12-22 14:23:30 +00001717}
1718
Ken Dyck16e20cc2010-01-26 17:25:18 +00001719/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +00001720/// characters. This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001721CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001722 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001723}
Jay Foad4ba2a172011-01-12 09:06:06 +00001724CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001725 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001726}
1727
Chris Lattner34ebde42009-01-27 18:08:34 +00001728/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1729/// type for the current target in bits. This can be different than the ABI
1730/// alignment in cases where it is beneficial for performance to overalign
1731/// a data type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001732unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattner34ebde42009-01-27 18:08:34 +00001733 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +00001734
1735 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +00001736 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +00001737 T = CT->getElementType().getTypePtr();
1738 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosiercde7a1d2012-03-21 20:20:47 +00001739 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1740 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman1eed6022009-05-25 21:27:19 +00001741 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1742
Chris Lattner34ebde42009-01-27 18:08:34 +00001743 return ABIAlign;
1744}
1745
Ulrich Weigand6b203512013-05-06 16:23:57 +00001746/// getAlignOfGlobalVar - Return the alignment in bits that should be given
1747/// to a global variable of the specified type.
1748unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1749 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1750}
1751
1752/// getAlignOfGlobalVarInChars - Return the alignment in characters that
1753/// should be given to a global variable of the specified type.
1754CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1755 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1756}
1757
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001758/// DeepCollectObjCIvars -
1759/// This routine first collects all declared, but not synthesized, ivars in
1760/// super class and then collects all ivars, including those synthesized for
1761/// current class. This routine is used for implementation of current class
1762/// when all ivars, declared and synthesized are known.
Fariborz Jahanian98200742009-05-12 18:14:29 +00001763///
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001764void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1765 bool leafClass,
Jordy Rosedb8264e2011-07-22 02:08:32 +00001766 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001767 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1768 DeepCollectObjCIvars(SuperClass, false, Ivars);
1769 if (!leafClass) {
1770 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1771 E = OI->ivar_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001772 Ivars.push_back(*I);
Chad Rosier30601782011-08-17 23:08:45 +00001773 } else {
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001774 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosedb8264e2011-07-22 02:08:32 +00001775 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001776 Iv= Iv->getNextIvar())
1777 Ivars.push_back(Iv);
1778 }
Fariborz Jahanian98200742009-05-12 18:14:29 +00001779}
1780
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001781/// CollectInheritedProtocols - Collect all protocols in current class and
1782/// those inherited by it.
1783void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001784 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001785 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001786 // We can use protocol_iterator here instead of
1787 // all_referenced_protocol_iterator since we are walking all categories.
1788 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1789 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001790 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001791 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001792 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001793 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001794 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001795 CollectInheritedProtocols(*P, Protocols);
1796 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001797 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001798
1799 // Categories of this Interface.
Douglas Gregord3297242013-01-16 23:00:23 +00001800 for (ObjCInterfaceDecl::visible_categories_iterator
1801 Cat = OI->visible_categories_begin(),
1802 CatEnd = OI->visible_categories_end();
1803 Cat != CatEnd; ++Cat) {
1804 CollectInheritedProtocols(*Cat, Protocols);
1805 }
1806
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001807 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1808 while (SD) {
1809 CollectInheritedProtocols(SD, Protocols);
1810 SD = SD->getSuperClass();
1811 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001812 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001813 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001814 PE = OC->protocol_end(); P != PE; ++P) {
1815 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001816 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001817 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1818 PE = Proto->protocol_end(); P != PE; ++P)
1819 CollectInheritedProtocols(*P, Protocols);
1820 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001821 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001822 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1823 PE = OP->protocol_end(); P != PE; ++P) {
1824 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001825 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001826 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1827 PE = Proto->protocol_end(); P != PE; ++P)
1828 CollectInheritedProtocols(*P, Protocols);
1829 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001830 }
1831}
1832
Jay Foad4ba2a172011-01-12 09:06:06 +00001833unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001834 unsigned count = 0;
1835 // Count ivars declared in class extension.
Douglas Gregord3297242013-01-16 23:00:23 +00001836 for (ObjCInterfaceDecl::known_extensions_iterator
1837 Ext = OI->known_extensions_begin(),
1838 ExtEnd = OI->known_extensions_end();
1839 Ext != ExtEnd; ++Ext) {
1840 count += Ext->ivar_size();
1841 }
1842
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001843 // Count ivar defined in this class's implementation. This
1844 // includes synthesized ivars.
1845 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001846 count += ImplDecl->ivar_size();
1847
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001848 return count;
1849}
1850
Argyrios Kyrtzidis8deabc12012-02-03 05:58:16 +00001851bool ASTContext::isSentinelNullExpr(const Expr *E) {
1852 if (!E)
1853 return false;
1854
1855 // nullptr_t is always treated as null.
1856 if (E->getType()->isNullPtrType()) return true;
1857
1858 if (E->getType()->isAnyPointerType() &&
1859 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1860 Expr::NPC_ValueDependentIsNull))
1861 return true;
1862
1863 // Unfortunately, __null has type 'int'.
1864 if (isa<GNUNullExpr>(E)) return true;
1865
1866 return false;
1867}
1868
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +00001869/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1870ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1871 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1872 I = ObjCImpls.find(D);
1873 if (I != ObjCImpls.end())
1874 return cast<ObjCImplementationDecl>(I->second);
1875 return 0;
1876}
1877/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1878ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1879 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1880 I = ObjCImpls.find(D);
1881 if (I != ObjCImpls.end())
1882 return cast<ObjCCategoryImplDecl>(I->second);
1883 return 0;
1884}
1885
1886/// \brief Set the implementation of ObjCInterfaceDecl.
1887void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1888 ObjCImplementationDecl *ImplD) {
1889 assert(IFaceD && ImplD && "Passed null params");
1890 ObjCImpls[IFaceD] = ImplD;
1891}
1892/// \brief Set the implementation of ObjCCategoryDecl.
1893void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1894 ObjCCategoryImplDecl *ImplD) {
1895 assert(CatD && ImplD && "Passed null params");
1896 ObjCImpls[CatD] = ImplD;
1897}
1898
Dmitri Gribenkob35cc2d2013-02-03 13:23:21 +00001899const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
1900 const NamedDecl *ND) const {
1901 if (const ObjCInterfaceDecl *ID =
1902 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001903 return ID;
Dmitri Gribenkob35cc2d2013-02-03 13:23:21 +00001904 if (const ObjCCategoryDecl *CD =
1905 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001906 return CD->getClassInterface();
Dmitri Gribenkob35cc2d2013-02-03 13:23:21 +00001907 if (const ObjCImplDecl *IMD =
1908 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001909 return IMD->getClassInterface();
1910
1911 return 0;
1912}
1913
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001914/// \brief Get the copy initialization expression of VarDecl,or NULL if
1915/// none exists.
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001916Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001917 assert(VD && "Passed null params");
1918 assert(VD->hasAttr<BlocksAttr>() &&
1919 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001920 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001921 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001922 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1923}
1924
1925/// \brief Set the copy inialization expression of a block var decl.
1926void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1927 assert(VD && Init && "Passed null params");
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001928 assert(VD->hasAttr<BlocksAttr>() &&
1929 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001930 BlockVarCopyInits[VD] = Init;
1931}
1932
John McCalla93c9342009-12-07 02:54:59 +00001933TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001934 unsigned DataSize) const {
John McCall109de5e2009-10-21 00:23:54 +00001935 if (!DataSize)
1936 DataSize = TypeLoc::getFullDataSizeForType(T);
1937 else
1938 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001939 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001940
John McCalla93c9342009-12-07 02:54:59 +00001941 TypeSourceInfo *TInfo =
1942 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1943 new (TInfo) TypeSourceInfo(T);
1944 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001945}
1946
John McCalla93c9342009-12-07 02:54:59 +00001947TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001948 SourceLocation L) const {
John McCalla93c9342009-12-07 02:54:59 +00001949 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregorc21c7e92011-01-25 19:13:18 +00001950 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCalla4eb74d2009-10-23 21:14:09 +00001951 return DI;
1952}
1953
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001954const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001955ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001956 return getObjCLayout(D, 0);
1957}
1958
1959const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001960ASTContext::getASTObjCImplementationLayout(
1961 const ObjCImplementationDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001962 return getObjCLayout(D->getClassInterface(), D);
1963}
1964
Chris Lattnera7674d82007-07-13 22:13:22 +00001965//===----------------------------------------------------------------------===//
1966// Type creation/memoization methods
1967//===----------------------------------------------------------------------===//
1968
Jay Foad4ba2a172011-01-12 09:06:06 +00001969QualType
John McCall3b657512011-01-19 10:06:00 +00001970ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1971 unsigned fastQuals = quals.getFastQualifiers();
1972 quals.removeFastQualifiers();
John McCall0953e762009-09-24 19:53:00 +00001973
1974 // Check if we've already instantiated this type.
1975 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001976 ExtQuals::Profile(ID, baseType, quals);
1977 void *insertPos = 0;
1978 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1979 assert(eq->getQualifiers() == quals);
1980 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001981 }
1982
John McCall3b657512011-01-19 10:06:00 +00001983 // If the base type is not canonical, make the appropriate canonical type.
1984 QualType canon;
1985 if (!baseType->isCanonicalUnqualified()) {
1986 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall200fa532012-02-08 00:46:36 +00001987 canonSplit.Quals.addConsistentQualifiers(quals);
1988 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00001989
1990 // Re-find the insert position.
1991 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1992 }
1993
1994 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1995 ExtQualNodes.InsertNode(eq, insertPos);
1996 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001997}
1998
Jay Foad4ba2a172011-01-12 09:06:06 +00001999QualType
2000ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002001 QualType CanT = getCanonicalType(T);
2002 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00002003 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00002004
John McCall0953e762009-09-24 19:53:00 +00002005 // If we are composing extended qualifiers together, merge together
2006 // into one ExtQuals node.
2007 QualifierCollector Quals;
2008 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002009
John McCall0953e762009-09-24 19:53:00 +00002010 // If this type already has an address space specified, it cannot get
2011 // another one.
2012 assert(!Quals.hasAddressSpace() &&
2013 "Type cannot be in multiple addr spaces!");
2014 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00002015
John McCall0953e762009-09-24 19:53:00 +00002016 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00002017}
2018
Chris Lattnerb7d25532009-02-18 22:53:11 +00002019QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00002020 Qualifiers::GC GCAttr) const {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00002021 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00002022 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00002023 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00002024
John McCall7f040a92010-12-24 02:08:15 +00002025 if (const PointerType *ptr = T->getAs<PointerType>()) {
2026 QualType Pointee = ptr->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00002027 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00002028 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2029 return getPointerType(ResultType);
2030 }
2031 }
Mike Stump1eb44332009-09-09 15:08:12 +00002032
John McCall0953e762009-09-24 19:53:00 +00002033 // If we are composing extended qualifiers together, merge together
2034 // into one ExtQuals node.
2035 QualifierCollector Quals;
2036 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002037
John McCall0953e762009-09-24 19:53:00 +00002038 // If this type already has an ObjCGC specified, it cannot get
2039 // another one.
2040 assert(!Quals.hasObjCGCAttr() &&
2041 "Type cannot have multiple ObjCGCs!");
2042 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00002043
John McCall0953e762009-09-24 19:53:00 +00002044 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00002045}
Chris Lattnera7674d82007-07-13 22:13:22 +00002046
John McCalle6a365d2010-12-19 02:44:49 +00002047const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2048 FunctionType::ExtInfo Info) {
2049 if (T->getExtInfo() == Info)
2050 return T;
2051
2052 QualType Result;
2053 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
2054 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
2055 } else {
2056 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2057 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2058 EPI.ExtInfo = Info;
Reid Kleckner0567a792013-06-10 20:51:09 +00002059 Result = getFunctionType(FPT->getResultType(), FPT->getArgTypes(), EPI);
John McCalle6a365d2010-12-19 02:44:49 +00002060 }
2061
2062 return cast<FunctionType>(Result.getTypePtr());
2063}
2064
Richard Smith60e141e2013-05-04 07:00:32 +00002065void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2066 QualType ResultType) {
Richard Smith9dadfab2013-05-11 05:45:24 +00002067 FD = FD->getMostRecentDecl();
2068 while (true) {
Richard Smith60e141e2013-05-04 07:00:32 +00002069 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2070 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2071 FD->setType(getFunctionType(ResultType, FPT->getArgTypes(), EPI));
Richard Smith9dadfab2013-05-11 05:45:24 +00002072 if (FunctionDecl *Next = FD->getPreviousDecl())
2073 FD = Next;
2074 else
2075 break;
Richard Smith60e141e2013-05-04 07:00:32 +00002076 }
Richard Smith9dadfab2013-05-11 05:45:24 +00002077 if (ASTMutationListener *L = getASTMutationListener())
2078 L->DeducedReturnType(FD, ResultType);
Richard Smith60e141e2013-05-04 07:00:32 +00002079}
2080
Reid Spencer5f016e22007-07-11 17:01:13 +00002081/// getComplexType - Return the uniqued reference to the type for a complex
2082/// number with the specified element type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002083QualType ASTContext::getComplexType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002084 // Unique pointers, to guarantee there is only one pointer of a particular
2085 // structure.
2086 llvm::FoldingSetNodeID ID;
2087 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00002088
Reid Spencer5f016e22007-07-11 17:01:13 +00002089 void *InsertPos = 0;
2090 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2091 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002092
Reid Spencer5f016e22007-07-11 17:01:13 +00002093 // If the pointee type isn't canonical, this won't be a canonical type either,
2094 // so fill in the canonical type field.
2095 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002096 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002097 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00002098
Reid Spencer5f016e22007-07-11 17:01:13 +00002099 // Get the new insert position for the node we care about.
2100 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002101 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002102 }
John McCall6b304a02009-09-24 23:30:46 +00002103 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00002104 Types.push_back(New);
2105 ComplexTypes.InsertNode(New, InsertPos);
2106 return QualType(New, 0);
2107}
2108
Reid Spencer5f016e22007-07-11 17:01:13 +00002109/// getPointerType - Return the uniqued reference to the type for a pointer to
2110/// the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002111QualType ASTContext::getPointerType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002112 // Unique pointers, to guarantee there is only one pointer of a particular
2113 // structure.
2114 llvm::FoldingSetNodeID ID;
2115 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00002116
Reid Spencer5f016e22007-07-11 17:01:13 +00002117 void *InsertPos = 0;
2118 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2119 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002120
Reid Spencer5f016e22007-07-11 17:01:13 +00002121 // If the pointee type isn't canonical, this won't be a canonical type either,
2122 // so fill in the canonical type field.
2123 QualType Canonical;
Bob Wilsonc90cc932013-03-15 17:12:43 +00002124 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002125 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00002126
Bob Wilsonc90cc932013-03-15 17:12:43 +00002127 // Get the new insert position for the node we care about.
2128 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2129 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2130 }
John McCall6b304a02009-09-24 23:30:46 +00002131 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00002132 Types.push_back(New);
2133 PointerTypes.InsertNode(New, InsertPos);
2134 return QualType(New, 0);
2135}
2136
Reid Kleckner12df2462013-06-24 17:51:48 +00002137QualType ASTContext::getDecayedType(QualType T) const {
2138 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2139
2140 llvm::FoldingSetNodeID ID;
2141 DecayedType::Profile(ID, T);
2142 void *InsertPos = 0;
2143 if (DecayedType *DT = DecayedTypes.FindNodeOrInsertPos(ID, InsertPos))
2144 return QualType(DT, 0);
2145
2146 QualType Decayed;
2147
2148 // C99 6.7.5.3p7:
2149 // A declaration of a parameter as "array of type" shall be
2150 // adjusted to "qualified pointer to type", where the type
2151 // qualifiers (if any) are those specified within the [ and ] of
2152 // the array type derivation.
2153 if (T->isArrayType())
2154 Decayed = getArrayDecayedType(T);
2155
2156 // C99 6.7.5.3p8:
2157 // A declaration of a parameter as "function returning type"
2158 // shall be adjusted to "pointer to function returning type", as
2159 // in 6.3.2.1.
2160 if (T->isFunctionType())
2161 Decayed = getPointerType(T);
2162
2163 QualType Canonical = getCanonicalType(Decayed);
2164
2165 // Get the new insert position for the node we care about.
2166 DecayedType *NewIP = DecayedTypes.FindNodeOrInsertPos(ID, InsertPos);
2167 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2168
2169 DecayedType *New =
2170 new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2171 Types.push_back(New);
2172 DecayedTypes.InsertNode(New, InsertPos);
2173 return QualType(New, 0);
2174}
2175
Mike Stump1eb44332009-09-09 15:08:12 +00002176/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00002177/// a pointer to the specified block.
Jay Foad4ba2a172011-01-12 09:06:06 +00002178QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff296e8d52008-08-28 19:20:44 +00002179 assert(T->isFunctionType() && "block of function types only");
2180 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00002181 // structure.
2182 llvm::FoldingSetNodeID ID;
2183 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00002184
Steve Naroff5618bd42008-08-27 16:04:49 +00002185 void *InsertPos = 0;
2186 if (BlockPointerType *PT =
2187 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2188 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002189
2190 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00002191 // type either so fill in the canonical type field.
2192 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002193 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00002194 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00002195
Steve Naroff5618bd42008-08-27 16:04:49 +00002196 // Get the new insert position for the node we care about.
2197 BlockPointerType *NewIP =
2198 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002199 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00002200 }
John McCall6b304a02009-09-24 23:30:46 +00002201 BlockPointerType *New
2202 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00002203 Types.push_back(New);
2204 BlockPointerTypes.InsertNode(New, InsertPos);
2205 return QualType(New, 0);
2206}
2207
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002208/// getLValueReferenceType - Return the uniqued reference to the type for an
2209/// lvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002210QualType
2211ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor9625e442011-05-21 22:16:50 +00002212 assert(getCanonicalType(T) != OverloadTy &&
2213 "Unresolved overloaded function type");
2214
Reid Spencer5f016e22007-07-11 17:01:13 +00002215 // Unique pointers, to guarantee there is only one pointer of a particular
2216 // structure.
2217 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00002218 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00002219
2220 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002221 if (LValueReferenceType *RT =
2222 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002223 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002224
John McCall54e14c42009-10-22 22:37:11 +00002225 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2226
Reid Spencer5f016e22007-07-11 17:01:13 +00002227 // If the referencee type isn't canonical, this won't be a canonical type
2228 // either, so fill in the canonical type field.
2229 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00002230 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2231 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2232 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002233
Reid Spencer5f016e22007-07-11 17:01:13 +00002234 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002235 LValueReferenceType *NewIP =
2236 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002237 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002238 }
2239
John McCall6b304a02009-09-24 23:30:46 +00002240 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00002241 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2242 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00002243 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002244 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00002245
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002246 return QualType(New, 0);
2247}
2248
2249/// getRValueReferenceType - Return the uniqued reference to the type for an
2250/// rvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002251QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002252 // Unique pointers, to guarantee there is only one pointer of a particular
2253 // structure.
2254 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00002255 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002256
2257 void *InsertPos = 0;
2258 if (RValueReferenceType *RT =
2259 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2260 return QualType(RT, 0);
2261
John McCall54e14c42009-10-22 22:37:11 +00002262 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2263
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002264 // If the referencee type isn't canonical, this won't be a canonical type
2265 // either, so fill in the canonical type field.
2266 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00002267 if (InnerRef || !T.isCanonical()) {
2268 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2269 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002270
2271 // Get the new insert position for the node we care about.
2272 RValueReferenceType *NewIP =
2273 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002274 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002275 }
2276
John McCall6b304a02009-09-24 23:30:46 +00002277 RValueReferenceType *New
2278 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002279 Types.push_back(New);
2280 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002281 return QualType(New, 0);
2282}
2283
Sebastian Redlf30208a2009-01-24 21:16:55 +00002284/// getMemberPointerType - Return the uniqued reference to the type for a
2285/// member pointer to the specified type, in the specified class.
Jay Foad4ba2a172011-01-12 09:06:06 +00002286QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redlf30208a2009-01-24 21:16:55 +00002287 // Unique pointers, to guarantee there is only one pointer of a particular
2288 // structure.
2289 llvm::FoldingSetNodeID ID;
2290 MemberPointerType::Profile(ID, T, Cls);
2291
2292 void *InsertPos = 0;
2293 if (MemberPointerType *PT =
2294 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2295 return QualType(PT, 0);
2296
2297 // If the pointee or class type isn't canonical, this won't be a canonical
2298 // type either, so fill in the canonical type field.
2299 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00002300 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00002301 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2302
2303 // Get the new insert position for the node we care about.
2304 MemberPointerType *NewIP =
2305 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002306 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redlf30208a2009-01-24 21:16:55 +00002307 }
John McCall6b304a02009-09-24 23:30:46 +00002308 MemberPointerType *New
2309 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00002310 Types.push_back(New);
2311 MemberPointerTypes.InsertNode(New, InsertPos);
2312 return QualType(New, 0);
2313}
2314
Mike Stump1eb44332009-09-09 15:08:12 +00002315/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00002316/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002317QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00002318 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00002319 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002320 unsigned IndexTypeQuals) const {
Sebastian Redl923d56d2009-11-05 15:52:31 +00002321 assert((EltTy->isDependentType() ||
2322 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00002323 "Constant array of VLAs is illegal!");
2324
Chris Lattner38aeec72009-05-13 04:12:56 +00002325 // Convert the array size into a canonical width matching the pointer size for
2326 // the target.
2327 llvm::APInt ArySize(ArySizeIn);
Jay Foad9f71a8f2010-12-07 08:25:34 +00002328 ArySize =
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002329 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump1eb44332009-09-09 15:08:12 +00002330
Reid Spencer5f016e22007-07-11 17:01:13 +00002331 llvm::FoldingSetNodeID ID;
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002332 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00002333
Reid Spencer5f016e22007-07-11 17:01:13 +00002334 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002335 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002336 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002337 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002338
John McCall3b657512011-01-19 10:06:00 +00002339 // If the element type isn't canonical or has qualifiers, this won't
2340 // be a canonical type either, so fill in the canonical type field.
2341 QualType Canon;
2342 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2343 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00002344 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002345 ASM, IndexTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00002346 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00002347
Reid Spencer5f016e22007-07-11 17:01:13 +00002348 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00002349 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002350 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002351 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002352 }
Mike Stump1eb44332009-09-09 15:08:12 +00002353
John McCall6b304a02009-09-24 23:30:46 +00002354 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002355 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002356 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002357 Types.push_back(New);
2358 return QualType(New, 0);
2359}
2360
John McCallce889032011-01-18 08:40:38 +00002361/// getVariableArrayDecayedType - Turns the given type, which may be
2362/// variably-modified, into the corresponding type with all the known
2363/// sizes replaced with [*].
2364QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2365 // Vastly most common case.
2366 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002367
John McCallce889032011-01-18 08:40:38 +00002368 QualType result;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002369
John McCallce889032011-01-18 08:40:38 +00002370 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00002371 const Type *ty = split.Ty;
John McCallce889032011-01-18 08:40:38 +00002372 switch (ty->getTypeClass()) {
2373#define TYPE(Class, Base)
2374#define ABSTRACT_TYPE(Class, Base)
2375#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2376#include "clang/AST/TypeNodes.def"
2377 llvm_unreachable("didn't desugar past all non-canonical types?");
2378
2379 // These types should never be variably-modified.
2380 case Type::Builtin:
2381 case Type::Complex:
2382 case Type::Vector:
2383 case Type::ExtVector:
2384 case Type::DependentSizedExtVector:
2385 case Type::ObjCObject:
2386 case Type::ObjCInterface:
2387 case Type::ObjCObjectPointer:
2388 case Type::Record:
2389 case Type::Enum:
2390 case Type::UnresolvedUsing:
2391 case Type::TypeOfExpr:
2392 case Type::TypeOf:
2393 case Type::Decltype:
Sean Huntca63c202011-05-24 22:41:36 +00002394 case Type::UnaryTransform:
John McCallce889032011-01-18 08:40:38 +00002395 case Type::DependentName:
2396 case Type::InjectedClassName:
2397 case Type::TemplateSpecialization:
2398 case Type::DependentTemplateSpecialization:
2399 case Type::TemplateTypeParm:
2400 case Type::SubstTemplateTypeParmPack:
Richard Smith34b41d92011-02-20 03:19:35 +00002401 case Type::Auto:
John McCallce889032011-01-18 08:40:38 +00002402 case Type::PackExpansion:
2403 llvm_unreachable("type should never be variably-modified");
2404
2405 // These types can be variably-modified but should never need to
2406 // further decay.
2407 case Type::FunctionNoProto:
2408 case Type::FunctionProto:
2409 case Type::BlockPointer:
2410 case Type::MemberPointer:
2411 return type;
2412
2413 // These types can be variably-modified. All these modifications
2414 // preserve structure except as noted by comments.
2415 // TODO: if we ever care about optimizing VLAs, there are no-op
2416 // optimizations available here.
2417 case Type::Pointer:
2418 result = getPointerType(getVariableArrayDecayedType(
2419 cast<PointerType>(ty)->getPointeeType()));
2420 break;
2421
2422 case Type::LValueReference: {
2423 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2424 result = getLValueReferenceType(
2425 getVariableArrayDecayedType(lv->getPointeeType()),
2426 lv->isSpelledAsLValue());
2427 break;
2428 }
2429
2430 case Type::RValueReference: {
2431 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2432 result = getRValueReferenceType(
2433 getVariableArrayDecayedType(lv->getPointeeType()));
2434 break;
2435 }
2436
Eli Friedmanb001de72011-10-06 23:00:33 +00002437 case Type::Atomic: {
2438 const AtomicType *at = cast<AtomicType>(ty);
2439 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2440 break;
2441 }
2442
John McCallce889032011-01-18 08:40:38 +00002443 case Type::ConstantArray: {
2444 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2445 result = getConstantArrayType(
2446 getVariableArrayDecayedType(cat->getElementType()),
2447 cat->getSize(),
2448 cat->getSizeModifier(),
2449 cat->getIndexTypeCVRQualifiers());
2450 break;
2451 }
2452
2453 case Type::DependentSizedArray: {
2454 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2455 result = getDependentSizedArrayType(
2456 getVariableArrayDecayedType(dat->getElementType()),
2457 dat->getSizeExpr(),
2458 dat->getSizeModifier(),
2459 dat->getIndexTypeCVRQualifiers(),
2460 dat->getBracketsRange());
2461 break;
2462 }
2463
2464 // Turn incomplete types into [*] types.
2465 case Type::IncompleteArray: {
2466 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2467 result = getVariableArrayType(
2468 getVariableArrayDecayedType(iat->getElementType()),
2469 /*size*/ 0,
2470 ArrayType::Normal,
2471 iat->getIndexTypeCVRQualifiers(),
2472 SourceRange());
2473 break;
2474 }
2475
2476 // Turn VLA types into [*] types.
2477 case Type::VariableArray: {
2478 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2479 result = getVariableArrayType(
2480 getVariableArrayDecayedType(vat->getElementType()),
2481 /*size*/ 0,
2482 ArrayType::Star,
2483 vat->getIndexTypeCVRQualifiers(),
2484 vat->getBracketsRange());
2485 break;
2486 }
2487 }
2488
2489 // Apply the top-level qualifiers from the original.
John McCall200fa532012-02-08 00:46:36 +00002490 return getQualifiedType(result, split.Quals);
John McCallce889032011-01-18 08:40:38 +00002491}
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002492
Steve Naroffbdbf7b02007-08-30 18:14:25 +00002493/// getVariableArrayType - Returns a non-unique reference to the type for a
2494/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002495QualType ASTContext::getVariableArrayType(QualType EltTy,
2496 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00002497 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002498 unsigned IndexTypeQuals,
Jay Foad4ba2a172011-01-12 09:06:06 +00002499 SourceRange Brackets) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00002500 // Since we don't unique expressions, it isn't possible to unique VLA's
2501 // that have an expression provided for their size.
John McCall3b657512011-01-19 10:06:00 +00002502 QualType Canon;
Douglas Gregor715e9c82010-05-23 16:10:32 +00002503
John McCall3b657512011-01-19 10:06:00 +00002504 // Be sure to pull qualifiers off the element type.
2505 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2506 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00002507 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002508 IndexTypeQuals, Brackets);
John McCall200fa532012-02-08 00:46:36 +00002509 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor715e9c82010-05-23 16:10:32 +00002510 }
2511
John McCall6b304a02009-09-24 23:30:46 +00002512 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002513 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002514
2515 VariableArrayTypes.push_back(New);
2516 Types.push_back(New);
2517 return QualType(New, 0);
2518}
2519
Douglas Gregor898574e2008-12-05 23:32:09 +00002520/// getDependentSizedArrayType - Returns a non-unique reference to
2521/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00002522/// type.
John McCall3b657512011-01-19 10:06:00 +00002523QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2524 Expr *numElements,
Douglas Gregor898574e2008-12-05 23:32:09 +00002525 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00002526 unsigned elementTypeQuals,
2527 SourceRange brackets) const {
2528 assert((!numElements || numElements->isTypeDependent() ||
2529 numElements->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00002530 "Size must be type- or value-dependent!");
2531
John McCall3b657512011-01-19 10:06:00 +00002532 // Dependently-sized array types that do not have a specified number
2533 // of elements will have their sizes deduced from a dependent
2534 // initializer. We do no canonicalization here at all, which is okay
2535 // because they can't be used in most locations.
2536 if (!numElements) {
2537 DependentSizedArrayType *newType
2538 = new (*this, TypeAlignment)
2539 DependentSizedArrayType(*this, elementType, QualType(),
2540 numElements, ASM, elementTypeQuals,
2541 brackets);
2542 Types.push_back(newType);
2543 return QualType(newType, 0);
2544 }
2545
2546 // Otherwise, we actually build a new type every time, but we
2547 // also build a canonical type.
2548
2549 SplitQualType canonElementType = getCanonicalType(elementType).split();
2550
2551 void *insertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00002552 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00002553 DependentSizedArrayType::Profile(ID, *this,
John McCall200fa532012-02-08 00:46:36 +00002554 QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002555 ASM, elementTypeQuals, numElements);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002556
John McCall3b657512011-01-19 10:06:00 +00002557 // Look for an existing type with these properties.
2558 DependentSizedArrayType *canonTy =
2559 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002560
John McCall3b657512011-01-19 10:06:00 +00002561 // If we don't have one, build one.
2562 if (!canonTy) {
2563 canonTy = new (*this, TypeAlignment)
John McCall200fa532012-02-08 00:46:36 +00002564 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002565 QualType(), numElements, ASM, elementTypeQuals,
2566 brackets);
2567 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2568 Types.push_back(canonTy);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002569 }
2570
John McCall3b657512011-01-19 10:06:00 +00002571 // Apply qualifiers from the element type to the array.
2572 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall200fa532012-02-08 00:46:36 +00002573 canonElementType.Quals);
Mike Stump1eb44332009-09-09 15:08:12 +00002574
John McCall3b657512011-01-19 10:06:00 +00002575 // If we didn't need extra canonicalization for the element type,
2576 // then just use that as our result.
John McCall200fa532012-02-08 00:46:36 +00002577 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall3b657512011-01-19 10:06:00 +00002578 return canon;
2579
2580 // Otherwise, we need to build a type which follows the spelling
2581 // of the element type.
2582 DependentSizedArrayType *sugaredType
2583 = new (*this, TypeAlignment)
2584 DependentSizedArrayType(*this, elementType, canon, numElements,
2585 ASM, elementTypeQuals, brackets);
2586 Types.push_back(sugaredType);
2587 return QualType(sugaredType, 0);
Douglas Gregor898574e2008-12-05 23:32:09 +00002588}
2589
John McCall3b657512011-01-19 10:06:00 +00002590QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanc5773c42008-02-15 18:16:39 +00002591 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00002592 unsigned elementTypeQuals) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00002593 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00002594 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002595
John McCall3b657512011-01-19 10:06:00 +00002596 void *insertPos = 0;
2597 if (IncompleteArrayType *iat =
2598 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2599 return QualType(iat, 0);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002600
2601 // If the element type isn't canonical, this won't be a canonical type
John McCall3b657512011-01-19 10:06:00 +00002602 // either, so fill in the canonical type field. We also have to pull
2603 // qualifiers off the element type.
2604 QualType canon;
Eli Friedmanc5773c42008-02-15 18:16:39 +00002605
John McCall3b657512011-01-19 10:06:00 +00002606 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2607 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall200fa532012-02-08 00:46:36 +00002608 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002609 ASM, elementTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00002610 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002611
2612 // Get the new insert position for the node we care about.
John McCall3b657512011-01-19 10:06:00 +00002613 IncompleteArrayType *existing =
2614 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2615 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00002616 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00002617
John McCall3b657512011-01-19 10:06:00 +00002618 IncompleteArrayType *newType = new (*this, TypeAlignment)
2619 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002620
John McCall3b657512011-01-19 10:06:00 +00002621 IncompleteArrayTypes.InsertNode(newType, insertPos);
2622 Types.push_back(newType);
2623 return QualType(newType, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00002624}
2625
Steve Naroff73322922007-07-18 18:00:27 +00002626/// getVectorType - Return the unique reference to a vector type of
2627/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00002628QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad4ba2a172011-01-12 09:06:06 +00002629 VectorType::VectorKind VecKind) const {
John McCall3b657512011-01-19 10:06:00 +00002630 assert(vecType->isBuiltinType());
Mike Stump1eb44332009-09-09 15:08:12 +00002631
Reid Spencer5f016e22007-07-11 17:01:13 +00002632 // Check if we've already instantiated a vector of this type.
2633 llvm::FoldingSetNodeID ID;
Bob Wilsone86d78c2010-11-10 21:56:12 +00002634 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner788b0fd2010-06-23 06:00:24 +00002635
Reid Spencer5f016e22007-07-11 17:01:13 +00002636 void *InsertPos = 0;
2637 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2638 return QualType(VTP, 0);
2639
2640 // If the element type isn't canonical, this won't be a canonical type either,
2641 // so fill in the canonical type field.
2642 QualType Canonical;
Douglas Gregor255210e2010-08-06 10:14:59 +00002643 if (!vecType.isCanonical()) {
Bob Wilson231da7e2010-11-16 00:32:20 +00002644 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump1eb44332009-09-09 15:08:12 +00002645
Reid Spencer5f016e22007-07-11 17:01:13 +00002646 // Get the new insert position for the node we care about.
2647 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002648 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002649 }
John McCall6b304a02009-09-24 23:30:46 +00002650 VectorType *New = new (*this, TypeAlignment)
Bob Wilsone86d78c2010-11-10 21:56:12 +00002651 VectorType(vecType, NumElts, Canonical, VecKind);
Reid Spencer5f016e22007-07-11 17:01:13 +00002652 VectorTypes.InsertNode(New, InsertPos);
2653 Types.push_back(New);
2654 return QualType(New, 0);
2655}
2656
Nate Begeman213541a2008-04-18 23:10:10 +00002657/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00002658/// the specified element type and size. VectorType must be a built-in type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002659QualType
2660ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor4ac01402011-06-15 16:02:29 +00002661 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump1eb44332009-09-09 15:08:12 +00002662
Steve Naroff73322922007-07-18 18:00:27 +00002663 // Check if we've already instantiated a vector of this type.
2664 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00002665 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsone86d78c2010-11-10 21:56:12 +00002666 VectorType::GenericVector);
Steve Naroff73322922007-07-18 18:00:27 +00002667 void *InsertPos = 0;
2668 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2669 return QualType(VTP, 0);
2670
2671 // If the element type isn't canonical, this won't be a canonical type either,
2672 // so fill in the canonical type field.
2673 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002674 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00002675 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00002676
Steve Naroff73322922007-07-18 18:00:27 +00002677 // Get the new insert position for the node we care about.
2678 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002679 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00002680 }
John McCall6b304a02009-09-24 23:30:46 +00002681 ExtVectorType *New = new (*this, TypeAlignment)
2682 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00002683 VectorTypes.InsertNode(New, InsertPos);
2684 Types.push_back(New);
2685 return QualType(New, 0);
2686}
2687
Jay Foad4ba2a172011-01-12 09:06:06 +00002688QualType
2689ASTContext::getDependentSizedExtVectorType(QualType vecType,
2690 Expr *SizeExpr,
2691 SourceLocation AttrLoc) const {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002692 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00002693 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002694 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002695
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002696 void *InsertPos = 0;
2697 DependentSizedExtVectorType *Canon
2698 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2699 DependentSizedExtVectorType *New;
2700 if (Canon) {
2701 // We already have a canonical version of this array type; use it as
2702 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00002703 New = new (*this, TypeAlignment)
2704 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2705 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002706 } else {
2707 QualType CanonVecTy = getCanonicalType(vecType);
2708 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00002709 New = new (*this, TypeAlignment)
2710 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2711 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002712
2713 DependentSizedExtVectorType *CanonCheck
2714 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2715 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2716 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002717 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2718 } else {
2719 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2720 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00002721 New = new (*this, TypeAlignment)
2722 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002723 }
2724 }
Mike Stump1eb44332009-09-09 15:08:12 +00002725
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00002726 Types.push_back(New);
2727 return QualType(New, 0);
2728}
2729
Douglas Gregor72564e72009-02-26 23:50:07 +00002730/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00002731///
Jay Foad4ba2a172011-01-12 09:06:06 +00002732QualType
2733ASTContext::getFunctionNoProtoType(QualType ResultTy,
2734 const FunctionType::ExtInfo &Info) const {
Reid Kleckneref072032013-08-27 23:08:25 +00002735 const CallingConv CallConv = Info.getCC();
2736
Reid Spencer5f016e22007-07-11 17:01:13 +00002737 // Unique functions, to guarantee there is only one function of a particular
2738 // structure.
2739 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00002740 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00002741
Reid Spencer5f016e22007-07-11 17:01:13 +00002742 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002743 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00002744 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002745 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002746
Reid Spencer5f016e22007-07-11 17:01:13 +00002747 QualType Canonical;
Reid Kleckneref072032013-08-27 23:08:25 +00002748 if (!ResultTy.isCanonical()) {
2749 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), Info);
Mike Stump1eb44332009-09-09 15:08:12 +00002750
Reid Spencer5f016e22007-07-11 17:01:13 +00002751 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002752 FunctionNoProtoType *NewIP =
2753 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002754 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002755 }
Mike Stump1eb44332009-09-09 15:08:12 +00002756
Roman Divackycfe9af22011-03-01 17:40:53 +00002757 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall6b304a02009-09-24 23:30:46 +00002758 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divackycfe9af22011-03-01 17:40:53 +00002759 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00002760 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00002761 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002762 return QualType(New, 0);
2763}
2764
Douglas Gregor02dd7982013-01-17 23:36:45 +00002765/// \brief Determine whether \p T is canonical as the result type of a function.
2766static bool isCanonicalResultType(QualType T) {
2767 return T.isCanonical() &&
2768 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2769 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2770}
2771
Reid Spencer5f016e22007-07-11 17:01:13 +00002772/// getFunctionType - Return a normal function type with a typed argument
2773/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad4ba2a172011-01-12 09:06:06 +00002774QualType
Jordan Rosebea522f2013-03-08 21:51:21 +00002775ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad4ba2a172011-01-12 09:06:06 +00002776 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rosebea522f2013-03-08 21:51:21 +00002777 size_t NumArgs = ArgArray.size();
2778
Reid Spencer5f016e22007-07-11 17:01:13 +00002779 // Unique functions, to guarantee there is only one function of a particular
2780 // structure.
2781 llvm::FoldingSetNodeID ID;
Jordan Rosebea522f2013-03-08 21:51:21 +00002782 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
2783 *this);
Reid Spencer5f016e22007-07-11 17:01:13 +00002784
2785 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002786 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00002787 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002788 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00002789
2790 // Determine whether the type being created is already canonical or not.
Richard Smitheefb3d52012-02-10 09:58:53 +00002791 bool isCanonical =
Douglas Gregor02dd7982013-01-17 23:36:45 +00002792 EPI.ExceptionSpecType == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smitheefb3d52012-02-10 09:58:53 +00002793 !EPI.HasTrailingReturn;
Reid Spencer5f016e22007-07-11 17:01:13 +00002794 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002795 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00002796 isCanonical = false;
2797
2798 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00002799 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002800 QualType Canonical;
Reid Kleckneref072032013-08-27 23:08:25 +00002801 if (!isCanonical) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002802 SmallVector<QualType, 16> CanonicalArgs;
Reid Spencer5f016e22007-07-11 17:01:13 +00002803 CanonicalArgs.reserve(NumArgs);
2804 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002805 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00002806
John McCalle23cf432010-12-14 08:05:40 +00002807 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smitheefb3d52012-02-10 09:58:53 +00002808 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002809 CanonicalEPI.ExceptionSpecType = EST_None;
2810 CanonicalEPI.NumExceptions = 0;
John McCalle23cf432010-12-14 08:05:40 +00002811
Douglas Gregor02dd7982013-01-17 23:36:45 +00002812 // Result types do not have ARC lifetime qualifiers.
2813 QualType CanResultTy = getCanonicalType(ResultTy);
2814 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2815 Qualifiers Qs = CanResultTy.getQualifiers();
2816 Qs.removeObjCLifetime();
2817 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2818 }
2819
Jordan Rosebea522f2013-03-08 21:51:21 +00002820 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl465226e2009-05-27 22:11:52 +00002821
Reid Spencer5f016e22007-07-11 17:01:13 +00002822 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002823 FunctionProtoType *NewIP =
2824 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002825 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002826 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002827
John McCallf85e1932011-06-15 23:02:42 +00002828 // FunctionProtoType objects are allocated with extra bytes after
2829 // them for three variable size arrays at the end:
2830 // - parameter types
2831 // - exception types
2832 // - consumed-arguments flags
2833 // Instead of the exception types, there could be a noexcept
Richard Smithb9d0b762012-07-27 04:22:15 +00002834 // expression, or information used to resolve the exception
2835 // specification.
John McCalle23cf432010-12-14 08:05:40 +00002836 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redl60618fa2011-03-12 11:50:43 +00002837 NumArgs * sizeof(QualType);
Richard Smithb9d0b762012-07-27 04:22:15 +00002838 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redl60618fa2011-03-12 11:50:43 +00002839 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithb9d0b762012-07-27 04:22:15 +00002840 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002841 Size += sizeof(Expr*);
Richard Smithe6975e92012-04-17 00:58:00 +00002842 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smith13bffc52012-04-19 00:08:28 +00002843 Size += 2 * sizeof(FunctionDecl*);
Richard Smithb9d0b762012-07-27 04:22:15 +00002844 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2845 Size += sizeof(FunctionDecl*);
Sebastian Redl60618fa2011-03-12 11:50:43 +00002846 }
John McCallf85e1932011-06-15 23:02:42 +00002847 if (EPI.ConsumedArguments)
2848 Size += NumArgs * sizeof(bool);
2849
John McCalle23cf432010-12-14 08:05:40 +00002850 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divackycfe9af22011-03-01 17:40:53 +00002851 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rosebea522f2013-03-08 21:51:21 +00002852 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00002853 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00002854 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002855 return QualType(FTP, 0);
2856}
2857
John McCall3cb0ebd2010-03-10 03:28:59 +00002858#ifndef NDEBUG
2859static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2860 if (!isa<CXXRecordDecl>(D)) return false;
2861 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2862 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2863 return true;
2864 if (RD->getDescribedClassTemplate() &&
2865 !isa<ClassTemplateSpecializationDecl>(RD))
2866 return true;
2867 return false;
2868}
2869#endif
2870
2871/// getInjectedClassNameType - Return the unique reference to the
2872/// injected class name type for the specified templated declaration.
2873QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00002874 QualType TST) const {
John McCall3cb0ebd2010-03-10 03:28:59 +00002875 assert(NeedsInjectedClassNameType(Decl));
2876 if (Decl->TypeForDecl) {
2877 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregoref96ee02012-01-14 16:38:05 +00002878 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00002879 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2880 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2881 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2882 } else {
John McCallf4c73712011-01-19 06:33:43 +00002883 Type *newType =
John McCall31f17ec2010-04-27 00:57:59 +00002884 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCallf4c73712011-01-19 06:33:43 +00002885 Decl->TypeForDecl = newType;
2886 Types.push_back(newType);
John McCall3cb0ebd2010-03-10 03:28:59 +00002887 }
2888 return QualType(Decl->TypeForDecl, 0);
2889}
2890
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002891/// getTypeDeclType - Return the unique reference to the type for the
2892/// specified type declaration.
Jay Foad4ba2a172011-01-12 09:06:06 +00002893QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00002894 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00002895 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00002896
Richard Smith162e1c12011-04-15 14:24:37 +00002897 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002898 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00002899
John McCallbecb8d52010-03-10 06:48:02 +00002900 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2901 "Template type parameter types are always available.");
2902
John McCall19c85762010-02-16 03:57:14 +00002903 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002904 assert(!Record->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002905 "struct/union has previous declaration");
2906 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002907 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00002908 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002909 assert(!Enum->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002910 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002911 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00002912 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00002913 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCallf4c73712011-01-19 06:33:43 +00002914 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2915 Decl->TypeForDecl = newType;
2916 Types.push_back(newType);
Mike Stump9fdbab32009-07-31 02:02:20 +00002917 } else
John McCallbecb8d52010-03-10 06:48:02 +00002918 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002919
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002920 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002921}
2922
Reid Spencer5f016e22007-07-11 17:01:13 +00002923/// getTypedefType - Return the unique reference to the type for the
Richard Smith162e1c12011-04-15 14:24:37 +00002924/// specified typedef name decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002925QualType
Richard Smith162e1c12011-04-15 14:24:37 +00002926ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2927 QualType Canonical) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002928 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002929
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002930 if (Canonical.isNull())
2931 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCallf4c73712011-01-19 06:33:43 +00002932 TypedefType *newType = new(*this, TypeAlignment)
John McCall6b304a02009-09-24 23:30:46 +00002933 TypedefType(Type::Typedef, Decl, Canonical);
John McCallf4c73712011-01-19 06:33:43 +00002934 Decl->TypeForDecl = newType;
2935 Types.push_back(newType);
2936 return QualType(newType, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002937}
2938
Jay Foad4ba2a172011-01-12 09:06:06 +00002939QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002940 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2941
Douglas Gregoref96ee02012-01-14 16:38:05 +00002942 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002943 if (PrevDecl->TypeForDecl)
2944 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2945
John McCallf4c73712011-01-19 06:33:43 +00002946 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2947 Decl->TypeForDecl = newType;
2948 Types.push_back(newType);
2949 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002950}
2951
Jay Foad4ba2a172011-01-12 09:06:06 +00002952QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002953 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2954
Douglas Gregoref96ee02012-01-14 16:38:05 +00002955 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002956 if (PrevDecl->TypeForDecl)
2957 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2958
John McCallf4c73712011-01-19 06:33:43 +00002959 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2960 Decl->TypeForDecl = newType;
2961 Types.push_back(newType);
2962 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002963}
2964
John McCall9d156a72011-01-06 01:58:22 +00002965QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2966 QualType modifiedType,
2967 QualType equivalentType) {
2968 llvm::FoldingSetNodeID id;
2969 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2970
2971 void *insertPos = 0;
2972 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2973 if (type) return QualType(type, 0);
2974
2975 QualType canon = getCanonicalType(equivalentType);
2976 type = new (*this, TypeAlignment)
2977 AttributedType(canon, attrKind, modifiedType, equivalentType);
2978
2979 Types.push_back(type);
2980 AttributedTypes.InsertNode(type, insertPos);
2981
2982 return QualType(type, 0);
2983}
2984
2985
John McCall49a832b2009-10-18 09:09:24 +00002986/// \brief Retrieve a substitution-result type.
2987QualType
2988ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad4ba2a172011-01-12 09:06:06 +00002989 QualType Replacement) const {
John McCall467b27b2009-10-22 20:10:53 +00002990 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00002991 && "replacement types must always be canonical");
2992
2993 llvm::FoldingSetNodeID ID;
2994 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2995 void *InsertPos = 0;
2996 SubstTemplateTypeParmType *SubstParm
2997 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2998
2999 if (!SubstParm) {
3000 SubstParm = new (*this, TypeAlignment)
3001 SubstTemplateTypeParmType(Parm, Replacement);
3002 Types.push_back(SubstParm);
3003 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3004 }
3005
3006 return QualType(SubstParm, 0);
3007}
3008
Douglas Gregorc3069d62011-01-14 02:55:32 +00003009/// \brief Retrieve a
3010QualType ASTContext::getSubstTemplateTypeParmPackType(
3011 const TemplateTypeParmType *Parm,
3012 const TemplateArgument &ArgPack) {
3013#ifndef NDEBUG
3014 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
3015 PEnd = ArgPack.pack_end();
3016 P != PEnd; ++P) {
3017 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3018 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
3019 }
3020#endif
3021
3022 llvm::FoldingSetNodeID ID;
3023 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
3024 void *InsertPos = 0;
3025 if (SubstTemplateTypeParmPackType *SubstParm
3026 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3027 return QualType(SubstParm, 0);
3028
3029 QualType Canon;
3030 if (!Parm->isCanonicalUnqualified()) {
3031 Canon = getCanonicalType(QualType(Parm, 0));
3032 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3033 ArgPack);
3034 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3035 }
3036
3037 SubstTemplateTypeParmPackType *SubstParm
3038 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3039 ArgPack);
3040 Types.push_back(SubstParm);
3041 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3042 return QualType(SubstParm, 0);
3043}
3044
Douglas Gregorfab9d672009-02-05 23:33:38 +00003045/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00003046/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003047/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00003048QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003049 bool ParameterPack,
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003050 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregorfab9d672009-02-05 23:33:38 +00003051 llvm::FoldingSetNodeID ID;
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003052 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregorfab9d672009-02-05 23:33:38 +00003053 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003054 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00003055 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3056
3057 if (TypeParm)
3058 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00003059
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003060 if (TTPDecl) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003061 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003062 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003063
3064 TemplateTypeParmType *TypeCheck
3065 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3066 assert(!TypeCheck && "Template type parameter canonical type broken");
3067 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003068 } else
John McCall6b304a02009-09-24 23:30:46 +00003069 TypeParm = new (*this, TypeAlignment)
3070 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00003071
3072 Types.push_back(TypeParm);
3073 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3074
3075 return QualType(TypeParm, 0);
3076}
3077
John McCall3cb0ebd2010-03-10 03:28:59 +00003078TypeSourceInfo *
3079ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3080 SourceLocation NameLoc,
3081 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003082 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003083 assert(!Name.getAsDependentTemplateName() &&
3084 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00003085 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCall3cb0ebd2010-03-10 03:28:59 +00003086
3087 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie39e6ab42013-02-18 22:06:02 +00003088 TemplateSpecializationTypeLoc TL =
3089 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara55d23c92012-02-06 14:41:24 +00003090 TL.setTemplateKeywordLoc(SourceLocation());
John McCall3cb0ebd2010-03-10 03:28:59 +00003091 TL.setTemplateNameLoc(NameLoc);
3092 TL.setLAngleLoc(Args.getLAngleLoc());
3093 TL.setRAngleLoc(Args.getRAngleLoc());
3094 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3095 TL.setArgLocInfo(i, Args[i].getLocInfo());
3096 return DI;
3097}
3098
Mike Stump1eb44332009-09-09 15:08:12 +00003099QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00003100ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00003101 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003102 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003103 assert(!Template.getAsDependentTemplateName() &&
3104 "No dependent template names here!");
3105
John McCalld5532b62009-11-23 01:53:49 +00003106 unsigned NumArgs = Args.size();
3107
Chris Lattner5f9e2722011-07-23 10:55:15 +00003108 SmallVector<TemplateArgument, 4> ArgVec;
John McCall833ca992009-10-29 08:12:44 +00003109 ArgVec.reserve(NumArgs);
3110 for (unsigned i = 0; i != NumArgs; ++i)
3111 ArgVec.push_back(Args[i].getArgument());
3112
John McCall31f17ec2010-04-27 00:57:59 +00003113 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003114 Underlying);
John McCall833ca992009-10-29 08:12:44 +00003115}
3116
Douglas Gregorb70126a2012-02-03 17:16:23 +00003117#ifndef NDEBUG
3118static bool hasAnyPackExpansions(const TemplateArgument *Args,
3119 unsigned NumArgs) {
3120 for (unsigned I = 0; I != NumArgs; ++I)
3121 if (Args[I].isPackExpansion())
3122 return true;
3123
3124 return true;
3125}
3126#endif
3127
John McCall833ca992009-10-29 08:12:44 +00003128QualType
3129ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003130 const TemplateArgument *Args,
3131 unsigned NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003132 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003133 assert(!Template.getAsDependentTemplateName() &&
3134 "No dependent template names here!");
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00003135 // Look through qualified template names.
3136 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3137 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003138
Douglas Gregorb70126a2012-02-03 17:16:23 +00003139 bool IsTypeAlias =
Richard Smith3e4c6c42011-05-05 21:57:07 +00003140 Template.getAsTemplateDecl() &&
3141 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00003142 QualType CanonType;
3143 if (!Underlying.isNull())
3144 CanonType = getCanonicalType(Underlying);
3145 else {
Douglas Gregorb70126a2012-02-03 17:16:23 +00003146 // We can get here with an alias template when the specialization contains
3147 // a pack expansion that does not match up with a parameter pack.
3148 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3149 "Caller must compute aliased type");
3150 IsTypeAlias = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00003151 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3152 NumArgs);
3153 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00003154
Douglas Gregor1275ae02009-07-28 23:00:59 +00003155 // Allocate the (non-canonical) template specialization type, but don't
3156 // try to unique it: these types typically have location information that
3157 // we don't unique and don't want to lose.
Richard Smith3e4c6c42011-05-05 21:57:07 +00003158 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3159 sizeof(TemplateArgument) * NumArgs +
Douglas Gregorb70126a2012-02-03 17:16:23 +00003160 (IsTypeAlias? sizeof(QualType) : 0),
John McCall6b304a02009-09-24 23:30:46 +00003161 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00003162 TemplateSpecializationType *Spec
Douglas Gregorb70126a2012-02-03 17:16:23 +00003163 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3164 IsTypeAlias ? Underlying : QualType());
Mike Stump1eb44332009-09-09 15:08:12 +00003165
Douglas Gregor55f6b142009-02-09 18:46:07 +00003166 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00003167 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00003168}
3169
Mike Stump1eb44332009-09-09 15:08:12 +00003170QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003171ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3172 const TemplateArgument *Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00003173 unsigned NumArgs) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003174 assert(!Template.getAsDependentTemplateName() &&
3175 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00003176
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00003177 // Look through qualified template names.
3178 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3179 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003180
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003181 // Build the canonical template specialization type.
3182 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003183 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003184 CanonArgs.reserve(NumArgs);
3185 for (unsigned I = 0; I != NumArgs; ++I)
3186 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3187
3188 // Determine whether this canonical template specialization type already
3189 // exists.
3190 llvm::FoldingSetNodeID ID;
3191 TemplateSpecializationType::Profile(ID, CanonTemplate,
3192 CanonArgs.data(), NumArgs, *this);
3193
3194 void *InsertPos = 0;
3195 TemplateSpecializationType *Spec
3196 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3197
3198 if (!Spec) {
3199 // Allocate a new canonical template specialization type.
3200 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3201 sizeof(TemplateArgument) * NumArgs),
3202 TypeAlignment);
3203 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3204 CanonArgs.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003205 QualType(), QualType());
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003206 Types.push_back(Spec);
3207 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3208 }
3209
3210 assert(Spec->isDependentType() &&
3211 "Non-dependent template-id type must have a canonical type");
3212 return QualType(Spec, 0);
3213}
3214
3215QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003216ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3217 NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00003218 QualType NamedType) const {
Douglas Gregore4e5b052009-03-19 00:18:19 +00003219 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003220 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003221
3222 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003223 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003224 if (T)
3225 return QualType(T, 0);
3226
Douglas Gregor789b1f62010-02-04 18:10:26 +00003227 QualType Canon = NamedType;
3228 if (!Canon.isCanonical()) {
3229 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003230 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3231 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00003232 (void)CheckT;
3233 }
3234
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003235 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003236 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003237 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003238 return QualType(T, 0);
3239}
3240
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003241QualType
Jay Foad4ba2a172011-01-12 09:06:06 +00003242ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003243 llvm::FoldingSetNodeID ID;
3244 ParenType::Profile(ID, InnerType);
3245
3246 void *InsertPos = 0;
3247 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3248 if (T)
3249 return QualType(T, 0);
3250
3251 QualType Canon = InnerType;
3252 if (!Canon.isCanonical()) {
3253 Canon = getCanonicalType(InnerType);
3254 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3255 assert(!CheckT && "Paren canonical type broken");
3256 (void)CheckT;
3257 }
3258
3259 T = new (*this) ParenType(InnerType, Canon);
3260 Types.push_back(T);
3261 ParenTypes.InsertNode(T, InsertPos);
3262 return QualType(T, 0);
3263}
3264
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003265QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3266 NestedNameSpecifier *NNS,
3267 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00003268 QualType Canon) const {
Douglas Gregord57959a2009-03-27 23:10:48 +00003269 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
3270
3271 if (Canon.isNull()) {
3272 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003273 ElaboratedTypeKeyword CanonKeyword = Keyword;
3274 if (Keyword == ETK_None)
3275 CanonKeyword = ETK_Typename;
3276
3277 if (CanonNNS != NNS || CanonKeyword != Keyword)
3278 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00003279 }
3280
3281 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003282 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00003283
3284 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00003285 DependentNameType *T
3286 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00003287 if (T)
3288 return QualType(T, 0);
3289
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003290 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00003291 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00003292 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00003293 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00003294}
3295
Mike Stump1eb44332009-09-09 15:08:12 +00003296QualType
John McCall33500952010-06-11 00:33:02 +00003297ASTContext::getDependentTemplateSpecializationType(
3298 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003299 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00003300 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00003301 const TemplateArgumentListInfo &Args) const {
John McCall33500952010-06-11 00:33:02 +00003302 // TODO: avoid this copy
Chris Lattner5f9e2722011-07-23 10:55:15 +00003303 SmallVector<TemplateArgument, 16> ArgCopy;
John McCall33500952010-06-11 00:33:02 +00003304 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3305 ArgCopy.push_back(Args[I].getArgument());
3306 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3307 ArgCopy.size(),
3308 ArgCopy.data());
3309}
3310
3311QualType
3312ASTContext::getDependentTemplateSpecializationType(
3313 ElaboratedTypeKeyword Keyword,
3314 NestedNameSpecifier *NNS,
3315 const IdentifierInfo *Name,
3316 unsigned NumArgs,
Jay Foad4ba2a172011-01-12 09:06:06 +00003317 const TemplateArgument *Args) const {
Douglas Gregoraa2187d2011-02-28 00:04:36 +00003318 assert((!NNS || NNS->isDependent()) &&
3319 "nested-name-specifier must be dependent");
Douglas Gregor17343172009-04-01 00:28:59 +00003320
Douglas Gregor789b1f62010-02-04 18:10:26 +00003321 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00003322 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3323 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003324
3325 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00003326 DependentTemplateSpecializationType *T
3327 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003328 if (T)
3329 return QualType(T, 0);
3330
John McCall33500952010-06-11 00:33:02 +00003331 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003332
John McCall33500952010-06-11 00:33:02 +00003333 ElaboratedTypeKeyword CanonKeyword = Keyword;
3334 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3335
3336 bool AnyNonCanonArgs = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003337 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCall33500952010-06-11 00:33:02 +00003338 for (unsigned I = 0; I != NumArgs; ++I) {
3339 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3340 if (!CanonArgs[I].structurallyEquals(Args[I]))
3341 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00003342 }
3343
John McCall33500952010-06-11 00:33:02 +00003344 QualType Canon;
3345 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3346 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3347 Name, NumArgs,
3348 CanonArgs.data());
3349
3350 // Find the insert position again.
3351 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3352 }
3353
3354 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3355 sizeof(TemplateArgument) * NumArgs),
3356 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00003357 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00003358 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00003359 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00003360 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00003361 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00003362}
3363
Douglas Gregorcded4f62011-01-14 17:04:44 +00003364QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikiedc84cd52013-02-20 22:23:23 +00003365 Optional<unsigned> NumExpansions) {
Douglas Gregor7536dd52010-12-20 02:24:11 +00003366 llvm::FoldingSetNodeID ID;
Douglas Gregorcded4f62011-01-14 17:04:44 +00003367 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003368
3369 assert(Pattern->containsUnexpandedParameterPack() &&
3370 "Pack expansions must expand one or more parameter packs");
3371 void *InsertPos = 0;
3372 PackExpansionType *T
3373 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3374 if (T)
3375 return QualType(T, 0);
3376
3377 QualType Canon;
3378 if (!Pattern.isCanonical()) {
Richard Smithd8672ef2012-07-16 00:20:35 +00003379 Canon = getCanonicalType(Pattern);
3380 // The canonical type might not contain an unexpanded parameter pack, if it
3381 // contains an alias template specialization which ignores one of its
3382 // parameters.
3383 if (Canon->containsUnexpandedParameterPack()) {
3384 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003385
Richard Smithd8672ef2012-07-16 00:20:35 +00003386 // Find the insert position again, in case we inserted an element into
3387 // PackExpansionTypes and invalidated our insert position.
3388 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3389 }
Douglas Gregor7536dd52010-12-20 02:24:11 +00003390 }
3391
Douglas Gregorcded4f62011-01-14 17:04:44 +00003392 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003393 Types.push_back(T);
3394 PackExpansionTypes.InsertNode(T, InsertPos);
3395 return QualType(T, 0);
3396}
3397
Chris Lattner88cb27a2008-04-07 04:56:42 +00003398/// CmpProtocolNames - Comparison predicate for sorting protocols
3399/// alphabetically.
3400static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3401 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003402 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00003403}
3404
John McCallc12c5bb2010-05-15 11:32:37 +00003405static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00003406 unsigned NumProtocols) {
3407 if (NumProtocols == 0) return true;
3408
Douglas Gregor61cc2962012-01-02 02:00:30 +00003409 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3410 return false;
3411
John McCall54e14c42009-10-22 22:37:11 +00003412 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregor61cc2962012-01-02 02:00:30 +00003413 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3414 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCall54e14c42009-10-22 22:37:11 +00003415 return false;
3416 return true;
3417}
3418
3419static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00003420 unsigned &NumProtocols) {
3421 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00003422
Chris Lattner88cb27a2008-04-07 04:56:42 +00003423 // Sort protocols, keyed by name.
3424 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3425
Douglas Gregor61cc2962012-01-02 02:00:30 +00003426 // Canonicalize.
3427 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3428 Protocols[I] = Protocols[I]->getCanonicalDecl();
3429
Chris Lattner88cb27a2008-04-07 04:56:42 +00003430 // Remove duplicates.
3431 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3432 NumProtocols = ProtocolsEnd-Protocols;
3433}
3434
John McCallc12c5bb2010-05-15 11:32:37 +00003435QualType ASTContext::getObjCObjectType(QualType BaseType,
3436 ObjCProtocolDecl * const *Protocols,
Jay Foad4ba2a172011-01-12 09:06:06 +00003437 unsigned NumProtocols) const {
John McCallc12c5bb2010-05-15 11:32:37 +00003438 // If the base type is an interface and there aren't any protocols
3439 // to add, then the interface type will do just fine.
3440 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3441 return BaseType;
3442
3443 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003444 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00003445 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003446 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00003447 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3448 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003449
John McCallc12c5bb2010-05-15 11:32:37 +00003450 // Build the canonical type, which has the canonical base type and
3451 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00003452 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00003453 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3454 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3455 if (!ProtocolsSorted) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003456 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer02379412010-04-27 17:12:11 +00003457 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00003458 unsigned UniqueCount = NumProtocols;
3459
John McCall54e14c42009-10-22 22:37:11 +00003460 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00003461 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3462 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00003463 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00003464 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3465 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00003466 }
3467
3468 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00003469 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3470 }
3471
3472 unsigned Size = sizeof(ObjCObjectTypeImpl);
3473 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3474 void *Mem = Allocate(Size, TypeAlignment);
3475 ObjCObjectTypeImpl *T =
3476 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3477
3478 Types.push_back(T);
3479 ObjCObjectTypes.InsertNode(T, InsertPos);
3480 return QualType(T, 0);
3481}
3482
3483/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3484/// the given object type.
Jay Foad4ba2a172011-01-12 09:06:06 +00003485QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCallc12c5bb2010-05-15 11:32:37 +00003486 llvm::FoldingSetNodeID ID;
3487 ObjCObjectPointerType::Profile(ID, ObjectT);
3488
3489 void *InsertPos = 0;
3490 if (ObjCObjectPointerType *QT =
3491 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3492 return QualType(QT, 0);
3493
3494 // Find the canonical object type.
3495 QualType Canonical;
3496 if (!ObjectT.isCanonical()) {
3497 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3498
3499 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00003500 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3501 }
3502
Douglas Gregorfd6a0882010-02-08 22:59:26 +00003503 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00003504 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3505 ObjCObjectPointerType *QType =
3506 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00003507
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003508 Types.push_back(QType);
3509 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00003510 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003511}
Chris Lattner88cb27a2008-04-07 04:56:42 +00003512
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003513/// getObjCInterfaceType - Return the unique reference to the type for the
3514/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregor0af55012011-12-16 03:12:41 +00003515QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3516 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003517 if (Decl->TypeForDecl)
3518 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00003519
Douglas Gregor0af55012011-12-16 03:12:41 +00003520 if (PrevDecl) {
3521 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3522 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3523 return QualType(PrevDecl->TypeForDecl, 0);
3524 }
3525
Douglas Gregor8d2dbbf2011-12-16 16:34:57 +00003526 // Prefer the definition, if there is one.
3527 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3528 Decl = Def;
3529
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003530 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3531 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3532 Decl->TypeForDecl = T;
3533 Types.push_back(T);
3534 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00003535}
3536
Douglas Gregor72564e72009-02-26 23:50:07 +00003537/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3538/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00003539/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00003540/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00003541/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00003542QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003543 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00003544 if (tofExpr->isTypeDependent()) {
3545 llvm::FoldingSetNodeID ID;
3546 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00003547
Douglas Gregorb1975722009-07-30 23:18:24 +00003548 void *InsertPos = 0;
3549 DependentTypeOfExprType *Canon
3550 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3551 if (Canon) {
3552 // We already have a "canonical" version of an identical, dependent
3553 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00003554 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00003555 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00003556 } else {
Douglas Gregorb1975722009-07-30 23:18:24 +00003557 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00003558 Canon
3559 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00003560 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3561 toe = Canon;
3562 }
3563 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003564 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00003565 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00003566 }
Steve Naroff9752f252007-08-01 18:02:17 +00003567 Types.push_back(toe);
3568 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00003569}
3570
Steve Naroff9752f252007-08-01 18:02:17 +00003571/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3572/// TypeOfType AST's. The only motivation to unique these nodes would be
3573/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00003574/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00003575/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00003576QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00003577 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00003578 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00003579 Types.push_back(tot);
3580 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00003581}
3582
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00003583
Anders Carlsson395b4752009-06-24 19:06:50 +00003584/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3585/// DecltypeType AST's. The only motivation to unique these nodes would be
3586/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00003587/// an issue. This doesn't effect the type checker, since it operates
David Blaikie39e02032011-11-06 22:28:03 +00003588/// on canonical types (which are always unique).
Douglas Gregorf8af9822012-02-12 18:42:33 +00003589QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003590 DecltypeType *dt;
Douglas Gregor561f8122011-07-01 01:22:09 +00003591
3592 // C++0x [temp.type]p2:
3593 // If an expression e involves a template parameter, decltype(e) denotes a
3594 // unique dependent type. Two such decltype-specifiers refer to the same
3595 // type only if their expressions are equivalent (14.5.6.1).
3596 if (e->isInstantiationDependent()) {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003597 llvm::FoldingSetNodeID ID;
3598 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00003599
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003600 void *InsertPos = 0;
3601 DependentDecltypeType *Canon
3602 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3603 if (Canon) {
3604 // We already have a "canonical" version of an equivalent, dependent
3605 // decltype type. Use that as our canonical type.
Richard Smith0d729102012-08-13 20:08:14 +00003606 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003607 QualType((DecltypeType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00003608 } else {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003609 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00003610 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003611 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3612 dt = Canon;
3613 }
3614 } else {
Douglas Gregorf8af9822012-02-12 18:42:33 +00003615 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3616 getCanonicalType(UnderlyingType));
Douglas Gregordd0257c2009-07-08 00:03:05 +00003617 }
Anders Carlsson395b4752009-06-24 19:06:50 +00003618 Types.push_back(dt);
3619 return QualType(dt, 0);
3620}
3621
Sean Huntca63c202011-05-24 22:41:36 +00003622/// getUnaryTransformationType - We don't unique these, since the memory
3623/// savings are minimal and these are rare.
3624QualType ASTContext::getUnaryTransformType(QualType BaseType,
3625 QualType UnderlyingType,
3626 UnaryTransformType::UTTKind Kind)
3627 const {
3628 UnaryTransformType *Ty =
Douglas Gregor69d97752011-05-25 17:51:54 +00003629 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3630 Kind,
3631 UnderlyingType->isDependentType() ?
Peter Collingbourne12fc4b02012-03-05 16:02:06 +00003632 QualType() : getCanonicalType(UnderlyingType));
Sean Huntca63c202011-05-24 22:41:36 +00003633 Types.push_back(Ty);
3634 return QualType(Ty, 0);
3635}
3636
Richard Smith60e141e2013-05-04 07:00:32 +00003637/// getAutoType - Return the uniqued reference to the 'auto' type which has been
3638/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3639/// canonical deduced-but-dependent 'auto' type.
3640QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
Manuel Klimek152b4e42013-08-22 12:12:24 +00003641 bool IsDependent) const {
3642 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
Richard Smith60e141e2013-05-04 07:00:32 +00003643 return getAutoDeductType();
Manuel Klimek152b4e42013-08-22 12:12:24 +00003644
Richard Smith60e141e2013-05-04 07:00:32 +00003645 // Look in the folding set for an existing type.
Richard Smith483b9f32011-02-21 20:05:19 +00003646 void *InsertPos = 0;
Richard Smith60e141e2013-05-04 07:00:32 +00003647 llvm::FoldingSetNodeID ID;
Manuel Klimek152b4e42013-08-22 12:12:24 +00003648 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
Richard Smith60e141e2013-05-04 07:00:32 +00003649 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3650 return QualType(AT, 0);
Richard Smith483b9f32011-02-21 20:05:19 +00003651
Richard Smitha2c36462013-04-26 16:15:35 +00003652 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smithdc7a4f52013-04-30 13:56:41 +00003653 IsDecltypeAuto,
Manuel Klimek152b4e42013-08-22 12:12:24 +00003654 IsDependent);
Richard Smith483b9f32011-02-21 20:05:19 +00003655 Types.push_back(AT);
3656 if (InsertPos)
3657 AutoTypes.InsertNode(AT, InsertPos);
3658 return QualType(AT, 0);
Richard Smith34b41d92011-02-20 03:19:35 +00003659}
3660
Eli Friedmanb001de72011-10-06 23:00:33 +00003661/// getAtomicType - Return the uniqued reference to the atomic type for
3662/// the given value type.
3663QualType ASTContext::getAtomicType(QualType T) const {
3664 // Unique pointers, to guarantee there is only one pointer of a particular
3665 // structure.
3666 llvm::FoldingSetNodeID ID;
3667 AtomicType::Profile(ID, T);
3668
3669 void *InsertPos = 0;
3670 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3671 return QualType(AT, 0);
3672
3673 // If the atomic value type isn't canonical, this won't be a canonical type
3674 // either, so fill in the canonical type field.
3675 QualType Canonical;
3676 if (!T.isCanonical()) {
3677 Canonical = getAtomicType(getCanonicalType(T));
3678
3679 // Get the new insert position for the node we care about.
3680 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3681 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3682 }
3683 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3684 Types.push_back(New);
3685 AtomicTypes.InsertNode(New, InsertPos);
3686 return QualType(New, 0);
3687}
3688
Richard Smithad762fc2011-04-14 22:09:26 +00003689/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3690QualType ASTContext::getAutoDeductType() const {
3691 if (AutoDeductTy.isNull())
Richard Smith60e141e2013-05-04 07:00:32 +00003692 AutoDeductTy = QualType(
3693 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
Manuel Klimek152b4e42013-08-22 12:12:24 +00003694 /*dependent*/false),
Richard Smith60e141e2013-05-04 07:00:32 +00003695 0);
Richard Smithad762fc2011-04-14 22:09:26 +00003696 return AutoDeductTy;
3697}
3698
3699/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3700QualType ASTContext::getAutoRRefDeductType() const {
3701 if (AutoRRefDeductTy.isNull())
3702 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3703 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3704 return AutoRRefDeductTy;
3705}
3706
Reid Spencer5f016e22007-07-11 17:01:13 +00003707/// getTagDeclType - Return the unique reference to the type for the
3708/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad4ba2a172011-01-12 09:06:06 +00003709QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenekd778f882007-11-26 21:16:01 +00003710 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00003711 // FIXME: What is the design on getTagDeclType when it requires casting
3712 // away const? mutable?
3713 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003714}
3715
Mike Stump1eb44332009-09-09 15:08:12 +00003716/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3717/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3718/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00003719CanQualType ASTContext::getSizeType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003720 return getFromTargetType(Target->getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00003721}
3722
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003723/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3724CanQualType ASTContext::getIntMaxType() const {
3725 return getFromTargetType(Target->getIntMaxType());
3726}
3727
3728/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3729CanQualType ASTContext::getUIntMaxType() const {
3730 return getFromTargetType(Target->getUIntMaxType());
3731}
3732
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00003733/// getSignedWCharType - Return the type of "signed wchar_t".
3734/// Used when in C++, as a GCC extension.
3735QualType ASTContext::getSignedWCharType() const {
3736 // FIXME: derive from "Target" ?
3737 return WCharTy;
3738}
3739
3740/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3741/// Used when in C++, as a GCC extension.
3742QualType ASTContext::getUnsignedWCharType() const {
3743 // FIXME: derive from "Target" ?
3744 return UnsignedIntTy;
3745}
3746
Enea Zaffanella9677eb82013-01-26 17:08:37 +00003747QualType ASTContext::getIntPtrType() const {
3748 return getFromTargetType(Target->getIntPtrType());
3749}
3750
3751QualType ASTContext::getUIntPtrType() const {
3752 return getCorrespondingUnsignedType(getIntPtrType());
3753}
3754
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003755/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattner8b9023b2007-07-13 03:05:23 +00003756/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3757QualType ASTContext::getPointerDiffType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003758 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00003759}
3760
Eli Friedman6902e412012-11-27 02:58:24 +00003761/// \brief Return the unique type for "pid_t" defined in
3762/// <sys/types.h>. We need this to compute the correct type for vfork().
3763QualType ASTContext::getProcessIDType() const {
3764 return getFromTargetType(Target->getProcessIDType());
3765}
3766
Chris Lattnere6327742008-04-02 05:18:44 +00003767//===----------------------------------------------------------------------===//
3768// Type Operators
3769//===----------------------------------------------------------------------===//
3770
Jay Foad4ba2a172011-01-12 09:06:06 +00003771CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCall54e14c42009-10-22 22:37:11 +00003772 // Push qualifiers into arrays, and then discard any remaining
3773 // qualifiers.
3774 T = getCanonicalType(T);
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003775 T = getVariableArrayDecayedType(T);
John McCall54e14c42009-10-22 22:37:11 +00003776 const Type *Ty = T.getTypePtr();
John McCall54e14c42009-10-22 22:37:11 +00003777 QualType Result;
3778 if (isa<ArrayType>(Ty)) {
3779 Result = getArrayDecayedType(QualType(Ty,0));
3780 } else if (isa<FunctionType>(Ty)) {
3781 Result = getPointerType(QualType(Ty, 0));
3782 } else {
3783 Result = QualType(Ty, 0);
3784 }
3785
3786 return CanQualType::CreateUnsafe(Result);
3787}
3788
John McCall62c28c82011-01-18 07:41:22 +00003789QualType ASTContext::getUnqualifiedArrayType(QualType type,
3790 Qualifiers &quals) {
3791 SplitQualType splitType = type.getSplitUnqualifiedType();
3792
3793 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3794 // the unqualified desugared type and then drops it on the floor.
3795 // We then have to strip that sugar back off with
3796 // getUnqualifiedDesugaredType(), which is silly.
3797 const ArrayType *AT =
John McCall200fa532012-02-08 00:46:36 +00003798 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall62c28c82011-01-18 07:41:22 +00003799
3800 // If we don't have an array, just use the results in splitType.
Douglas Gregor9dadd942010-05-17 18:45:21 +00003801 if (!AT) {
John McCall200fa532012-02-08 00:46:36 +00003802 quals = splitType.Quals;
3803 return QualType(splitType.Ty, 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003804 }
3805
John McCall62c28c82011-01-18 07:41:22 +00003806 // Otherwise, recurse on the array's element type.
3807 QualType elementType = AT->getElementType();
3808 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3809
3810 // If that didn't change the element type, AT has no qualifiers, so we
3811 // can just use the results in splitType.
3812 if (elementType == unqualElementType) {
3813 assert(quals.empty()); // from the recursive call
John McCall200fa532012-02-08 00:46:36 +00003814 quals = splitType.Quals;
3815 return QualType(splitType.Ty, 0);
John McCall62c28c82011-01-18 07:41:22 +00003816 }
3817
3818 // Otherwise, add in the qualifiers from the outermost type, then
3819 // build the type back up.
John McCall200fa532012-02-08 00:46:36 +00003820 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003821
Douglas Gregor9dadd942010-05-17 18:45:21 +00003822 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003823 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003824 CAT->getSizeModifier(), 0);
3825 }
3826
Douglas Gregor9dadd942010-05-17 18:45:21 +00003827 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003828 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003829 }
3830
Douglas Gregor9dadd942010-05-17 18:45:21 +00003831 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003832 return getVariableArrayType(unqualElementType,
John McCall3fa5cae2010-10-26 07:05:15 +00003833 VAT->getSizeExpr(),
Douglas Gregor9dadd942010-05-17 18:45:21 +00003834 VAT->getSizeModifier(),
3835 VAT->getIndexTypeCVRQualifiers(),
3836 VAT->getBracketsRange());
3837 }
3838
3839 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall62c28c82011-01-18 07:41:22 +00003840 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003841 DSAT->getSizeModifier(), 0,
3842 SourceRange());
3843}
3844
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003845/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3846/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3847/// they point to and return true. If T1 and T2 aren't pointer types
3848/// or pointer-to-member types, or if they are not similar at this
3849/// level, returns false and leaves T1 and T2 unchanged. Top-level
3850/// qualifiers on T1 and T2 are ignored. This function will typically
3851/// be called in a loop that successively "unwraps" pointer and
3852/// pointer-to-member types to compare them at each level.
3853bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3854 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3855 *T2PtrType = T2->getAs<PointerType>();
3856 if (T1PtrType && T2PtrType) {
3857 T1 = T1PtrType->getPointeeType();
3858 T2 = T2PtrType->getPointeeType();
3859 return true;
3860 }
3861
3862 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3863 *T2MPType = T2->getAs<MemberPointerType>();
3864 if (T1MPType && T2MPType &&
3865 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3866 QualType(T2MPType->getClass(), 0))) {
3867 T1 = T1MPType->getPointeeType();
3868 T2 = T2MPType->getPointeeType();
3869 return true;
3870 }
3871
David Blaikie4e4d0842012-03-11 07:00:24 +00003872 if (getLangOpts().ObjC1) {
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003873 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3874 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3875 if (T1OPType && T2OPType) {
3876 T1 = T1OPType->getPointeeType();
3877 T2 = T2OPType->getPointeeType();
3878 return true;
3879 }
3880 }
3881
3882 // FIXME: Block pointers, too?
3883
3884 return false;
3885}
3886
Jay Foad4ba2a172011-01-12 09:06:06 +00003887DeclarationNameInfo
3888ASTContext::getNameForTemplate(TemplateName Name,
3889 SourceLocation NameLoc) const {
John McCall14606042011-06-30 08:33:18 +00003890 switch (Name.getKind()) {
3891 case TemplateName::QualifiedTemplate:
3892 case TemplateName::Template:
Abramo Bagnara25777432010-08-11 22:01:17 +00003893 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCall14606042011-06-30 08:33:18 +00003894 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3895 NameLoc);
Abramo Bagnara25777432010-08-11 22:01:17 +00003896
John McCall14606042011-06-30 08:33:18 +00003897 case TemplateName::OverloadedTemplate: {
3898 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3899 // DNInfo work in progress: CHECKME: what about DNLoc?
3900 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3901 }
3902
3903 case TemplateName::DependentTemplate: {
3904 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnara25777432010-08-11 22:01:17 +00003905 DeclarationName DName;
John McCall80ad16f2009-11-24 18:42:40 +00003906 if (DTN->isIdentifier()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00003907 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3908 return DeclarationNameInfo(DName, NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003909 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00003910 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3911 // DNInfo work in progress: FIXME: source locations?
3912 DeclarationNameLoc DNLoc;
3913 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3914 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3915 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003916 }
3917 }
3918
John McCall14606042011-06-30 08:33:18 +00003919 case TemplateName::SubstTemplateTemplateParm: {
3920 SubstTemplateTemplateParmStorage *subst
3921 = Name.getAsSubstTemplateTemplateParm();
3922 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3923 NameLoc);
3924 }
3925
3926 case TemplateName::SubstTemplateTemplateParmPack: {
3927 SubstTemplateTemplateParmPackStorage *subst
3928 = Name.getAsSubstTemplateTemplateParmPack();
3929 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3930 NameLoc);
3931 }
3932 }
3933
3934 llvm_unreachable("bad template name kind!");
John McCall80ad16f2009-11-24 18:42:40 +00003935}
3936
Jay Foad4ba2a172011-01-12 09:06:06 +00003937TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCall14606042011-06-30 08:33:18 +00003938 switch (Name.getKind()) {
3939 case TemplateName::QualifiedTemplate:
3940 case TemplateName::Template: {
3941 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003942 if (TemplateTemplateParmDecl *TTP
John McCall14606042011-06-30 08:33:18 +00003943 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003944 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3945
3946 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00003947 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003948 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003949
John McCall14606042011-06-30 08:33:18 +00003950 case TemplateName::OverloadedTemplate:
3951 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump1eb44332009-09-09 15:08:12 +00003952
John McCall14606042011-06-30 08:33:18 +00003953 case TemplateName::DependentTemplate: {
3954 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3955 assert(DTN && "Non-dependent template names must refer to template decls.");
3956 return DTN->CanonicalTemplateName;
3957 }
3958
3959 case TemplateName::SubstTemplateTemplateParm: {
3960 SubstTemplateTemplateParmStorage *subst
3961 = Name.getAsSubstTemplateTemplateParm();
3962 return getCanonicalTemplateName(subst->getReplacement());
3963 }
3964
3965 case TemplateName::SubstTemplateTemplateParmPack: {
3966 SubstTemplateTemplateParmPackStorage *subst
3967 = Name.getAsSubstTemplateTemplateParmPack();
3968 TemplateTemplateParmDecl *canonParameter
3969 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3970 TemplateArgument canonArgPack
3971 = getCanonicalTemplateArgument(subst->getArgumentPack());
3972 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3973 }
3974 }
3975
3976 llvm_unreachable("bad template name!");
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003977}
3978
Douglas Gregordb0d4b72009-11-11 23:06:43 +00003979bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3980 X = getCanonicalTemplateName(X);
3981 Y = getCanonicalTemplateName(Y);
3982 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3983}
3984
Mike Stump1eb44332009-09-09 15:08:12 +00003985TemplateArgument
Jay Foad4ba2a172011-01-12 09:06:06 +00003986ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregor1275ae02009-07-28 23:00:59 +00003987 switch (Arg.getKind()) {
3988 case TemplateArgument::Null:
3989 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003990
Douglas Gregor1275ae02009-07-28 23:00:59 +00003991 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00003992 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003993
Douglas Gregord2008e22012-04-06 22:40:38 +00003994 case TemplateArgument::Declaration: {
Eli Friedmand7a6b162012-09-26 02:36:12 +00003995 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
3996 return TemplateArgument(D, Arg.isDeclForReferenceParam());
Douglas Gregord2008e22012-04-06 22:40:38 +00003997 }
Mike Stump1eb44332009-09-09 15:08:12 +00003998
Eli Friedmand7a6b162012-09-26 02:36:12 +00003999 case TemplateArgument::NullPtr:
4000 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4001 /*isNullPtr*/true);
4002
Douglas Gregor788cd062009-11-11 01:00:40 +00004003 case TemplateArgument::Template:
4004 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregora7fc9012011-01-05 18:58:31 +00004005
4006 case TemplateArgument::TemplateExpansion:
4007 return TemplateArgument(getCanonicalTemplateName(
4008 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregor2be29f42011-01-14 23:41:42 +00004009 Arg.getNumTemplateExpansions());
Douglas Gregora7fc9012011-01-05 18:58:31 +00004010
Douglas Gregor1275ae02009-07-28 23:00:59 +00004011 case TemplateArgument::Integral:
Benjamin Kramer85524372012-06-07 15:09:51 +00004012 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00004013
Douglas Gregor1275ae02009-07-28 23:00:59 +00004014 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00004015 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00004016
Douglas Gregor1275ae02009-07-28 23:00:59 +00004017 case TemplateArgument::Pack: {
Douglas Gregor87dd6972010-12-20 16:52:59 +00004018 if (Arg.pack_size() == 0)
4019 return Arg;
4020
Douglas Gregor910f8002010-11-07 23:05:16 +00004021 TemplateArgument *CanonArgs
4022 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregor1275ae02009-07-28 23:00:59 +00004023 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004024 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00004025 AEnd = Arg.pack_end();
4026 A != AEnd; (void)++A, ++Idx)
4027 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00004028
Douglas Gregor910f8002010-11-07 23:05:16 +00004029 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregor1275ae02009-07-28 23:00:59 +00004030 }
4031 }
4032
4033 // Silence GCC warning
David Blaikieb219cfc2011-09-23 05:06:16 +00004034 llvm_unreachable("Unhandled template argument kind");
Douglas Gregor1275ae02009-07-28 23:00:59 +00004035}
4036
Douglas Gregord57959a2009-03-27 23:10:48 +00004037NestedNameSpecifier *
Jay Foad4ba2a172011-01-12 09:06:06 +00004038ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump1eb44332009-09-09 15:08:12 +00004039 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00004040 return 0;
4041
4042 switch (NNS->getKind()) {
4043 case NestedNameSpecifier::Identifier:
4044 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00004045 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00004046 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4047 NNS->getAsIdentifier());
4048
4049 case NestedNameSpecifier::Namespace:
4050 // A namespace is canonical; build a nested-name-specifier with
4051 // this namespace and no prefix.
Douglas Gregor14aba762011-02-24 02:36:08 +00004052 return NestedNameSpecifier::Create(*this, 0,
4053 NNS->getAsNamespace()->getOriginalNamespace());
4054
4055 case NestedNameSpecifier::NamespaceAlias:
4056 // A namespace is canonical; build a nested-name-specifier with
4057 // this namespace and no prefix.
4058 return NestedNameSpecifier::Create(*this, 0,
4059 NNS->getAsNamespaceAlias()->getNamespace()
4060 ->getOriginalNamespace());
Douglas Gregord57959a2009-03-27 23:10:48 +00004061
4062 case NestedNameSpecifier::TypeSpec:
4063 case NestedNameSpecifier::TypeSpecWithTemplate: {
4064 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor264bf662010-11-04 00:09:33 +00004065
4066 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4067 // break it apart into its prefix and identifier, then reconsititute those
4068 // as the canonical nested-name-specifier. This is required to canonicalize
4069 // a dependent nested-name-specifier involving typedefs of dependent-name
4070 // types, e.g.,
4071 // typedef typename T::type T1;
4072 // typedef typename T1::type T2;
Eli Friedman16412ef2012-03-03 04:09:56 +00004073 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4074 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor264bf662010-11-04 00:09:33 +00004075 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor264bf662010-11-04 00:09:33 +00004076
Eli Friedman16412ef2012-03-03 04:09:56 +00004077 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4078 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4079 // first place?
John McCall3b657512011-01-19 10:06:00 +00004080 return NestedNameSpecifier::Create(*this, 0, false,
4081 const_cast<Type*>(T.getTypePtr()));
Douglas Gregord57959a2009-03-27 23:10:48 +00004082 }
4083
4084 case NestedNameSpecifier::Global:
4085 // The global specifier is canonical and unique.
4086 return NNS;
4087 }
4088
David Blaikie7530c032012-01-17 06:56:22 +00004089 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregord57959a2009-03-27 23:10:48 +00004090}
4091
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004092
Jay Foad4ba2a172011-01-12 09:06:06 +00004093const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004094 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004095 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004096 // Handle the common positive case fast.
4097 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4098 return AT;
4099 }
Mike Stump1eb44332009-09-09 15:08:12 +00004100
John McCall0953e762009-09-24 19:53:00 +00004101 // Handle the common negative case fast.
John McCall3b657512011-01-19 10:06:00 +00004102 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004103 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004104
John McCall0953e762009-09-24 19:53:00 +00004105 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004106 // implements C99 6.7.3p8: "If the specification of an array type includes
4107 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00004108
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004109 // If we get here, we either have type qualifiers on the type, or we have
4110 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00004111 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00004112
John McCall3b657512011-01-19 10:06:00 +00004113 SplitQualType split = T.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00004114 Qualifiers qs = split.Quals;
Mike Stump1eb44332009-09-09 15:08:12 +00004115
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004116 // If we have a simple case, just return now.
John McCall200fa532012-02-08 00:46:36 +00004117 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall3b657512011-01-19 10:06:00 +00004118 if (ATy == 0 || qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004119 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00004120
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004121 // Otherwise, we have an array and we have qualifiers on it. Push the
4122 // qualifiers into the array element type and return a new array type.
John McCall3b657512011-01-19 10:06:00 +00004123 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump1eb44332009-09-09 15:08:12 +00004124
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004125 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4126 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4127 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004128 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004129 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4130 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4131 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004132 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00004133
Mike Stump1eb44332009-09-09 15:08:12 +00004134 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00004135 = dyn_cast<DependentSizedArrayType>(ATy))
4136 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00004137 getDependentSizedArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00004138 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00004139 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004140 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004141 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00004142
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004143 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004144 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00004145 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004146 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004147 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004148 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00004149}
4150
Abramo Bagnaraad9689f2012-05-17 12:44:05 +00004151QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner12df2462013-06-24 17:51:48 +00004152 if (T->isArrayType() || T->isFunctionType())
4153 return getDecayedType(T);
4154 return T;
Douglas Gregor79e6bd32011-07-12 04:42:08 +00004155}
4156
Abramo Bagnaraad9689f2012-05-17 12:44:05 +00004157QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor79e6bd32011-07-12 04:42:08 +00004158 T = getVariableArrayDecayedType(T);
4159 T = getAdjustedParameterType(T);
4160 return T.getUnqualifiedType();
4161}
4162
Chris Lattnere6327742008-04-02 05:18:44 +00004163/// getArrayDecayedType - Return the properly qualified result of decaying the
4164/// specified array type to a pointer. This operation is non-trivial when
4165/// handling typedefs etc. The canonical type of "T" must be an array type,
4166/// this returns a pointer to a properly qualified element of the array.
4167///
4168/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad4ba2a172011-01-12 09:06:06 +00004169QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004170 // Get the element type with 'getAsArrayType' so that we don't lose any
4171 // typedefs in the element type of the array. This also handles propagation
4172 // of type qualifiers from the array type into the element type if present
4173 // (C99 6.7.3p8).
4174 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4175 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00004176
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004177 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00004178
4179 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00004180 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00004181}
4182
John McCall3b657512011-01-19 10:06:00 +00004183QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4184 return getBaseElementType(array->getElementType());
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00004185}
4186
John McCall3b657512011-01-19 10:06:00 +00004187QualType ASTContext::getBaseElementType(QualType type) const {
4188 Qualifiers qs;
4189 while (true) {
4190 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00004191 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall3b657512011-01-19 10:06:00 +00004192 if (!array) break;
Mike Stump1eb44332009-09-09 15:08:12 +00004193
John McCall3b657512011-01-19 10:06:00 +00004194 type = array->getElementType();
John McCall200fa532012-02-08 00:46:36 +00004195 qs.addConsistentQualifiers(split.Quals);
John McCall3b657512011-01-19 10:06:00 +00004196 }
Mike Stump1eb44332009-09-09 15:08:12 +00004197
John McCall3b657512011-01-19 10:06:00 +00004198 return getQualifiedType(type, qs);
Anders Carlsson6183a992008-12-21 03:44:36 +00004199}
4200
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004201/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00004202uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004203ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4204 uint64_t ElementCount = 1;
4205 do {
4206 ElementCount *= CA->getSize().getZExtValue();
Richard Smithd5e83942012-12-06 03:04:50 +00004207 CA = dyn_cast_or_null<ConstantArrayType>(
4208 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004209 } while (CA);
4210 return ElementCount;
4211}
4212
Reid Spencer5f016e22007-07-11 17:01:13 +00004213/// getFloatingRank - Return a relative rank for floating point types.
4214/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00004215static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00004216 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00004217 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00004218
John McCall183700f2009-09-21 23:43:11 +00004219 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4220 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004221 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00004222 case BuiltinType::Half: return HalfRank;
Reid Spencer5f016e22007-07-11 17:01:13 +00004223 case BuiltinType::Float: return FloatRank;
4224 case BuiltinType::Double: return DoubleRank;
4225 case BuiltinType::LongDouble: return LongDoubleRank;
4226 }
4227}
4228
Mike Stump1eb44332009-09-09 15:08:12 +00004229/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4230/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00004231/// 'typeDomain' is a real floating point or complex type.
4232/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00004233QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4234 QualType Domain) const {
4235 FloatingRank EltRank = getFloatingRank(Size);
4236 if (Domain->isComplexType()) {
4237 switch (EltRank) {
David Blaikie561d3ab2012-01-17 02:30:50 +00004238 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Narofff1448a02007-08-27 01:27:54 +00004239 case FloatRank: return FloatComplexTy;
4240 case DoubleRank: return DoubleComplexTy;
4241 case LongDoubleRank: return LongDoubleComplexTy;
4242 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004243 }
Chris Lattner1361b112008-04-06 23:58:54 +00004244
4245 assert(Domain->isRealFloatingType() && "Unknown domain!");
4246 switch (EltRank) {
Joey Gouly19dbb202013-01-23 11:56:20 +00004247 case HalfRank: return HalfTy;
Chris Lattner1361b112008-04-06 23:58:54 +00004248 case FloatRank: return FloatTy;
4249 case DoubleRank: return DoubleTy;
4250 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00004251 }
David Blaikie561d3ab2012-01-17 02:30:50 +00004252 llvm_unreachable("getFloatingRank(): illegal value for rank");
Reid Spencer5f016e22007-07-11 17:01:13 +00004253}
4254
Chris Lattner7cfeb082008-04-06 23:55:33 +00004255/// getFloatingTypeOrder - Compare the rank of the two specified floating
4256/// point types, ignoring the domain of the type (i.e. 'double' ==
4257/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00004258/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00004259int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnera75cea32008-04-06 23:38:49 +00004260 FloatingRank LHSR = getFloatingRank(LHS);
4261 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004262
Chris Lattnera75cea32008-04-06 23:38:49 +00004263 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00004264 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00004265 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00004266 return 1;
4267 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00004268}
4269
Chris Lattnerf52ab252008-04-06 22:59:24 +00004270/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4271/// routine will assert if passed a built-in type that isn't an integer or enum,
4272/// or if it is not canonicalized.
John McCallf4c73712011-01-19 06:33:43 +00004273unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCall467b27b2009-10-22 20:10:53 +00004274 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00004275
Chris Lattnerf52ab252008-04-06 22:59:24 +00004276 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004277 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattner7cfeb082008-04-06 23:55:33 +00004278 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004279 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004280 case BuiltinType::Char_S:
4281 case BuiltinType::Char_U:
4282 case BuiltinType::SChar:
4283 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004284 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004285 case BuiltinType::Short:
4286 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004287 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004288 case BuiltinType::Int:
4289 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004290 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004291 case BuiltinType::Long:
4292 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004293 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004294 case BuiltinType::LongLong:
4295 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004296 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00004297 case BuiltinType::Int128:
4298 case BuiltinType::UInt128:
4299 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00004300 }
4301}
4302
Eli Friedman04e83572009-08-20 04:21:42 +00004303/// \brief Whether this is a promotable bitfield reference according
4304/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4305///
4306/// \returns the type this bit-field will promote to, or NULL if no
4307/// promotion occurs.
Jay Foad4ba2a172011-01-12 09:06:06 +00004308QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregorceafbde2010-05-24 20:13:53 +00004309 if (E->isTypeDependent() || E->isValueDependent())
4310 return QualType();
4311
John McCall993f43f2013-05-06 21:39:12 +00004312 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman04e83572009-08-20 04:21:42 +00004313 if (!Field)
4314 return QualType();
4315
4316 QualType FT = Field->getType();
4317
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004318 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman04e83572009-08-20 04:21:42 +00004319 uint64_t IntSize = getTypeSize(IntTy);
4320 // GCC extension compatibility: if the bit-field size is less than or equal
4321 // to the size of int, it gets promoted no matter what its type is.
4322 // For instance, unsigned long bf : 4 gets promoted to signed int.
4323 if (BitWidth < IntSize)
4324 return IntTy;
4325
4326 if (BitWidth == IntSize)
4327 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4328
4329 // Types bigger than int are not subject to promotions, and therefore act
4330 // like the base type.
4331 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4332 // is ridiculous.
4333 return QualType();
4334}
4335
Eli Friedmana95d7572009-08-19 07:44:53 +00004336/// getPromotedIntegerType - Returns the type that Promotable will
4337/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4338/// integer type.
Jay Foad4ba2a172011-01-12 09:06:06 +00004339QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedmana95d7572009-08-19 07:44:53 +00004340 assert(!Promotable.isNull());
4341 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00004342 if (const EnumType *ET = Promotable->getAs<EnumType>())
4343 return ET->getDecl()->getPromotionType();
Eli Friedman68a2dc42011-10-26 07:22:48 +00004344
4345 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4346 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4347 // (3.9.1) can be converted to a prvalue of the first of the following
4348 // types that can represent all the values of its underlying type:
4349 // int, unsigned int, long int, unsigned long int, long long int, or
4350 // unsigned long long int [...]
4351 // FIXME: Is there some better way to compute this?
4352 if (BT->getKind() == BuiltinType::WChar_S ||
4353 BT->getKind() == BuiltinType::WChar_U ||
4354 BT->getKind() == BuiltinType::Char16 ||
4355 BT->getKind() == BuiltinType::Char32) {
4356 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4357 uint64_t FromSize = getTypeSize(BT);
4358 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4359 LongLongTy, UnsignedLongLongTy };
4360 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4361 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4362 if (FromSize < ToSize ||
4363 (FromSize == ToSize &&
4364 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4365 return PromoteTypes[Idx];
4366 }
4367 llvm_unreachable("char type should fit into long long");
4368 }
4369 }
4370
4371 // At this point, we should have a signed or unsigned integer type.
Eli Friedmana95d7572009-08-19 07:44:53 +00004372 if (Promotable->isSignedIntegerType())
4373 return IntTy;
Eli Friedman5b64e772012-11-15 01:21:59 +00004374 uint64_t PromotableSize = getIntWidth(Promotable);
4375 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedmana95d7572009-08-19 07:44:53 +00004376 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4377 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4378}
4379
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00004380/// \brief Recurses in pointer/array types until it finds an objc retainable
4381/// type and returns its ownership.
4382Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4383 while (!T.isNull()) {
4384 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4385 return T.getObjCLifetime();
4386 if (T->isArrayType())
4387 T = getBaseElementType(T);
4388 else if (const PointerType *PT = T->getAs<PointerType>())
4389 T = PT->getPointeeType();
4390 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis28445f02011-07-01 23:01:46 +00004391 T = RT->getPointeeType();
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00004392 else
4393 break;
4394 }
4395
4396 return Qualifiers::OCL_None;
4397}
4398
Mike Stump1eb44332009-09-09 15:08:12 +00004399/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00004400/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00004401/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00004402int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCallf4c73712011-01-19 06:33:43 +00004403 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4404 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00004405 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004406
Chris Lattnerf52ab252008-04-06 22:59:24 +00004407 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4408 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00004409
Chris Lattner7cfeb082008-04-06 23:55:33 +00004410 unsigned LHSRank = getIntegerRank(LHSC);
4411 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00004412
Chris Lattner7cfeb082008-04-06 23:55:33 +00004413 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4414 if (LHSRank == RHSRank) return 0;
4415 return LHSRank > RHSRank ? 1 : -1;
4416 }
Mike Stump1eb44332009-09-09 15:08:12 +00004417
Chris Lattner7cfeb082008-04-06 23:55:33 +00004418 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4419 if (LHSUnsigned) {
4420 // If the unsigned [LHS] type is larger, return it.
4421 if (LHSRank >= RHSRank)
4422 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004423
Chris Lattner7cfeb082008-04-06 23:55:33 +00004424 // If the signed type can represent all values of the unsigned type, it
4425 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00004426 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00004427 return -1;
4428 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00004429
Chris Lattner7cfeb082008-04-06 23:55:33 +00004430 // If the unsigned [RHS] type is larger, return it.
4431 if (RHSRank >= LHSRank)
4432 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00004433
Chris Lattner7cfeb082008-04-06 23:55:33 +00004434 // If the signed type can represent all values of the unsigned type, it
4435 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00004436 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00004437 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00004438}
Anders Carlsson71993dd2007-08-17 05:31:46 +00004439
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004440static RecordDecl *
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004441CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
4442 DeclContext *DC, IdentifierInfo *Id) {
4443 SourceLocation Loc;
David Blaikie4e4d0842012-03-11 07:00:24 +00004444 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004445 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004446 else
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004447 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004448}
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004449
Mike Stump1eb44332009-09-09 15:08:12 +00004450// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00004451QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson71993dd2007-08-17 05:31:46 +00004452 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00004453 CFConstantStringTypeDecl =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004454 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004455 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00004456 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004457
Anders Carlssonf06273f2007-11-19 00:25:30 +00004458 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00004459
Anders Carlsson71993dd2007-08-17 05:31:46 +00004460 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00004461 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00004462 // int flags;
4463 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00004464 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00004465 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00004466 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00004467 FieldTypes[3] = LongTy;
4468
Anders Carlsson71993dd2007-08-17 05:31:46 +00004469 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00004470 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00004471 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004472 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00004473 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00004474 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00004475 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004476 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004477 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004478 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004479 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00004480 }
4481
Douglas Gregor838db382010-02-11 01:19:42 +00004482 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00004483 }
Mike Stump1eb44332009-09-09 15:08:12 +00004484
Anders Carlsson71993dd2007-08-17 05:31:46 +00004485 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00004486}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004487
Fariborz Jahanianf7992132013-01-04 18:45:40 +00004488QualType ASTContext::getObjCSuperType() const {
4489 if (ObjCSuperType.isNull()) {
4490 RecordDecl *ObjCSuperTypeDecl =
4491 CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get("objc_super"));
4492 TUDecl->addDecl(ObjCSuperTypeDecl);
4493 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4494 }
4495 return ObjCSuperType;
4496}
4497
Douglas Gregor319ac892009-04-23 22:29:11 +00004498void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004499 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00004500 assert(Rec && "Invalid CFConstantStringType");
4501 CFConstantStringTypeDecl = Rec->getDecl();
4502}
4503
Jay Foad4ba2a172011-01-12 09:06:06 +00004504QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpadaaad32009-10-20 02:12:22 +00004505 if (BlockDescriptorType)
4506 return getTagDeclType(BlockDescriptorType);
4507
4508 RecordDecl *T;
4509 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004510 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004511 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00004512 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00004513
4514 QualType FieldTypes[] = {
4515 UnsignedLongTy,
4516 UnsignedLongTy,
4517 };
4518
Craig Topper3aa29df2013-07-15 08:24:27 +00004519 static const char *const FieldNames[] = {
Mike Stumpadaaad32009-10-20 02:12:22 +00004520 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00004521 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00004522 };
4523
4524 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004525 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00004526 SourceLocation(),
4527 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004528 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00004529 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004530 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004531 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004532 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00004533 T->addDecl(Field);
4534 }
4535
Douglas Gregor838db382010-02-11 01:19:42 +00004536 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00004537
4538 BlockDescriptorType = T;
4539
4540 return getTagDeclType(BlockDescriptorType);
4541}
4542
Jay Foad4ba2a172011-01-12 09:06:06 +00004543QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stump083c25e2009-10-22 00:49:09 +00004544 if (BlockDescriptorExtendedType)
4545 return getTagDeclType(BlockDescriptorExtendedType);
4546
4547 RecordDecl *T;
4548 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004549 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004550 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00004551 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00004552
4553 QualType FieldTypes[] = {
4554 UnsignedLongTy,
4555 UnsignedLongTy,
4556 getPointerType(VoidPtrTy),
4557 getPointerType(VoidPtrTy)
4558 };
4559
Craig Topper3aa29df2013-07-15 08:24:27 +00004560 static const char *const FieldNames[] = {
Mike Stump083c25e2009-10-22 00:49:09 +00004561 "reserved",
4562 "Size",
4563 "CopyFuncPtr",
4564 "DestroyFuncPtr"
4565 };
4566
4567 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004568 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stump083c25e2009-10-22 00:49:09 +00004569 SourceLocation(),
4570 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004571 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00004572 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004573 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004574 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004575 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00004576 T->addDecl(Field);
4577 }
4578
Douglas Gregor838db382010-02-11 01:19:42 +00004579 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00004580
4581 BlockDescriptorExtendedType = T;
4582
4583 return getTagDeclType(BlockDescriptorExtendedType);
4584}
4585
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00004586/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4587/// requires copy/dispose. Note that this must match the logic
4588/// in buildByrefHelpers.
4589bool ASTContext::BlockRequiresCopying(QualType Ty,
4590 const VarDecl *D) {
4591 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4592 const Expr *copyExpr = getBlockVarCopyInits(D);
4593 if (!copyExpr && record->hasTrivialDestructor()) return false;
4594
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004595 return true;
Fariborz Jahaniane38be612010-11-17 00:21:28 +00004596 }
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00004597
4598 if (!Ty->isObjCRetainableType()) return false;
4599
4600 Qualifiers qs = Ty.getQualifiers();
4601
4602 // If we have lifetime, that dominates.
4603 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4604 assert(getLangOpts().ObjCAutoRefCount);
4605
4606 switch (lifetime) {
4607 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4608
4609 // These are just bits as far as the runtime is concerned.
4610 case Qualifiers::OCL_ExplicitNone:
4611 case Qualifiers::OCL_Autoreleasing:
4612 return false;
4613
4614 // Tell the runtime that this is ARC __weak, called by the
4615 // byref routines.
4616 case Qualifiers::OCL_Weak:
4617 // ARC __strong __block variables need to be retained.
4618 case Qualifiers::OCL_Strong:
4619 return true;
4620 }
4621 llvm_unreachable("fell out of lifetime switch!");
4622 }
4623 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4624 Ty->isObjCObjectPointerType());
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004625}
4626
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00004627bool ASTContext::getByrefLifetime(QualType Ty,
4628 Qualifiers::ObjCLifetime &LifeTime,
4629 bool &HasByrefExtendedLayout) const {
4630
4631 if (!getLangOpts().ObjC1 ||
4632 getLangOpts().getGC() != LangOptions::NonGC)
4633 return false;
4634
4635 HasByrefExtendedLayout = false;
Fariborz Jahanian34db84f2012-12-11 19:58:01 +00004636 if (Ty->isRecordType()) {
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00004637 HasByrefExtendedLayout = true;
4638 LifeTime = Qualifiers::OCL_None;
4639 }
4640 else if (getLangOpts().ObjCAutoRefCount)
4641 LifeTime = Ty.getObjCLifetime();
4642 // MRR.
4643 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4644 LifeTime = Qualifiers::OCL_ExplicitNone;
4645 else
4646 LifeTime = Qualifiers::OCL_None;
4647 return true;
4648}
4649
Douglas Gregore97179c2011-09-08 01:46:34 +00004650TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4651 if (!ObjCInstanceTypeDecl)
4652 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4653 getTranslationUnitDecl(),
4654 SourceLocation(),
4655 SourceLocation(),
4656 &Idents.get("instancetype"),
4657 getTrivialTypeSourceInfo(getObjCIdType()));
4658 return ObjCInstanceTypeDecl;
4659}
4660
Anders Carlssone8c49532007-10-29 06:33:42 +00004661// This returns true if a type has been typedefed to BOOL:
4662// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00004663static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00004664 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00004665 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4666 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00004667
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004668 return false;
4669}
4670
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004671/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004672/// purpose.
Jay Foad4ba2a172011-01-12 09:06:06 +00004673CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregorf968d832011-05-27 01:19:52 +00004674 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4675 return CharUnits::Zero();
4676
Ken Dyck199c3d62010-01-11 17:06:35 +00004677 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00004678
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004679 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004680 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004681 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004682 // Treat arrays as pointers, since that's how they're passed in.
4683 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004684 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004685 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00004686}
4687
4688static inline
4689std::string charUnitsToString(const CharUnits &CU) {
4690 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004691}
4692
John McCall6b5a61b2011-02-07 10:33:21 +00004693/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00004694/// declaration.
John McCall6b5a61b2011-02-07 10:33:21 +00004695std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4696 std::string S;
4697
David Chisnall5e530af2009-11-17 19:33:30 +00004698 const BlockDecl *Decl = Expr->getBlockDecl();
4699 QualType BlockTy =
4700 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4701 // Encode result type.
Fariborz Jahanian3d145f62012-11-15 19:02:45 +00004702 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian06cffc02012-11-14 23:11:38 +00004703 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None,
4704 BlockTy->getAs<FunctionType>()->getResultType(),
4705 S, true /*Extended*/);
4706 else
4707 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(),
4708 S);
David Chisnall5e530af2009-11-17 19:33:30 +00004709 // Compute size of all parameters.
4710 // Start with computing size of a pointer in number of bytes.
4711 // FIXME: There might(should) be a better way of doing this computation!
4712 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004713 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4714 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00004715 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00004716 E = Decl->param_end(); PI != E; ++PI) {
4717 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004718 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahanian075a5432012-06-30 00:48:59 +00004719 if (sz.isZero())
4720 continue;
Ken Dyck199c3d62010-01-11 17:06:35 +00004721 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00004722 ParmOffset += sz;
4723 }
4724 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00004725 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00004726 // Block pointer and offset.
4727 S += "@?0";
David Chisnall5e530af2009-11-17 19:33:30 +00004728
4729 // Argument types.
4730 ParmOffset = PtrSize;
4731 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4732 Decl->param_end(); PI != E; ++PI) {
4733 ParmVarDecl *PVDecl = *PI;
4734 QualType PType = PVDecl->getOriginalType();
4735 if (const ArrayType *AT =
4736 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4737 // Use array's original type only if it has known number of
4738 // elements.
4739 if (!isa<ConstantArrayType>(AT))
4740 PType = PVDecl->getType();
4741 } else if (PType->isFunctionType())
4742 PType = PVDecl->getType();
Fariborz Jahanian3d145f62012-11-15 19:02:45 +00004743 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian06cffc02012-11-14 23:11:38 +00004744 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4745 S, true /*Extended*/);
4746 else
4747 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00004748 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004749 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00004750 }
John McCall6b5a61b2011-02-07 10:33:21 +00004751
4752 return S;
David Chisnall5e530af2009-11-17 19:33:30 +00004753}
4754
Douglas Gregorf968d832011-05-27 01:19:52 +00004755bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall5389f482010-12-30 14:05:53 +00004756 std::string& S) {
4757 // Encode result type.
4758 getObjCEncodingForType(Decl->getResultType(), S);
4759 CharUnits ParmOffset;
4760 // Compute size of all parameters.
4761 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4762 E = Decl->param_end(); PI != E; ++PI) {
4763 QualType PType = (*PI)->getType();
4764 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004765 if (sz.isZero())
Fariborz Jahanian7e68ba52012-06-29 22:54:56 +00004766 continue;
4767
David Chisnall5389f482010-12-30 14:05:53 +00004768 assert (sz.isPositive() &&
Douglas Gregorf968d832011-05-27 01:19:52 +00004769 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall5389f482010-12-30 14:05:53 +00004770 ParmOffset += sz;
4771 }
4772 S += charUnitsToString(ParmOffset);
4773 ParmOffset = CharUnits::Zero();
4774
4775 // Argument types.
4776 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4777 E = Decl->param_end(); PI != E; ++PI) {
4778 ParmVarDecl *PVDecl = *PI;
4779 QualType PType = PVDecl->getOriginalType();
4780 if (const ArrayType *AT =
4781 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4782 // Use array's original type only if it has known number of
4783 // elements.
4784 if (!isa<ConstantArrayType>(AT))
4785 PType = PVDecl->getType();
4786 } else if (PType->isFunctionType())
4787 PType = PVDecl->getType();
4788 getObjCEncodingForType(PType, S);
4789 S += charUnitsToString(ParmOffset);
4790 ParmOffset += getObjCEncodingTypeSize(PType);
4791 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004792
4793 return false;
David Chisnall5389f482010-12-30 14:05:53 +00004794}
4795
Bob Wilsondc8dab62011-11-30 01:57:58 +00004796/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4797/// method parameter or return type. If Extended, include class names and
4798/// block object types.
4799void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4800 QualType T, std::string& S,
4801 bool Extended) const {
4802 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4803 getObjCEncodingForTypeQualifier(QT, S);
4804 // Encode parameter type.
4805 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4806 true /*OutermostType*/,
4807 false /*EncodingProperty*/,
4808 false /*StructField*/,
4809 Extended /*EncodeBlockParameters*/,
4810 Extended /*EncodeClassNames*/);
4811}
4812
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004813/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004814/// declaration.
Douglas Gregorf968d832011-05-27 01:19:52 +00004815bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilsondc8dab62011-11-30 01:57:58 +00004816 std::string& S,
4817 bool Extended) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004818 // FIXME: This is not very efficient.
Bob Wilsondc8dab62011-11-30 01:57:58 +00004819 // Encode return type.
4820 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4821 Decl->getResultType(), S, Extended);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004822 // Compute size of all parameters.
4823 // Start with computing size of a pointer in number of bytes.
4824 // FIXME: There might(should) be a better way of doing this computation!
4825 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004826 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004827 // The first two arguments (self and _cmd) are pointers; account for
4828 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00004829 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004830 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004831 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00004832 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004833 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004834 if (sz.isZero())
Fariborz Jahanian7e68ba52012-06-29 22:54:56 +00004835 continue;
4836
Ken Dyck199c3d62010-01-11 17:06:35 +00004837 assert (sz.isPositive() &&
4838 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004839 ParmOffset += sz;
4840 }
Ken Dyck199c3d62010-01-11 17:06:35 +00004841 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004842 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00004843 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00004844
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004845 // Argument types.
4846 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004847 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004848 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004849 const ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00004850 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00004851 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00004852 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4853 // Use array's original type only if it has known number of
4854 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00004855 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00004856 PType = PVDecl->getType();
4857 } else if (PType->isFunctionType())
4858 PType = PVDecl->getType();
Bob Wilsondc8dab62011-11-30 01:57:58 +00004859 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4860 PType, S, Extended);
Ken Dyck199c3d62010-01-11 17:06:35 +00004861 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004862 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004863 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004864
4865 return false;
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004866}
4867
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004868/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004869/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004870/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4871/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00004872/// Property attributes are stored as a comma-delimited C string. The simple
4873/// attributes readonly and bycopy are encoded as single characters. The
4874/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4875/// encoded as single characters, followed by an identifier. Property types
4876/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004877/// these attributes are defined by the following enumeration:
4878/// @code
4879/// enum PropertyAttributes {
4880/// kPropertyReadOnly = 'R', // property is read-only.
4881/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4882/// kPropertyByref = '&', // property is a reference to the value last assigned
4883/// kPropertyDynamic = 'D', // property is dynamic
4884/// kPropertyGetter = 'G', // followed by getter selector name
4885/// kPropertySetter = 'S', // followed by setter selector name
4886/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson0d4cb852012-03-22 17:48:02 +00004887/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004888/// kPropertyWeak = 'W' // 'weak' property
4889/// kPropertyStrong = 'P' // property GC'able
4890/// kPropertyNonAtomic = 'N' // property non-atomic
4891/// };
4892/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00004893void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004894 const Decl *Container,
Jay Foad4ba2a172011-01-12 09:06:06 +00004895 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004896 // Collect information from the property implementation decl(s).
4897 bool Dynamic = false;
4898 ObjCPropertyImplDecl *SynthesizePID = 0;
4899
4900 // FIXME: Duplicated code due to poor abstraction.
4901 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00004902 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004903 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4904 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004905 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004906 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00004907 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004908 if (PID->getPropertyDecl() == PD) {
4909 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4910 Dynamic = true;
4911 } else {
4912 SynthesizePID = PID;
4913 }
4914 }
4915 }
4916 } else {
Chris Lattner61710852008-10-05 17:34:18 +00004917 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004918 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004919 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004920 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00004921 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004922 if (PID->getPropertyDecl() == PD) {
4923 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4924 Dynamic = true;
4925 } else {
4926 SynthesizePID = PID;
4927 }
4928 }
Mike Stump1eb44332009-09-09 15:08:12 +00004929 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004930 }
4931 }
4932
4933 // FIXME: This is not very efficient.
4934 S = "T";
4935
4936 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004937 // GCC has some special rules regarding encoding of properties which
4938 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00004939 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004940 true /* outermost type */,
4941 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004942
4943 if (PD->isReadOnly()) {
4944 S += ",R";
Nico Weberd7ceab32013-05-08 23:47:40 +00004945 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
4946 S += ",C";
4947 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
4948 S += ",&";
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004949 } else {
4950 switch (PD->getSetterKind()) {
4951 case ObjCPropertyDecl::Assign: break;
4952 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00004953 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian3a02b442011-08-12 20:47:08 +00004954 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004955 }
4956 }
4957
4958 // It really isn't clear at all what this means, since properties
4959 // are "dynamic by default".
4960 if (Dynamic)
4961 S += ",D";
4962
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004963 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4964 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00004965
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004966 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4967 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004968 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004969 }
4970
4971 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4972 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004973 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004974 }
4975
4976 if (SynthesizePID) {
4977 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4978 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00004979 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004980 }
4981
4982 // FIXME: OBJCGC: weak & strong
4983}
4984
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004985/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00004986/// Another legacy compatibility encoding: 32-bit longs are encoded as
4987/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004988/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4989///
4990void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00004991 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00004992 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad4ba2a172011-01-12 09:06:06 +00004993 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004994 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00004995 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004996 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004997 PointeeTy = IntTy;
4998 }
4999 }
5000}
5001
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00005002void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad4ba2a172011-01-12 09:06:06 +00005003 const FieldDecl *Field) const {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00005004 // We follow the behavior of gcc, expanding structures which are
5005 // directly pointed to, and expanding embedded structures. Note that
5006 // these rules are sufficient to prevent recursive encoding of the
5007 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00005008 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00005009 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00005010}
5011
John McCall3624e9e2012-12-20 02:45:14 +00005012static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5013 BuiltinType::Kind kind) {
5014 switch (kind) {
David Chisnall64fd7e82010-06-04 01:10:52 +00005015 case BuiltinType::Void: return 'v';
5016 case BuiltinType::Bool: return 'B';
5017 case BuiltinType::Char_U:
5018 case BuiltinType::UChar: return 'C';
John McCall3624e9e2012-12-20 02:45:14 +00005019 case BuiltinType::Char16:
David Chisnall64fd7e82010-06-04 01:10:52 +00005020 case BuiltinType::UShort: return 'S';
John McCall3624e9e2012-12-20 02:45:14 +00005021 case BuiltinType::Char32:
David Chisnall64fd7e82010-06-04 01:10:52 +00005022 case BuiltinType::UInt: return 'I';
5023 case BuiltinType::ULong:
John McCall3624e9e2012-12-20 02:45:14 +00005024 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnall64fd7e82010-06-04 01:10:52 +00005025 case BuiltinType::UInt128: return 'T';
5026 case BuiltinType::ULongLong: return 'Q';
5027 case BuiltinType::Char_S:
5028 case BuiltinType::SChar: return 'c';
5029 case BuiltinType::Short: return 's';
Chris Lattner3f59c972010-12-25 23:25:43 +00005030 case BuiltinType::WChar_S:
5031 case BuiltinType::WChar_U:
David Chisnall64fd7e82010-06-04 01:10:52 +00005032 case BuiltinType::Int: return 'i';
5033 case BuiltinType::Long:
John McCall3624e9e2012-12-20 02:45:14 +00005034 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnall64fd7e82010-06-04 01:10:52 +00005035 case BuiltinType::LongLong: return 'q';
5036 case BuiltinType::Int128: return 't';
5037 case BuiltinType::Float: return 'f';
5038 case BuiltinType::Double: return 'd';
Daniel Dunbar3a0be842010-10-11 21:13:48 +00005039 case BuiltinType::LongDouble: return 'D';
John McCall3624e9e2012-12-20 02:45:14 +00005040 case BuiltinType::NullPtr: return '*'; // like char*
5041
5042 case BuiltinType::Half:
5043 // FIXME: potentially need @encodes for these!
5044 return ' ';
5045
5046 case BuiltinType::ObjCId:
5047 case BuiltinType::ObjCClass:
5048 case BuiltinType::ObjCSel:
5049 llvm_unreachable("@encoding ObjC primitive type");
5050
5051 // OpenCL and placeholder types don't need @encodings.
5052 case BuiltinType::OCLImage1d:
5053 case BuiltinType::OCLImage1dArray:
5054 case BuiltinType::OCLImage1dBuffer:
5055 case BuiltinType::OCLImage2d:
5056 case BuiltinType::OCLImage2dArray:
5057 case BuiltinType::OCLImage3d:
Guy Benyeie6b9d802013-01-20 12:31:11 +00005058 case BuiltinType::OCLEvent:
Guy Benyei21f18c42013-02-07 10:55:47 +00005059 case BuiltinType::OCLSampler:
John McCall3624e9e2012-12-20 02:45:14 +00005060 case BuiltinType::Dependent:
5061#define BUILTIN_TYPE(KIND, ID)
5062#define PLACEHOLDER_TYPE(KIND, ID) \
5063 case BuiltinType::KIND:
5064#include "clang/AST/BuiltinTypes.def"
5065 llvm_unreachable("invalid builtin type for @encode");
David Chisnall64fd7e82010-06-04 01:10:52 +00005066 }
David Blaikie719e53f2013-01-09 17:48:41 +00005067 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnall64fd7e82010-06-04 01:10:52 +00005068}
5069
Douglas Gregor5471bc82011-09-08 17:18:35 +00005070static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5071 EnumDecl *Enum = ET->getDecl();
5072
5073 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5074 if (!Enum->isFixed())
5075 return 'i';
5076
5077 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall3624e9e2012-12-20 02:45:14 +00005078 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5079 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor5471bc82011-09-08 17:18:35 +00005080}
5081
Jay Foad4ba2a172011-01-12 09:06:06 +00005082static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00005083 QualType T, const FieldDecl *FD) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005084 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00005085 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00005086 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5087 // The GNU runtime requires more information; bitfields are encoded as b,
5088 // then the offset (in bits) of the first element, then the type of the
5089 // bitfield, then the size in bits. For example, in this structure:
5090 //
5091 // struct
5092 // {
5093 // int integer;
5094 // int flags:2;
5095 // };
5096 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5097 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5098 // information is not especially sensible, but we're stuck with it for
5099 // compatibility with GCC, although providing it breaks anything that
5100 // actually uses runtime introspection and wants to work on both runtimes...
John McCall260611a2012-06-20 06:18:46 +00005101 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnall64fd7e82010-06-04 01:10:52 +00005102 const RecordDecl *RD = FD->getParent();
5103 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedman82905742011-07-07 01:54:01 +00005104 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor5471bc82011-09-08 17:18:35 +00005105 if (const EnumType *ET = T->getAs<EnumType>())
5106 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall3624e9e2012-12-20 02:45:14 +00005107 else {
5108 const BuiltinType *BT = T->castAs<BuiltinType>();
5109 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5110 }
David Chisnall64fd7e82010-06-04 01:10:52 +00005111 }
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005112 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00005113}
5114
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00005115// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00005116void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5117 bool ExpandPointedToStructures,
5118 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00005119 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00005120 bool OutermostType,
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005121 bool EncodingProperty,
Bob Wilsondc8dab62011-11-30 01:57:58 +00005122 bool StructField,
5123 bool EncodeBlockParameters,
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005124 bool EncodeClassNames,
5125 bool EncodePointerToObjCTypedef) const {
John McCall3624e9e2012-12-20 02:45:14 +00005126 CanQualType CT = getCanonicalType(T);
5127 switch (CT->getTypeClass()) {
5128 case Type::Builtin:
5129 case Type::Enum:
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005130 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00005131 return EncodeBitField(this, S, T, FD);
John McCall3624e9e2012-12-20 02:45:14 +00005132 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5133 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5134 else
5135 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005136 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005137
John McCall3624e9e2012-12-20 02:45:14 +00005138 case Type::Complex: {
5139 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlssonc612f7b2009-04-09 21:55:45 +00005140 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00005141 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00005142 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005143 return;
5144 }
John McCall3624e9e2012-12-20 02:45:14 +00005145
5146 case Type::Atomic: {
5147 const AtomicType *AT = T->castAs<AtomicType>();
5148 S += 'A';
5149 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, 0,
5150 false, false);
5151 return;
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00005152 }
John McCall3624e9e2012-12-20 02:45:14 +00005153
5154 // encoding for pointer or reference types.
5155 case Type::Pointer:
5156 case Type::LValueReference:
5157 case Type::RValueReference: {
5158 QualType PointeeTy;
5159 if (isa<PointerType>(CT)) {
5160 const PointerType *PT = T->castAs<PointerType>();
5161 if (PT->isObjCSelType()) {
5162 S += ':';
5163 return;
5164 }
5165 PointeeTy = PT->getPointeeType();
5166 } else {
5167 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5168 }
5169
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005170 bool isReadOnly = false;
5171 // For historical/compatibility reasons, the read-only qualifier of the
5172 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5173 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00005174 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00005175 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005176 if (OutermostType && T.isConstQualified()) {
5177 isReadOnly = true;
5178 S += 'r';
5179 }
Mike Stump9fdbab32009-07-31 02:02:20 +00005180 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005181 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00005182 while (P->getAs<PointerType>())
5183 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005184 if (P.isConstQualified()) {
5185 isReadOnly = true;
5186 S += 'r';
5187 }
5188 }
5189 if (isReadOnly) {
5190 // Another legacy compatibility encoding. Some ObjC qualifier and type
5191 // combinations need to be rearranged.
5192 // Rewrite "in const" from "nr" to "rn"
Chris Lattner5f9e2722011-07-23 10:55:15 +00005193 if (StringRef(S).endswith("nr"))
Benjamin Kramer02379412010-04-27 17:12:11 +00005194 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005195 }
Mike Stump1eb44332009-09-09 15:08:12 +00005196
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005197 if (PointeeTy->isCharType()) {
5198 // char pointer types should be encoded as '*' unless it is a
5199 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00005200 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005201 S += '*';
5202 return;
5203 }
Ted Kremenek6217b802009-07-29 21:53:49 +00005204 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00005205 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5206 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5207 S += '#';
5208 return;
5209 }
5210 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5211 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5212 S += '@';
5213 return;
5214 }
5215 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005216 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005217 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005218 getLegacyIntegralTypeEncoding(PointeeTy);
5219
Mike Stump1eb44332009-09-09 15:08:12 +00005220 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005221 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005222 return;
5223 }
John McCall3624e9e2012-12-20 02:45:14 +00005224
5225 case Type::ConstantArray:
5226 case Type::IncompleteArray:
5227 case Type::VariableArray: {
5228 const ArrayType *AT = cast<ArrayType>(CT);
5229
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005230 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlsson559a8332009-02-22 01:38:57 +00005231 // Incomplete arrays are encoded as a pointer to the array element.
5232 S += '^';
5233
Mike Stump1eb44332009-09-09 15:08:12 +00005234 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00005235 false, ExpandStructures, FD);
5236 } else {
5237 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00005238
Fariborz Jahanian48eff6c2013-06-04 16:04:37 +00005239 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5240 S += llvm::utostr(CAT->getSize().getZExtValue());
5241 else {
Anders Carlsson559a8332009-02-22 01:38:57 +00005242 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005243 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5244 "Unknown array type!");
Anders Carlsson559a8332009-02-22 01:38:57 +00005245 S += '0';
5246 }
Mike Stump1eb44332009-09-09 15:08:12 +00005247
5248 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00005249 false, ExpandStructures, FD);
5250 S += ']';
5251 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005252 return;
5253 }
Mike Stump1eb44332009-09-09 15:08:12 +00005254
John McCall3624e9e2012-12-20 02:45:14 +00005255 case Type::FunctionNoProto:
5256 case Type::FunctionProto:
Anders Carlssonc0a87b72007-10-30 00:06:20 +00005257 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005258 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005259
John McCall3624e9e2012-12-20 02:45:14 +00005260 case Type::Record: {
5261 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005262 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00005263 // Anonymous structures print as '?'
5264 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5265 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00005266 if (ClassTemplateSpecializationDecl *Spec
5267 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5268 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer5eada842013-02-22 15:46:01 +00005269 llvm::raw_string_ostream OS(S);
5270 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor910f8002010-11-07 23:05:16 +00005271 TemplateArgs.data(),
5272 TemplateArgs.size(),
Douglas Gregor30c42402011-09-27 22:38:19 +00005273 (*this).getPrintingPolicy());
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00005274 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00005275 } else {
5276 S += '?';
5277 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00005278 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00005279 S += '=';
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005280 if (!RDecl->isUnion()) {
5281 getObjCEncodingForStructureImpl(RDecl, S, FD);
5282 } else {
5283 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5284 FieldEnd = RDecl->field_end();
5285 Field != FieldEnd; ++Field) {
5286 if (FD) {
5287 S += '"';
5288 S += Field->getNameAsString();
5289 S += '"';
5290 }
Mike Stump1eb44332009-09-09 15:08:12 +00005291
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005292 // Special case bit-fields.
5293 if (Field->isBitField()) {
5294 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie581deb32012-06-06 20:45:41 +00005295 *Field);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005296 } else {
5297 QualType qt = Field->getType();
5298 getLegacyIntegralTypeEncoding(qt);
5299 getObjCEncodingForTypeImpl(qt, S, false, true,
5300 FD, /*OutermostType*/false,
5301 /*EncodingProperty*/false,
5302 /*StructField*/true);
5303 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005304 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00005305 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00005306 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005307 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005308 return;
5309 }
Mike Stump1eb44332009-09-09 15:08:12 +00005310
John McCall3624e9e2012-12-20 02:45:14 +00005311 case Type::BlockPointer: {
5312 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff21a98b12009-02-02 18:24:29 +00005313 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilsondc8dab62011-11-30 01:57:58 +00005314 if (EncodeBlockParameters) {
John McCall3624e9e2012-12-20 02:45:14 +00005315 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilsondc8dab62011-11-30 01:57:58 +00005316
5317 S += '<';
5318 // Block return type
5319 getObjCEncodingForTypeImpl(FT->getResultType(), S,
5320 ExpandPointedToStructures, ExpandStructures,
5321 FD,
5322 false /* OutermostType */,
5323 EncodingProperty,
5324 false /* StructField */,
5325 EncodeBlockParameters,
5326 EncodeClassNames);
5327 // Block self
5328 S += "@?";
5329 // Block parameters
5330 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
5331 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
5332 E = FPT->arg_type_end(); I && (I != E); ++I) {
5333 getObjCEncodingForTypeImpl(*I, S,
5334 ExpandPointedToStructures,
5335 ExpandStructures,
5336 FD,
5337 false /* OutermostType */,
5338 EncodingProperty,
5339 false /* StructField */,
5340 EncodeBlockParameters,
5341 EncodeClassNames);
5342 }
5343 }
5344 S += '>';
5345 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005346 return;
5347 }
Mike Stump1eb44332009-09-09 15:08:12 +00005348
John McCall3624e9e2012-12-20 02:45:14 +00005349 case Type::ObjCObject:
5350 case Type::ObjCInterface: {
5351 // Ignore protocol qualifiers when mangling at this level.
5352 T = T->castAs<ObjCObjectType>()->getBaseType();
John McCallc12c5bb2010-05-15 11:32:37 +00005353
John McCall3624e9e2012-12-20 02:45:14 +00005354 // The assumption seems to be that this assert will succeed
5355 // because nested levels will have filtered out 'id' and 'Class'.
5356 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005357 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00005358 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005359 S += '{';
5360 const IdentifierInfo *II = OI->getIdentifier();
5361 S += II->getName();
5362 S += '=';
Jordy Rosedb8264e2011-07-22 02:08:32 +00005363 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00005364 DeepCollectObjCIvars(OI, true, Ivars);
5365 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00005366 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00005367 if (Field->isBitField())
5368 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005369 else
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005370 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5371 false, false, false, false, false,
5372 EncodePointerToObjCTypedef);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005373 }
5374 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005375 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005376 }
Mike Stump1eb44332009-09-09 15:08:12 +00005377
John McCall3624e9e2012-12-20 02:45:14 +00005378 case Type::ObjCObjectPointer: {
5379 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff14108da2009-07-10 23:34:53 +00005380 if (OPT->isObjCIdType()) {
5381 S += '@';
5382 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005383 }
Mike Stump1eb44332009-09-09 15:08:12 +00005384
Steve Naroff27d20a22009-10-28 22:03:49 +00005385 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5386 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5387 // Since this is a binary compatibility issue, need to consult with runtime
5388 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00005389 S += '#';
5390 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005391 }
Mike Stump1eb44332009-09-09 15:08:12 +00005392
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005393 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005394 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00005395 ExpandPointedToStructures,
5396 ExpandStructures, FD);
Bob Wilsondc8dab62011-11-30 01:57:58 +00005397 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff14108da2009-07-10 23:34:53 +00005398 // Note that we do extended encoding of protocol qualifer list
5399 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00005400 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005401 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5402 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00005403 S += '<';
5404 S += (*I)->getNameAsString();
5405 S += '>';
5406 }
5407 S += '"';
5408 }
5409 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005410 }
Mike Stump1eb44332009-09-09 15:08:12 +00005411
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005412 QualType PointeeTy = OPT->getPointeeType();
5413 if (!EncodingProperty &&
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005414 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5415 !EncodePointerToObjCTypedef) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005416 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00005417 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005418 // {...};
5419 S += '^';
Fariborz Jahanian361a3292013-07-12 16:19:11 +00005420 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc1310462013-07-12 16:41:56 +00005421 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian361a3292013-07-12 16:19:11 +00005422 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5423 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5424 DeepCollectObjCIvars(OI, true, Ivars);
5425 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5426 if (cast<FieldDecl>(Ivars[i]) == FD) {
5427 S += '{';
5428 S += OI->getIdentifier()->getName();
5429 S += '}';
5430 return;
5431 }
5432 }
5433 }
Mike Stump1eb44332009-09-09 15:08:12 +00005434 getObjCEncodingForTypeImpl(PointeeTy, S,
5435 false, ExpandPointedToStructures,
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005436 NULL,
5437 false, false, false, false, false,
5438 /*EncodePointerToObjCTypedef*/true);
Steve Naroff14108da2009-07-10 23:34:53 +00005439 return;
5440 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005441
5442 S += '@';
Bob Wilsondc8dab62011-11-30 01:57:58 +00005443 if (OPT->getInterfaceDecl() &&
5444 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005445 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00005446 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005447 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5448 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005449 S += '<';
5450 S += (*I)->getNameAsString();
5451 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00005452 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005453 S += '"';
5454 }
5455 return;
5456 }
Mike Stump1eb44332009-09-09 15:08:12 +00005457
John McCall532ec7b2010-05-17 23:56:34 +00005458 // gcc just blithely ignores member pointers.
John McCall3624e9e2012-12-20 02:45:14 +00005459 // FIXME: we shoul do better than that. 'M' is available.
5460 case Type::MemberPointer:
John McCall532ec7b2010-05-17 23:56:34 +00005461 return;
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005462
John McCall3624e9e2012-12-20 02:45:14 +00005463 case Type::Vector:
5464 case Type::ExtVector:
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005465 // This matches gcc's encoding, even though technically it is
5466 // insufficient.
5467 // FIXME. We should do a better job than gcc.
5468 return;
John McCall3624e9e2012-12-20 02:45:14 +00005469
Richard Smithdc7a4f52013-04-30 13:56:41 +00005470 case Type::Auto:
5471 // We could see an undeduced auto type here during error recovery.
5472 // Just ignore it.
5473 return;
5474
John McCall3624e9e2012-12-20 02:45:14 +00005475#define ABSTRACT_TYPE(KIND, BASE)
5476#define TYPE(KIND, BASE)
5477#define DEPENDENT_TYPE(KIND, BASE) \
5478 case Type::KIND:
5479#define NON_CANONICAL_TYPE(KIND, BASE) \
5480 case Type::KIND:
5481#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5482 case Type::KIND:
5483#include "clang/AST/TypeNodes.def"
5484 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005485 }
John McCall3624e9e2012-12-20 02:45:14 +00005486 llvm_unreachable("bad type kind!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005487}
5488
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005489void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5490 std::string &S,
5491 const FieldDecl *FD,
5492 bool includeVBases) const {
5493 assert(RDecl && "Expected non-null RecordDecl");
5494 assert(!RDecl->isUnion() && "Should not be called for unions");
5495 if (!RDecl->getDefinition())
5496 return;
5497
5498 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5499 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5500 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5501
5502 if (CXXRec) {
5503 for (CXXRecordDecl::base_class_iterator
5504 BI = CXXRec->bases_begin(),
5505 BE = CXXRec->bases_end(); BI != BE; ++BI) {
5506 if (!BI->isVirtual()) {
5507 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005508 if (base->isEmpty())
5509 continue;
Benjamin Kramerd4f51982012-07-04 18:45:14 +00005510 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005511 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5512 std::make_pair(offs, base));
5513 }
5514 }
5515 }
5516
5517 unsigned i = 0;
5518 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5519 FieldEnd = RDecl->field_end();
5520 Field != FieldEnd; ++Field, ++i) {
5521 uint64_t offs = layout.getFieldOffset(i);
5522 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie581deb32012-06-06 20:45:41 +00005523 std::make_pair(offs, *Field));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005524 }
5525
5526 if (CXXRec && includeVBases) {
5527 for (CXXRecordDecl::base_class_iterator
5528 BI = CXXRec->vbases_begin(),
5529 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
5530 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005531 if (base->isEmpty())
5532 continue;
Benjamin Kramerd4f51982012-07-04 18:45:14 +00005533 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Argyrios Kyrtzidis19aa8602011-09-26 18:14:24 +00005534 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
5535 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5536 std::make_pair(offs, base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005537 }
5538 }
5539
5540 CharUnits size;
5541 if (CXXRec) {
5542 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5543 } else {
5544 size = layout.getSize();
5545 }
5546
5547 uint64_t CurOffs = 0;
5548 std::multimap<uint64_t, NamedDecl *>::iterator
5549 CurLayObj = FieldOrBaseOffsets.begin();
5550
Douglas Gregor58db7a52012-04-27 22:30:01 +00005551 if (CXXRec && CXXRec->isDynamicClass() &&
5552 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005553 if (FD) {
5554 S += "\"_vptr$";
5555 std::string recname = CXXRec->getNameAsString();
5556 if (recname.empty()) recname = "?";
5557 S += recname;
5558 S += '"';
5559 }
5560 S += "^^?";
5561 CurOffs += getTypeSize(VoidPtrTy);
5562 }
5563
5564 if (!RDecl->hasFlexibleArrayMember()) {
5565 // Mark the end of the structure.
5566 uint64_t offs = toBits(size);
5567 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5568 std::make_pair(offs, (NamedDecl*)0));
5569 }
5570
5571 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5572 assert(CurOffs <= CurLayObj->first);
5573
5574 if (CurOffs < CurLayObj->first) {
5575 uint64_t padding = CurLayObj->first - CurOffs;
5576 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5577 // packing/alignment of members is different that normal, in which case
5578 // the encoding will be out-of-sync with the real layout.
5579 // If the runtime switches to just consider the size of types without
5580 // taking into account alignment, we could make padding explicit in the
5581 // encoding (e.g. using arrays of chars). The encoding strings would be
5582 // longer then though.
5583 CurOffs += padding;
5584 }
5585
5586 NamedDecl *dcl = CurLayObj->second;
5587 if (dcl == 0)
5588 break; // reached end of structure.
5589
5590 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5591 // We expand the bases without their virtual bases since those are going
5592 // in the initial structure. Note that this differs from gcc which
5593 // expands virtual bases each time one is encountered in the hierarchy,
5594 // making the encoding type bigger than it really is.
5595 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005596 assert(!base->isEmpty());
5597 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005598 } else {
5599 FieldDecl *field = cast<FieldDecl>(dcl);
5600 if (FD) {
5601 S += '"';
5602 S += field->getNameAsString();
5603 S += '"';
5604 }
5605
5606 if (field->isBitField()) {
5607 EncodeBitField(this, S, field->getType(), field);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005608 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005609 } else {
5610 QualType qt = field->getType();
5611 getLegacyIntegralTypeEncoding(qt);
5612 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5613 /*OutermostType*/false,
5614 /*EncodingProperty*/false,
5615 /*StructField*/true);
5616 CurOffs += getTypeSize(field->getType());
5617 }
5618 }
5619 }
5620}
5621
Mike Stump1eb44332009-09-09 15:08:12 +00005622void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00005623 std::string& S) const {
5624 if (QT & Decl::OBJC_TQ_In)
5625 S += 'n';
5626 if (QT & Decl::OBJC_TQ_Inout)
5627 S += 'N';
5628 if (QT & Decl::OBJC_TQ_Out)
5629 S += 'o';
5630 if (QT & Decl::OBJC_TQ_Bycopy)
5631 S += 'O';
5632 if (QT & Decl::OBJC_TQ_Byref)
5633 S += 'R';
5634 if (QT & Decl::OBJC_TQ_Oneway)
5635 S += 'V';
5636}
5637
Douglas Gregor4dfd02a2011-08-12 05:46:01 +00005638TypedefDecl *ASTContext::getObjCIdDecl() const {
5639 if (!ObjCIdDecl) {
5640 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5641 T = getObjCObjectPointerType(T);
5642 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
5643 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5644 getTranslationUnitDecl(),
5645 SourceLocation(), SourceLocation(),
5646 &Idents.get("id"), IdInfo);
5647 }
5648
5649 return ObjCIdDecl;
Steve Naroff7e219e42007-10-15 14:41:52 +00005650}
5651
Douglas Gregor7a27ea52011-08-12 06:17:30 +00005652TypedefDecl *ASTContext::getObjCSelDecl() const {
5653 if (!ObjCSelDecl) {
5654 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5655 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5656 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5657 getTranslationUnitDecl(),
5658 SourceLocation(), SourceLocation(),
5659 &Idents.get("SEL"), SelInfo);
5660 }
5661 return ObjCSelDecl;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00005662}
5663
Douglas Gregor79d67262011-08-12 05:59:41 +00005664TypedefDecl *ASTContext::getObjCClassDecl() const {
5665 if (!ObjCClassDecl) {
5666 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5667 T = getObjCObjectPointerType(T);
5668 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5669 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5670 getTranslationUnitDecl(),
5671 SourceLocation(), SourceLocation(),
5672 &Idents.get("Class"), ClassInfo);
5673 }
5674
5675 return ObjCClassDecl;
Anders Carlsson8baaca52007-10-31 02:53:19 +00005676}
5677
Douglas Gregora6ea10e2012-01-17 18:09:05 +00005678ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5679 if (!ObjCProtocolClassDecl) {
5680 ObjCProtocolClassDecl
5681 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5682 SourceLocation(),
5683 &Idents.get("Protocol"),
5684 /*PrevDecl=*/0,
5685 SourceLocation(), true);
5686 }
5687
5688 return ObjCProtocolClassDecl;
5689}
5690
Meador Ingec5613b22012-06-16 03:34:49 +00005691//===----------------------------------------------------------------------===//
5692// __builtin_va_list Construction Functions
5693//===----------------------------------------------------------------------===//
5694
5695static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5696 // typedef char* __builtin_va_list;
5697 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5698 TypeSourceInfo *TInfo
5699 = Context->getTrivialTypeSourceInfo(CharPtrType);
5700
5701 TypedefDecl *VaListTypeDecl
5702 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5703 Context->getTranslationUnitDecl(),
5704 SourceLocation(), SourceLocation(),
5705 &Context->Idents.get("__builtin_va_list"),
5706 TInfo);
5707 return VaListTypeDecl;
5708}
5709
5710static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5711 // typedef void* __builtin_va_list;
5712 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5713 TypeSourceInfo *TInfo
5714 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5715
5716 TypedefDecl *VaListTypeDecl
5717 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5718 Context->getTranslationUnitDecl(),
5719 SourceLocation(), SourceLocation(),
5720 &Context->Idents.get("__builtin_va_list"),
5721 TInfo);
5722 return VaListTypeDecl;
5723}
5724
Tim Northoverc264e162013-01-31 12:13:10 +00005725static TypedefDecl *
5726CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
5727 RecordDecl *VaListTagDecl;
5728 if (Context->getLangOpts().CPlusPlus) {
5729 // namespace std { struct __va_list {
5730 NamespaceDecl *NS;
5731 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5732 Context->getTranslationUnitDecl(),
5733 /*Inline*/false, SourceLocation(),
5734 SourceLocation(), &Context->Idents.get("std"),
5735 /*PrevDecl*/0);
5736
5737 VaListTagDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5738 Context->getTranslationUnitDecl(),
5739 SourceLocation(), SourceLocation(),
5740 &Context->Idents.get("__va_list"));
5741 VaListTagDecl->setDeclContext(NS);
5742 } else {
5743 // struct __va_list
5744 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5745 Context->getTranslationUnitDecl(),
5746 &Context->Idents.get("__va_list"));
5747 }
5748
5749 VaListTagDecl->startDefinition();
5750
5751 const size_t NumFields = 5;
5752 QualType FieldTypes[NumFields];
5753 const char *FieldNames[NumFields];
5754
5755 // void *__stack;
5756 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
5757 FieldNames[0] = "__stack";
5758
5759 // void *__gr_top;
5760 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
5761 FieldNames[1] = "__gr_top";
5762
5763 // void *__vr_top;
5764 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5765 FieldNames[2] = "__vr_top";
5766
5767 // int __gr_offs;
5768 FieldTypes[3] = Context->IntTy;
5769 FieldNames[3] = "__gr_offs";
5770
5771 // int __vr_offs;
5772 FieldTypes[4] = Context->IntTy;
5773 FieldNames[4] = "__vr_offs";
5774
5775 // Create fields
5776 for (unsigned i = 0; i < NumFields; ++i) {
5777 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5778 VaListTagDecl,
5779 SourceLocation(),
5780 SourceLocation(),
5781 &Context->Idents.get(FieldNames[i]),
5782 FieldTypes[i], /*TInfo=*/0,
5783 /*BitWidth=*/0,
5784 /*Mutable=*/false,
5785 ICIS_NoInit);
5786 Field->setAccess(AS_public);
5787 VaListTagDecl->addDecl(Field);
5788 }
5789 VaListTagDecl->completeDefinition();
5790 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5791 Context->VaListTagTy = VaListTagType;
5792
5793 // } __builtin_va_list;
5794 TypedefDecl *VaListTypedefDecl
5795 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5796 Context->getTranslationUnitDecl(),
5797 SourceLocation(), SourceLocation(),
5798 &Context->Idents.get("__builtin_va_list"),
5799 Context->getTrivialTypeSourceInfo(VaListTagType));
5800
5801 return VaListTypedefDecl;
5802}
5803
Meador Ingec5613b22012-06-16 03:34:49 +00005804static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5805 // typedef struct __va_list_tag {
5806 RecordDecl *VaListTagDecl;
5807
5808 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5809 Context->getTranslationUnitDecl(),
5810 &Context->Idents.get("__va_list_tag"));
5811 VaListTagDecl->startDefinition();
5812
5813 const size_t NumFields = 5;
5814 QualType FieldTypes[NumFields];
5815 const char *FieldNames[NumFields];
5816
5817 // unsigned char gpr;
5818 FieldTypes[0] = Context->UnsignedCharTy;
5819 FieldNames[0] = "gpr";
5820
5821 // unsigned char fpr;
5822 FieldTypes[1] = Context->UnsignedCharTy;
5823 FieldNames[1] = "fpr";
5824
5825 // unsigned short reserved;
5826 FieldTypes[2] = Context->UnsignedShortTy;
5827 FieldNames[2] = "reserved";
5828
5829 // void* overflow_arg_area;
5830 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5831 FieldNames[3] = "overflow_arg_area";
5832
5833 // void* reg_save_area;
5834 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5835 FieldNames[4] = "reg_save_area";
5836
5837 // Create fields
5838 for (unsigned i = 0; i < NumFields; ++i) {
5839 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5840 SourceLocation(),
5841 SourceLocation(),
5842 &Context->Idents.get(FieldNames[i]),
5843 FieldTypes[i], /*TInfo=*/0,
5844 /*BitWidth=*/0,
5845 /*Mutable=*/false,
5846 ICIS_NoInit);
5847 Field->setAccess(AS_public);
5848 VaListTagDecl->addDecl(Field);
5849 }
5850 VaListTagDecl->completeDefinition();
5851 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingefb40e3f2012-07-01 15:57:25 +00005852 Context->VaListTagTy = VaListTagType;
Meador Ingec5613b22012-06-16 03:34:49 +00005853
5854 // } __va_list_tag;
5855 TypedefDecl *VaListTagTypedefDecl
5856 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5857 Context->getTranslationUnitDecl(),
5858 SourceLocation(), SourceLocation(),
5859 &Context->Idents.get("__va_list_tag"),
5860 Context->getTrivialTypeSourceInfo(VaListTagType));
5861 QualType VaListTagTypedefType =
5862 Context->getTypedefType(VaListTagTypedefDecl);
5863
5864 // typedef __va_list_tag __builtin_va_list[1];
5865 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5866 QualType VaListTagArrayType
5867 = Context->getConstantArrayType(VaListTagTypedefType,
5868 Size, ArrayType::Normal, 0);
5869 TypeSourceInfo *TInfo
5870 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5871 TypedefDecl *VaListTypedefDecl
5872 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5873 Context->getTranslationUnitDecl(),
5874 SourceLocation(), SourceLocation(),
5875 &Context->Idents.get("__builtin_va_list"),
5876 TInfo);
5877
5878 return VaListTypedefDecl;
5879}
5880
5881static TypedefDecl *
5882CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5883 // typedef struct __va_list_tag {
5884 RecordDecl *VaListTagDecl;
5885 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5886 Context->getTranslationUnitDecl(),
5887 &Context->Idents.get("__va_list_tag"));
5888 VaListTagDecl->startDefinition();
5889
5890 const size_t NumFields = 4;
5891 QualType FieldTypes[NumFields];
5892 const char *FieldNames[NumFields];
5893
5894 // unsigned gp_offset;
5895 FieldTypes[0] = Context->UnsignedIntTy;
5896 FieldNames[0] = "gp_offset";
5897
5898 // unsigned fp_offset;
5899 FieldTypes[1] = Context->UnsignedIntTy;
5900 FieldNames[1] = "fp_offset";
5901
5902 // void* overflow_arg_area;
5903 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5904 FieldNames[2] = "overflow_arg_area";
5905
5906 // void* reg_save_area;
5907 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5908 FieldNames[3] = "reg_save_area";
5909
5910 // Create fields
5911 for (unsigned i = 0; i < NumFields; ++i) {
5912 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5913 VaListTagDecl,
5914 SourceLocation(),
5915 SourceLocation(),
5916 &Context->Idents.get(FieldNames[i]),
5917 FieldTypes[i], /*TInfo=*/0,
5918 /*BitWidth=*/0,
5919 /*Mutable=*/false,
5920 ICIS_NoInit);
5921 Field->setAccess(AS_public);
5922 VaListTagDecl->addDecl(Field);
5923 }
5924 VaListTagDecl->completeDefinition();
5925 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingefb40e3f2012-07-01 15:57:25 +00005926 Context->VaListTagTy = VaListTagType;
Meador Ingec5613b22012-06-16 03:34:49 +00005927
5928 // } __va_list_tag;
5929 TypedefDecl *VaListTagTypedefDecl
5930 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5931 Context->getTranslationUnitDecl(),
5932 SourceLocation(), SourceLocation(),
5933 &Context->Idents.get("__va_list_tag"),
5934 Context->getTrivialTypeSourceInfo(VaListTagType));
5935 QualType VaListTagTypedefType =
5936 Context->getTypedefType(VaListTagTypedefDecl);
5937
5938 // typedef __va_list_tag __builtin_va_list[1];
5939 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5940 QualType VaListTagArrayType
5941 = Context->getConstantArrayType(VaListTagTypedefType,
5942 Size, ArrayType::Normal,0);
5943 TypeSourceInfo *TInfo
5944 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5945 TypedefDecl *VaListTypedefDecl
5946 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5947 Context->getTranslationUnitDecl(),
5948 SourceLocation(), SourceLocation(),
5949 &Context->Idents.get("__builtin_va_list"),
5950 TInfo);
5951
5952 return VaListTypedefDecl;
5953}
5954
5955static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5956 // typedef int __builtin_va_list[4];
5957 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5958 QualType IntArrayType
5959 = Context->getConstantArrayType(Context->IntTy,
5960 Size, ArrayType::Normal, 0);
5961 TypedefDecl *VaListTypedefDecl
5962 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5963 Context->getTranslationUnitDecl(),
5964 SourceLocation(), SourceLocation(),
5965 &Context->Idents.get("__builtin_va_list"),
5966 Context->getTrivialTypeSourceInfo(IntArrayType));
5967
5968 return VaListTypedefDecl;
5969}
5970
Logan Chieneae5a8202012-10-10 06:56:20 +00005971static TypedefDecl *
5972CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
5973 RecordDecl *VaListDecl;
5974 if (Context->getLangOpts().CPlusPlus) {
5975 // namespace std { struct __va_list {
5976 NamespaceDecl *NS;
5977 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5978 Context->getTranslationUnitDecl(),
5979 /*Inline*/false, SourceLocation(),
5980 SourceLocation(), &Context->Idents.get("std"),
5981 /*PrevDecl*/0);
5982
5983 VaListDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5984 Context->getTranslationUnitDecl(),
5985 SourceLocation(), SourceLocation(),
5986 &Context->Idents.get("__va_list"));
5987
5988 VaListDecl->setDeclContext(NS);
5989
5990 } else {
5991 // struct __va_list {
5992 VaListDecl = CreateRecordDecl(*Context, TTK_Struct,
5993 Context->getTranslationUnitDecl(),
5994 &Context->Idents.get("__va_list"));
5995 }
5996
5997 VaListDecl->startDefinition();
5998
5999 // void * __ap;
6000 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6001 VaListDecl,
6002 SourceLocation(),
6003 SourceLocation(),
6004 &Context->Idents.get("__ap"),
6005 Context->getPointerType(Context->VoidTy),
6006 /*TInfo=*/0,
6007 /*BitWidth=*/0,
6008 /*Mutable=*/false,
6009 ICIS_NoInit);
6010 Field->setAccess(AS_public);
6011 VaListDecl->addDecl(Field);
6012
6013 // };
6014 VaListDecl->completeDefinition();
6015
6016 // typedef struct __va_list __builtin_va_list;
6017 TypeSourceInfo *TInfo
6018 = Context->getTrivialTypeSourceInfo(Context->getRecordType(VaListDecl));
6019
6020 TypedefDecl *VaListTypeDecl
6021 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6022 Context->getTranslationUnitDecl(),
6023 SourceLocation(), SourceLocation(),
6024 &Context->Idents.get("__builtin_va_list"),
6025 TInfo);
6026
6027 return VaListTypeDecl;
6028}
6029
Ulrich Weigandb8409212013-05-06 16:26:41 +00006030static TypedefDecl *
6031CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
6032 // typedef struct __va_list_tag {
6033 RecordDecl *VaListTagDecl;
6034 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
6035 Context->getTranslationUnitDecl(),
6036 &Context->Idents.get("__va_list_tag"));
6037 VaListTagDecl->startDefinition();
6038
6039 const size_t NumFields = 4;
6040 QualType FieldTypes[NumFields];
6041 const char *FieldNames[NumFields];
6042
6043 // long __gpr;
6044 FieldTypes[0] = Context->LongTy;
6045 FieldNames[0] = "__gpr";
6046
6047 // long __fpr;
6048 FieldTypes[1] = Context->LongTy;
6049 FieldNames[1] = "__fpr";
6050
6051 // void *__overflow_arg_area;
6052 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6053 FieldNames[2] = "__overflow_arg_area";
6054
6055 // void *__reg_save_area;
6056 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6057 FieldNames[3] = "__reg_save_area";
6058
6059 // Create fields
6060 for (unsigned i = 0; i < NumFields; ++i) {
6061 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6062 VaListTagDecl,
6063 SourceLocation(),
6064 SourceLocation(),
6065 &Context->Idents.get(FieldNames[i]),
6066 FieldTypes[i], /*TInfo=*/0,
6067 /*BitWidth=*/0,
6068 /*Mutable=*/false,
6069 ICIS_NoInit);
6070 Field->setAccess(AS_public);
6071 VaListTagDecl->addDecl(Field);
6072 }
6073 VaListTagDecl->completeDefinition();
6074 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6075 Context->VaListTagTy = VaListTagType;
6076
6077 // } __va_list_tag;
6078 TypedefDecl *VaListTagTypedefDecl
6079 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6080 Context->getTranslationUnitDecl(),
6081 SourceLocation(), SourceLocation(),
6082 &Context->Idents.get("__va_list_tag"),
6083 Context->getTrivialTypeSourceInfo(VaListTagType));
6084 QualType VaListTagTypedefType =
6085 Context->getTypedefType(VaListTagTypedefDecl);
6086
6087 // typedef __va_list_tag __builtin_va_list[1];
6088 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6089 QualType VaListTagArrayType
6090 = Context->getConstantArrayType(VaListTagTypedefType,
6091 Size, ArrayType::Normal,0);
6092 TypeSourceInfo *TInfo
6093 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
6094 TypedefDecl *VaListTypedefDecl
6095 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6096 Context->getTranslationUnitDecl(),
6097 SourceLocation(), SourceLocation(),
6098 &Context->Idents.get("__builtin_va_list"),
6099 TInfo);
6100
6101 return VaListTypedefDecl;
6102}
6103
Meador Ingec5613b22012-06-16 03:34:49 +00006104static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6105 TargetInfo::BuiltinVaListKind Kind) {
6106 switch (Kind) {
6107 case TargetInfo::CharPtrBuiltinVaList:
6108 return CreateCharPtrBuiltinVaListDecl(Context);
6109 case TargetInfo::VoidPtrBuiltinVaList:
6110 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northoverc264e162013-01-31 12:13:10 +00006111 case TargetInfo::AArch64ABIBuiltinVaList:
6112 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Ingec5613b22012-06-16 03:34:49 +00006113 case TargetInfo::PowerABIBuiltinVaList:
6114 return CreatePowerABIBuiltinVaListDecl(Context);
6115 case TargetInfo::X86_64ABIBuiltinVaList:
6116 return CreateX86_64ABIBuiltinVaListDecl(Context);
6117 case TargetInfo::PNaClABIBuiltinVaList:
6118 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chieneae5a8202012-10-10 06:56:20 +00006119 case TargetInfo::AAPCSABIBuiltinVaList:
6120 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigandb8409212013-05-06 16:26:41 +00006121 case TargetInfo::SystemZBuiltinVaList:
6122 return CreateSystemZBuiltinVaListDecl(Context);
Meador Ingec5613b22012-06-16 03:34:49 +00006123 }
6124
6125 llvm_unreachable("Unhandled __builtin_va_list type kind");
6126}
6127
6128TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
6129 if (!BuiltinVaListDecl)
6130 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
6131
6132 return BuiltinVaListDecl;
6133}
6134
Meador Ingefb40e3f2012-07-01 15:57:25 +00006135QualType ASTContext::getVaListTagType() const {
6136 // Force the creation of VaListTagTy by building the __builtin_va_list
6137 // declaration.
6138 if (VaListTagTy.isNull())
6139 (void) getBuiltinVaListDecl();
6140
6141 return VaListTagTy;
6142}
6143
Ted Kremeneka526c5c2008-01-07 19:49:32 +00006144void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00006145 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00006146 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00006147
Ted Kremeneka526c5c2008-01-07 19:49:32 +00006148 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00006149}
6150
John McCall0bd6feb2009-12-02 08:04:21 +00006151/// \brief Retrieve the template name that corresponds to a non-empty
6152/// lookup.
Jay Foad4ba2a172011-01-12 09:06:06 +00006153TemplateName
6154ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6155 UnresolvedSetIterator End) const {
John McCall0bd6feb2009-12-02 08:04:21 +00006156 unsigned size = End - Begin;
6157 assert(size > 1 && "set is not overloaded!");
6158
6159 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6160 size * sizeof(FunctionTemplateDecl*));
6161 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6162
6163 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00006164 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00006165 NamedDecl *D = *I;
6166 assert(isa<FunctionTemplateDecl>(D) ||
6167 (isa<UsingShadowDecl>(D) &&
6168 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6169 *Storage++ = D;
6170 }
6171
6172 return TemplateName(OT);
6173}
6174
Douglas Gregor7532dc62009-03-30 22:58:21 +00006175/// \brief Retrieve the template name that represents a qualified
6176/// template name such as \c std::vector.
Jay Foad4ba2a172011-01-12 09:06:06 +00006177TemplateName
6178ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6179 bool TemplateKeyword,
6180 TemplateDecl *Template) const {
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00006181 assert(NNS && "Missing nested-name-specifier in qualified template name");
6182
Douglas Gregor789b1f62010-02-04 18:10:26 +00006183 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00006184 llvm::FoldingSetNodeID ID;
6185 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6186
6187 void *InsertPos = 0;
6188 QualifiedTemplateName *QTN =
6189 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6190 if (!QTN) {
Richard Smith2f47cab2012-08-16 01:19:31 +00006191 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6192 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregor7532dc62009-03-30 22:58:21 +00006193 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6194 }
6195
6196 return TemplateName(QTN);
6197}
6198
6199/// \brief Retrieve the template name that represents a dependent
6200/// template name such as \c MetaFun::template apply.
Jay Foad4ba2a172011-01-12 09:06:06 +00006201TemplateName
6202ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6203 const IdentifierInfo *Name) const {
Mike Stump1eb44332009-09-09 15:08:12 +00006204 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00006205 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00006206
6207 llvm::FoldingSetNodeID ID;
6208 DependentTemplateName::Profile(ID, NNS, Name);
6209
6210 void *InsertPos = 0;
6211 DependentTemplateName *QTN =
6212 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6213
6214 if (QTN)
6215 return TemplateName(QTN);
6216
6217 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6218 if (CanonNNS == NNS) {
Richard Smith2f47cab2012-08-16 01:19:31 +00006219 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6220 DependentTemplateName(NNS, Name);
Douglas Gregor7532dc62009-03-30 22:58:21 +00006221 } else {
6222 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smith2f47cab2012-08-16 01:19:31 +00006223 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6224 DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00006225 DependentTemplateName *CheckQTN =
6226 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6227 assert(!CheckQTN && "Dependent type name canonicalization broken");
6228 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00006229 }
6230
6231 DependentTemplateNames.InsertNode(QTN, InsertPos);
6232 return TemplateName(QTN);
6233}
6234
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006235/// \brief Retrieve the template name that represents a dependent
6236/// template name such as \c MetaFun::template operator+.
6237TemplateName
6238ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00006239 OverloadedOperatorKind Operator) const {
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006240 assert((!NNS || NNS->isDependent()) &&
6241 "Nested name specifier must be dependent");
6242
6243 llvm::FoldingSetNodeID ID;
6244 DependentTemplateName::Profile(ID, NNS, Operator);
6245
6246 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00006247 DependentTemplateName *QTN
6248 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006249
6250 if (QTN)
6251 return TemplateName(QTN);
6252
6253 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6254 if (CanonNNS == NNS) {
Richard Smith2f47cab2012-08-16 01:19:31 +00006255 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6256 DependentTemplateName(NNS, Operator);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006257 } else {
6258 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smith2f47cab2012-08-16 01:19:31 +00006259 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6260 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00006261
6262 DependentTemplateName *CheckQTN
6263 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6264 assert(!CheckQTN && "Dependent template name canonicalization broken");
6265 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006266 }
6267
6268 DependentTemplateNames.InsertNode(QTN, InsertPos);
6269 return TemplateName(QTN);
6270}
6271
Douglas Gregor1aee05d2011-01-15 06:45:20 +00006272TemplateName
John McCall14606042011-06-30 08:33:18 +00006273ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6274 TemplateName replacement) const {
6275 llvm::FoldingSetNodeID ID;
6276 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
6277
6278 void *insertPos = 0;
6279 SubstTemplateTemplateParmStorage *subst
6280 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6281
6282 if (!subst) {
6283 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6284 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6285 }
6286
6287 return TemplateName(subst);
6288}
6289
6290TemplateName
Douglas Gregor1aee05d2011-01-15 06:45:20 +00006291ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6292 const TemplateArgument &ArgPack) const {
6293 ASTContext &Self = const_cast<ASTContext &>(*this);
6294 llvm::FoldingSetNodeID ID;
6295 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
6296
6297 void *InsertPos = 0;
6298 SubstTemplateTemplateParmPackStorage *Subst
6299 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6300
6301 if (!Subst) {
John McCall14606042011-06-30 08:33:18 +00006302 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor1aee05d2011-01-15 06:45:20 +00006303 ArgPack.pack_size(),
6304 ArgPack.pack_begin());
6305 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6306 }
6307
6308 return TemplateName(Subst);
6309}
6310
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006311/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00006312/// TargetInfo, produce the corresponding type. The unsigned @p Type
6313/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00006314CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006315 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00006316 case TargetInfo::NoInt: return CanQualType();
Stepan Dyatkovskiy7b7bef12013-09-05 11:23:21 +00006317 case TargetInfo::SignedChar: return SignedCharTy;
6318 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006319 case TargetInfo::SignedShort: return ShortTy;
6320 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6321 case TargetInfo::SignedInt: return IntTy;
6322 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6323 case TargetInfo::SignedLong: return LongTy;
6324 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6325 case TargetInfo::SignedLongLong: return LongLongTy;
6326 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6327 }
6328
David Blaikieb219cfc2011-09-23 05:06:16 +00006329 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006330}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00006331
6332//===----------------------------------------------------------------------===//
6333// Type Predicates.
6334//===----------------------------------------------------------------------===//
6335
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00006336/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6337/// garbage collection attribute.
6338///
John McCallae278a32011-01-12 00:34:59 +00006339Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikie4e4d0842012-03-11 07:00:24 +00006340 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCallae278a32011-01-12 00:34:59 +00006341 return Qualifiers::GCNone;
6342
David Blaikie4e4d0842012-03-11 07:00:24 +00006343 assert(getLangOpts().ObjC1);
John McCallae278a32011-01-12 00:34:59 +00006344 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6345
6346 // Default behaviour under objective-C's gc is for ObjC pointers
6347 // (or pointers to them) be treated as though they were declared
6348 // as __strong.
6349 if (GCAttrs == Qualifiers::GCNone) {
6350 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6351 return Qualifiers::Strong;
6352 else if (Ty->isPointerType())
6353 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6354 } else {
6355 // It's not valid to set GC attributes on anything that isn't a
6356 // pointer.
6357#ifndef NDEBUG
6358 QualType CT = Ty->getCanonicalTypeInternal();
6359 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6360 CT = AT->getElementType();
6361 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6362#endif
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00006363 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00006364 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00006365}
6366
Chris Lattner6ac46a42008-04-07 06:51:04 +00006367//===----------------------------------------------------------------------===//
6368// Type Compatibility Testing
6369//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00006370
Mike Stump1eb44332009-09-09 15:08:12 +00006371/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00006372/// compatible.
6373static bool areCompatVectorTypes(const VectorType *LHS,
6374 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00006375 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00006376 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00006377 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00006378}
6379
Douglas Gregor255210e2010-08-06 10:14:59 +00006380bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6381 QualType SecondVec) {
6382 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6383 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6384
6385 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6386 return true;
6387
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00006388 // Treat Neon vector types and most AltiVec vector types as if they are the
6389 // equivalent GCC vector types.
Douglas Gregor255210e2010-08-06 10:14:59 +00006390 const VectorType *First = FirstVec->getAs<VectorType>();
6391 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00006392 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor255210e2010-08-06 10:14:59 +00006393 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00006394 First->getVectorKind() != VectorType::AltiVecPixel &&
6395 First->getVectorKind() != VectorType::AltiVecBool &&
6396 Second->getVectorKind() != VectorType::AltiVecPixel &&
6397 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor255210e2010-08-06 10:14:59 +00006398 return true;
6399
6400 return false;
6401}
6402
Steve Naroff4084c302009-07-23 01:01:38 +00006403//===----------------------------------------------------------------------===//
6404// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6405//===----------------------------------------------------------------------===//
6406
6407/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6408/// inheritance hierarchy of 'rProto'.
Jay Foad4ba2a172011-01-12 09:06:06 +00006409bool
6410ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6411 ObjCProtocolDecl *rProto) const {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00006412 if (declaresSameEntity(lProto, rProto))
Steve Naroff4084c302009-07-23 01:01:38 +00006413 return true;
6414 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
6415 E = rProto->protocol_end(); PI != E; ++PI)
6416 if (ProtocolCompatibleWithProtocol(lProto, *PI))
6417 return true;
6418 return false;
6419}
6420
Dmitri Gribenko4c3b8a32012-08-28 02:49:14 +00006421/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6422/// Class<pr1, ...>.
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00006423bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6424 QualType rhs) {
6425 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6426 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6427 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6428
6429 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6430 E = lhsQID->qual_end(); I != E; ++I) {
6431 bool match = false;
6432 ObjCProtocolDecl *lhsProto = *I;
6433 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6434 E = rhsOPT->qual_end(); J != E; ++J) {
6435 ObjCProtocolDecl *rhsProto = *J;
6436 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6437 match = true;
6438 break;
6439 }
6440 }
6441 if (!match)
6442 return false;
6443 }
6444 return true;
6445}
6446
Steve Naroff4084c302009-07-23 01:01:38 +00006447/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6448/// ObjCQualifiedIDType.
6449bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6450 bool compare) {
6451 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00006452 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00006453 lhs->isObjCIdType() || lhs->isObjCClassType())
6454 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00006455 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00006456 rhs->isObjCIdType() || rhs->isObjCClassType())
6457 return true;
6458
6459 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00006460 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00006461
Steve Naroff4084c302009-07-23 01:01:38 +00006462 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006463
Steve Naroff4084c302009-07-23 01:01:38 +00006464 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006465 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00006466 // make sure we check the class hierarchy.
6467 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6468 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6469 E = lhsQID->qual_end(); I != E; ++I) {
6470 // when comparing an id<P> on lhs with a static type on rhs,
6471 // see if static class implements all of id's protocols, directly or
6472 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00006473 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00006474 return false;
6475 }
6476 }
6477 // If there are no qualifiers and no interface, we have an 'id'.
6478 return true;
6479 }
Mike Stump1eb44332009-09-09 15:08:12 +00006480 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00006481 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6482 E = lhsQID->qual_end(); I != E; ++I) {
6483 ObjCProtocolDecl *lhsProto = *I;
6484 bool match = false;
6485
6486 // when comparing an id<P> on lhs with a static type on rhs,
6487 // see if static class implements all of id's protocols, directly or
6488 // through its super class and categories.
6489 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6490 E = rhsOPT->qual_end(); J != E; ++J) {
6491 ObjCProtocolDecl *rhsProto = *J;
6492 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6493 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6494 match = true;
6495 break;
6496 }
6497 }
Mike Stump1eb44332009-09-09 15:08:12 +00006498 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00006499 // make sure we check the class hierarchy.
6500 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6501 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6502 E = lhsQID->qual_end(); I != E; ++I) {
6503 // when comparing an id<P> on lhs with a static type on rhs,
6504 // see if static class implements all of id's protocols, directly or
6505 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00006506 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00006507 match = true;
6508 break;
6509 }
6510 }
6511 }
6512 if (!match)
6513 return false;
6514 }
Mike Stump1eb44332009-09-09 15:08:12 +00006515
Steve Naroff4084c302009-07-23 01:01:38 +00006516 return true;
6517 }
Mike Stump1eb44332009-09-09 15:08:12 +00006518
Steve Naroff4084c302009-07-23 01:01:38 +00006519 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6520 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6521
Mike Stump1eb44332009-09-09 15:08:12 +00006522 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00006523 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006524 // If both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00006525 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
6526 E = lhsOPT->qual_end(); I != E; ++I) {
6527 ObjCProtocolDecl *lhsProto = *I;
6528 bool match = false;
6529
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006530 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff4084c302009-07-23 01:01:38 +00006531 // see if static class implements all of id's protocols, directly or
6532 // through its super class and categories.
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006533 // First, lhs protocols in the qualifier list must be found, direct
6534 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff4084c302009-07-23 01:01:38 +00006535 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6536 E = rhsQID->qual_end(); J != E; ++J) {
6537 ObjCProtocolDecl *rhsProto = *J;
6538 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6539 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6540 match = true;
6541 break;
6542 }
6543 }
6544 if (!match)
6545 return false;
6546 }
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006547
6548 // Static class's protocols, or its super class or category protocols
6549 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6550 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6551 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6552 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6553 // This is rather dubious but matches gcc's behavior. If lhs has
6554 // no type qualifier and its class has no static protocol(s)
6555 // assume that it is mismatch.
6556 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6557 return false;
6558 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6559 LHSInheritedProtocols.begin(),
6560 E = LHSInheritedProtocols.end(); I != E; ++I) {
6561 bool match = false;
6562 ObjCProtocolDecl *lhsProto = (*I);
6563 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6564 E = rhsQID->qual_end(); J != E; ++J) {
6565 ObjCProtocolDecl *rhsProto = *J;
6566 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6567 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6568 match = true;
6569 break;
6570 }
6571 }
6572 if (!match)
6573 return false;
6574 }
6575 }
Steve Naroff4084c302009-07-23 01:01:38 +00006576 return true;
6577 }
6578 return false;
6579}
6580
Eli Friedman3d815e72008-08-22 00:56:42 +00006581/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00006582/// compatible for assignment from RHS to LHS. This handles validation of any
6583/// protocol qualifiers on the LHS or RHS.
6584///
Steve Naroff14108da2009-07-10 23:34:53 +00006585bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6586 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00006587 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6588 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6589
Steve Naroffde2e22d2009-07-15 18:40:39 +00006590 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00006591 if (LHS->isObjCUnqualifiedIdOrClass() ||
6592 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00006593 return true;
6594
John McCallc12c5bb2010-05-15 11:32:37 +00006595 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00006596 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6597 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00006598 false);
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00006599
6600 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6601 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6602 QualType(RHSOPT,0));
6603
John McCallc12c5bb2010-05-15 11:32:37 +00006604 // If we have 2 user-defined types, fall into that path.
6605 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00006606 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00006607
Steve Naroff4084c302009-07-23 01:01:38 +00006608 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00006609}
6610
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006611/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00006612/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006613/// arguments in block literals. When passed as arguments, passing 'A*' where
6614/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6615/// not OK. For the return type, the opposite is not OK.
6616bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6617 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006618 const ObjCObjectPointerType *RHSOPT,
6619 bool BlockReturnType) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00006620 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006621 return true;
6622
6623 if (LHSOPT->isObjCBuiltinType()) {
6624 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6625 }
6626
Fariborz Jahaniana9834482010-04-06 17:23:39 +00006627 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006628 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6629 QualType(RHSOPT,0),
6630 false);
6631
6632 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6633 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6634 if (LHS && RHS) { // We have 2 user-defined types.
6635 if (LHS != RHS) {
6636 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006637 return BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006638 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006639 return !BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006640 }
6641 else
6642 return true;
6643 }
6644 return false;
6645}
6646
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006647/// getIntersectionOfProtocols - This routine finds the intersection of set
6648/// of protocols inherited from two distinct objective-c pointer objects.
6649/// It is used to build composite qualifier list of the composite type of
6650/// the conditional expression involving two objective-c pointer objects.
6651static
6652void getIntersectionOfProtocols(ASTContext &Context,
6653 const ObjCObjectPointerType *LHSOPT,
6654 const ObjCObjectPointerType *RHSOPT,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006655 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006656
John McCallc12c5bb2010-05-15 11:32:37 +00006657 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6658 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6659 assert(LHS->getInterface() && "LHS must have an interface base");
6660 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006661
6662 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6663 unsigned LHSNumProtocols = LHS->getNumProtocols();
6664 if (LHSNumProtocols > 0)
6665 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6666 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006667 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006668 Context.CollectInheritedProtocols(LHS->getInterface(),
6669 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006670 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6671 LHSInheritedProtocols.end());
6672 }
6673
6674 unsigned RHSNumProtocols = RHS->getNumProtocols();
6675 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00006676 ObjCProtocolDecl **RHSProtocols =
6677 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006678 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6679 if (InheritedProtocolSet.count(RHSProtocols[i]))
6680 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier30601782011-08-17 23:08:45 +00006681 } else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006682 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006683 Context.CollectInheritedProtocols(RHS->getInterface(),
6684 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006685 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6686 RHSInheritedProtocols.begin(),
6687 E = RHSInheritedProtocols.end(); I != E; ++I)
6688 if (InheritedProtocolSet.count((*I)))
6689 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006690 }
6691}
6692
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006693/// areCommonBaseCompatible - Returns common base class of the two classes if
6694/// one found. Note that this is O'2 algorithm. But it will be called as the
6695/// last type comparison in a ?-exp of ObjC pointer types before a
6696/// warning is issued. So, its invokation is extremely rare.
6697QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00006698 const ObjCObjectPointerType *Lptr,
6699 const ObjCObjectPointerType *Rptr) {
6700 const ObjCObjectType *LHS = Lptr->getObjectType();
6701 const ObjCObjectType *RHS = Rptr->getObjectType();
6702 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6703 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor60ef3082011-12-15 00:29:59 +00006704 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006705 return QualType();
6706
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00006707 do {
John McCallc12c5bb2010-05-15 11:32:37 +00006708 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006709 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006710 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006711 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6712
6713 QualType Result = QualType(LHS, 0);
6714 if (!Protocols.empty())
6715 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6716 Result = getObjCObjectPointerType(Result);
6717 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006718 }
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00006719 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006720
6721 return QualType();
6722}
6723
John McCallc12c5bb2010-05-15 11:32:37 +00006724bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6725 const ObjCObjectType *RHS) {
6726 assert(LHS->getInterface() && "LHS is not an interface type");
6727 assert(RHS->getInterface() && "RHS is not an interface type");
6728
Chris Lattner6ac46a42008-04-07 06:51:04 +00006729 // Verify that the base decls are compatible: the RHS must be a subclass of
6730 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00006731 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00006732 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006733
Chris Lattner6ac46a42008-04-07 06:51:04 +00006734 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6735 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00006736 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00006737 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00006738
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006739 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6740 // more detailed analysis is required.
6741 if (RHS->getNumProtocols() == 0) {
6742 // OK, if LHS is a superclass of RHS *and*
6743 // this superclass is assignment compatible with LHS.
6744 // false otherwise.
Fariborz Jahanian627788c2011-04-12 16:34:14 +00006745 bool IsSuperClass =
6746 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6747 if (IsSuperClass) {
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006748 // OK if conversion of LHS to SuperClass results in narrowing of types
6749 // ; i.e., SuperClass may implement at least one of the protocols
6750 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6751 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6752 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian627788c2011-04-12 16:34:14 +00006753 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006754 // If super class has no protocols, it is not a match.
6755 if (SuperClassInheritedProtocols.empty())
6756 return false;
6757
6758 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6759 LHSPE = LHS->qual_end();
6760 LHSPI != LHSPE; LHSPI++) {
6761 bool SuperImplementsProtocol = false;
6762 ObjCProtocolDecl *LHSProto = (*LHSPI);
6763
6764 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6765 SuperClassInheritedProtocols.begin(),
6766 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6767 ObjCProtocolDecl *SuperClassProto = (*I);
6768 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6769 SuperImplementsProtocol = true;
6770 break;
6771 }
6772 }
6773 if (!SuperImplementsProtocol)
6774 return false;
6775 }
6776 return true;
6777 }
6778 return false;
6779 }
Mike Stump1eb44332009-09-09 15:08:12 +00006780
John McCallc12c5bb2010-05-15 11:32:37 +00006781 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6782 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006783 LHSPI != LHSPE; LHSPI++) {
6784 bool RHSImplementsProtocol = false;
6785
6786 // If the RHS doesn't implement the protocol on the left, the types
6787 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00006788 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6789 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00006790 RHSPI != RHSPE; RHSPI++) {
6791 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006792 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00006793 break;
6794 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006795 }
6796 // FIXME: For better diagnostics, consider passing back the protocol name.
6797 if (!RHSImplementsProtocol)
6798 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00006799 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006800 // The RHS implements all protocols listed on the LHS.
6801 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00006802}
6803
Steve Naroff389bf462009-02-12 17:52:19 +00006804bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6805 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00006806 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6807 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00006808
Steve Naroff14108da2009-07-10 23:34:53 +00006809 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00006810 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00006811
6812 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6813 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00006814}
6815
Douglas Gregor569c3162010-08-07 11:51:51 +00006816bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6817 return canAssignObjCInterfaces(
6818 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6819 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6820}
6821
Mike Stump1eb44332009-09-09 15:08:12 +00006822/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00006823/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00006824/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00006825/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor447234d2010-07-29 15:18:02 +00006826bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6827 bool CompareUnqualified) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006828 if (getLangOpts().CPlusPlus)
Douglas Gregor0e709ab2010-02-03 21:02:30 +00006829 return hasSameType(LHS, RHS);
6830
Douglas Gregor447234d2010-07-29 15:18:02 +00006831 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman3d815e72008-08-22 00:56:42 +00006832}
6833
Fariborz Jahanianc286f382011-07-12 22:05:16 +00006834bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanian82378392011-07-12 23:20:13 +00006835 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc286f382011-07-12 22:05:16 +00006836}
6837
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006838bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6839 return !mergeTypes(LHS, RHS, true).isNull();
6840}
6841
Peter Collingbourne48466752010-10-24 18:30:18 +00006842/// mergeTransparentUnionType - if T is a transparent union type and a member
6843/// of T is compatible with SubType, return the merged type, else return
6844/// QualType()
6845QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6846 bool OfBlockPointer,
6847 bool Unqualified) {
6848 if (const RecordType *UT = T->getAsUnionType()) {
6849 RecordDecl *UD = UT->getDecl();
6850 if (UD->hasAttr<TransparentUnionAttr>()) {
6851 for (RecordDecl::field_iterator it = UD->field_begin(),
6852 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbournef91d7572010-12-02 21:00:06 +00006853 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00006854 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6855 if (!MT.isNull())
6856 return MT;
6857 }
6858 }
6859 }
6860
6861 return QualType();
6862}
6863
6864/// mergeFunctionArgumentTypes - merge two types which appear as function
6865/// argument types
6866QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
6867 bool OfBlockPointer,
6868 bool Unqualified) {
6869 // GNU extension: two types are compatible if they appear as a function
6870 // argument, one of the types is a transparent union type and the other
6871 // type is compatible with a union member
6872 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6873 Unqualified);
6874 if (!lmerge.isNull())
6875 return lmerge;
6876
6877 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6878 Unqualified);
6879 if (!rmerge.isNull())
6880 return rmerge;
6881
6882 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6883}
6884
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006885QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor447234d2010-07-29 15:18:02 +00006886 bool OfBlockPointer,
6887 bool Unqualified) {
John McCall183700f2009-09-21 23:43:11 +00006888 const FunctionType *lbase = lhs->getAs<FunctionType>();
6889 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00006890 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6891 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00006892 bool allLTypes = true;
6893 bool allRTypes = true;
6894
6895 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006896 QualType retType;
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00006897 if (OfBlockPointer) {
6898 QualType RHS = rbase->getResultType();
6899 QualType LHS = lbase->getResultType();
6900 bool UnqualifiedResult = Unqualified;
6901 if (!UnqualifiedResult)
6902 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006903 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00006904 }
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006905 else
John McCall8cc246c2010-12-15 01:06:38 +00006906 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6907 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006908 if (retType.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006909
6910 if (Unqualified)
6911 retType = retType.getUnqualifiedType();
6912
6913 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6914 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6915 if (Unqualified) {
6916 LRetType = LRetType.getUnqualifiedType();
6917 RRetType = RRetType.getUnqualifiedType();
6918 }
6919
6920 if (getCanonicalType(retType) != LRetType)
Chris Lattner61710852008-10-05 17:34:18 +00006921 allLTypes = false;
Douglas Gregor447234d2010-07-29 15:18:02 +00006922 if (getCanonicalType(retType) != RRetType)
Chris Lattner61710852008-10-05 17:34:18 +00006923 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00006924
Daniel Dunbar6a15c852010-04-28 16:20:58 +00006925 // FIXME: double check this
6926 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6927 // rbase->getRegParmAttr() != 0 &&
6928 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00006929 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6930 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8cc246c2010-12-15 01:06:38 +00006931
Douglas Gregorab8bbf42010-01-18 17:14:39 +00006932 // Compatible functions must have compatible calling conventions
Reid Kleckneref072032013-08-27 23:08:25 +00006933 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Douglas Gregorab8bbf42010-01-18 17:14:39 +00006934 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00006935
John McCall8cc246c2010-12-15 01:06:38 +00006936 // Regparm is part of the calling convention.
Eli Friedmana49218e2011-04-09 08:18:08 +00006937 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6938 return QualType();
John McCall8cc246c2010-12-15 01:06:38 +00006939 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6940 return QualType();
6941
John McCallf85e1932011-06-15 23:02:42 +00006942 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6943 return QualType();
6944
John McCall8cc246c2010-12-15 01:06:38 +00006945 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6946 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8cc246c2010-12-15 01:06:38 +00006947
Rafael Espindola8b8a09e2012-11-29 16:09:03 +00006948 if (lbaseInfo.getNoReturn() != NoReturn)
6949 allLTypes = false;
6950 if (rbaseInfo.getNoReturn() != NoReturn)
6951 allRTypes = false;
6952
John McCallf85e1932011-06-15 23:02:42 +00006953 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00006954
Eli Friedman3d815e72008-08-22 00:56:42 +00006955 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00006956 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6957 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00006958 unsigned lproto_nargs = lproto->getNumArgs();
6959 unsigned rproto_nargs = rproto->getNumArgs();
6960
6961 // Compatible functions must have the same number of arguments
6962 if (lproto_nargs != rproto_nargs)
6963 return QualType();
6964
6965 // Variadic and non-variadic functions aren't compatible
6966 if (lproto->isVariadic() != rproto->isVariadic())
6967 return QualType();
6968
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00006969 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6970 return QualType();
6971
Fariborz Jahanian78213e42011-09-28 21:52:05 +00006972 if (LangOpts.ObjCAutoRefCount &&
6973 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6974 return QualType();
6975
Eli Friedman3d815e72008-08-22 00:56:42 +00006976 // Check argument compatibility
Chris Lattner5f9e2722011-07-23 10:55:15 +00006977 SmallVector<QualType, 10> types;
Eli Friedman3d815e72008-08-22 00:56:42 +00006978 for (unsigned i = 0; i < lproto_nargs; i++) {
6979 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
6980 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00006981 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
6982 OfBlockPointer,
6983 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006984 if (argtype.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006985
6986 if (Unqualified)
6987 argtype = argtype.getUnqualifiedType();
6988
Eli Friedman3d815e72008-08-22 00:56:42 +00006989 types.push_back(argtype);
Douglas Gregor447234d2010-07-29 15:18:02 +00006990 if (Unqualified) {
6991 largtype = largtype.getUnqualifiedType();
6992 rargtype = rargtype.getUnqualifiedType();
6993 }
6994
Chris Lattner61710852008-10-05 17:34:18 +00006995 if (getCanonicalType(argtype) != getCanonicalType(largtype))
6996 allLTypes = false;
6997 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
6998 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00006999 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00007000
Eli Friedman3d815e72008-08-22 00:56:42 +00007001 if (allLTypes) return lhs;
7002 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00007003
7004 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7005 EPI.ExtInfo = einfo;
Jordan Rosebea522f2013-03-08 21:51:21 +00007006 return getFunctionType(retType, types, EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00007007 }
7008
7009 if (lproto) allRTypes = false;
7010 if (rproto) allLTypes = false;
7011
Douglas Gregor72564e72009-02-26 23:50:07 +00007012 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00007013 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00007014 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00007015 if (proto->isVariadic()) return QualType();
7016 // Check that the types are compatible with the types that
7017 // would result from default argument promotions (C99 6.7.5.3p15).
7018 // The only types actually affected are promotable integer
7019 // types and floats, which would be passed as a different
7020 // type depending on whether the prototype is visible.
7021 unsigned proto_nargs = proto->getNumArgs();
7022 for (unsigned i = 0; i < proto_nargs; ++i) {
7023 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00007024
Eli Friedmanc586d5d2012-08-30 00:44:15 +00007025 // Look at the converted type of enum types, since that is the type used
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00007026 // to pass enum values.
Eli Friedmanc586d5d2012-08-30 00:44:15 +00007027 if (const EnumType *Enum = argTy->getAs<EnumType>()) {
7028 argTy = Enum->getDecl()->getIntegerType();
7029 if (argTy.isNull())
7030 return QualType();
7031 }
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00007032
Eli Friedman3d815e72008-08-22 00:56:42 +00007033 if (argTy->isPromotableIntegerType() ||
7034 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
7035 return QualType();
7036 }
7037
7038 if (allLTypes) return lhs;
7039 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00007040
7041 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7042 EPI.ExtInfo = einfo;
Reid Kleckner0567a792013-06-10 20:51:09 +00007043 return getFunctionType(retType, proto->getArgTypes(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00007044 }
7045
7046 if (allLTypes) return lhs;
7047 if (allRTypes) return rhs;
John McCall8cc246c2010-12-15 01:06:38 +00007048 return getFunctionNoProtoType(retType, einfo);
Eli Friedman3d815e72008-08-22 00:56:42 +00007049}
7050
John McCallb9da7132013-03-21 00:10:07 +00007051/// Given that we have an enum type and a non-enum type, try to merge them.
7052static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7053 QualType other, bool isBlockReturnType) {
7054 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7055 // a signed integer type, or an unsigned integer type.
7056 // Compatibility is based on the underlying type, not the promotion
7057 // type.
7058 QualType underlyingType = ET->getDecl()->getIntegerType();
7059 if (underlyingType.isNull()) return QualType();
7060 if (Context.hasSameType(underlyingType, other))
7061 return other;
7062
7063 // In block return types, we're more permissive and accept any
7064 // integral type of the same size.
7065 if (isBlockReturnType && other->isIntegerType() &&
7066 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7067 return other;
7068
7069 return QualType();
7070}
7071
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00007072QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor447234d2010-07-29 15:18:02 +00007073 bool OfBlockPointer,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00007074 bool Unqualified, bool BlockReturnType) {
Bill Wendling43d69752007-12-03 07:33:35 +00007075 // C++ [expr]: If an expression initially has the type "reference to T", the
7076 // type is adjusted to "T" prior to any further analysis, the expression
7077 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00007078 // expression is an lvalue unless the reference is an rvalue reference and
7079 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00007080 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7081 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor447234d2010-07-29 15:18:02 +00007082
7083 if (Unqualified) {
7084 LHS = LHS.getUnqualifiedType();
7085 RHS = RHS.getUnqualifiedType();
7086 }
Douglas Gregor0e709ab2010-02-03 21:02:30 +00007087
Eli Friedman3d815e72008-08-22 00:56:42 +00007088 QualType LHSCan = getCanonicalType(LHS),
7089 RHSCan = getCanonicalType(RHS);
7090
7091 // If two types are identical, they are compatible.
7092 if (LHSCan == RHSCan)
7093 return LHS;
7094
John McCall0953e762009-09-24 19:53:00 +00007095 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00007096 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7097 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00007098 if (LQuals != RQuals) {
7099 // If any of these qualifiers are different, we have a type
7100 // mismatch.
7101 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCallf85e1932011-06-15 23:02:42 +00007102 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7103 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall0953e762009-09-24 19:53:00 +00007104 return QualType();
7105
7106 // Exactly one GC qualifier difference is allowed: __strong is
7107 // okay if the other type has no GC qualifier but is an Objective
7108 // C object pointer (i.e. implicitly strong by default). We fix
7109 // this by pretending that the unqualified type was actually
7110 // qualified __strong.
7111 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7112 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7113 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7114
7115 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7116 return QualType();
7117
7118 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7119 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7120 }
7121 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7122 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7123 }
Eli Friedman3d815e72008-08-22 00:56:42 +00007124 return QualType();
John McCall0953e762009-09-24 19:53:00 +00007125 }
7126
7127 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00007128
Eli Friedman852d63b2009-06-01 01:22:52 +00007129 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7130 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00007131
Chris Lattner1adb8832008-01-14 05:45:46 +00007132 // We want to consider the two function types to be the same for these
7133 // comparisons, just force one to the other.
7134 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7135 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00007136
7137 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00007138 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7139 LHSClass = Type::ConstantArray;
7140 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7141 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00007142
John McCallc12c5bb2010-05-15 11:32:37 +00007143 // ObjCInterfaces are just specialized ObjCObjects.
7144 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7145 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7146
Nate Begeman213541a2008-04-18 23:10:10 +00007147 // Canonicalize ExtVector -> Vector.
7148 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7149 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00007150
Chris Lattnera36a61f2008-04-07 05:43:21 +00007151 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00007152 if (LHSClass != RHSClass) {
John McCallb9da7132013-03-21 00:10:07 +00007153 // Note that we only have special rules for turning block enum
7154 // returns into block int returns, not vice-versa.
John McCall183700f2009-09-21 23:43:11 +00007155 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCallb9da7132013-03-21 00:10:07 +00007156 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmanbab96962008-02-12 08:46:17 +00007157 }
John McCall183700f2009-09-21 23:43:11 +00007158 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCallb9da7132013-03-21 00:10:07 +00007159 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmanbab96962008-02-12 08:46:17 +00007160 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00007161 // allow block pointer type to match an 'id' type.
Fariborz Jahanian41963632012-01-26 17:08:50 +00007162 if (OfBlockPointer && !BlockReturnType) {
7163 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7164 return LHS;
7165 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7166 return RHS;
7167 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00007168
Eli Friedman3d815e72008-08-22 00:56:42 +00007169 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00007170 }
Eli Friedman3d815e72008-08-22 00:56:42 +00007171
Steve Naroff4a746782008-01-09 22:43:08 +00007172 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00007173 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00007174#define TYPE(Class, Base)
7175#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00007176#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00007177#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7178#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7179#include "clang/AST/TypeNodes.def"
David Blaikieb219cfc2011-09-23 05:06:16 +00007180 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregor72564e72009-02-26 23:50:07 +00007181
Richard Smithdc7a4f52013-04-30 13:56:41 +00007182 case Type::Auto:
Sebastian Redl7c80bd62009-03-16 23:22:08 +00007183 case Type::LValueReference:
7184 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00007185 case Type::MemberPointer:
David Blaikieb219cfc2011-09-23 05:06:16 +00007186 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregor72564e72009-02-26 23:50:07 +00007187
John McCallc12c5bb2010-05-15 11:32:37 +00007188 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00007189 case Type::IncompleteArray:
7190 case Type::VariableArray:
7191 case Type::FunctionProto:
7192 case Type::ExtVector:
David Blaikieb219cfc2011-09-23 05:06:16 +00007193 llvm_unreachable("Types are eliminated above");
Douglas Gregor72564e72009-02-26 23:50:07 +00007194
Chris Lattner1adb8832008-01-14 05:45:46 +00007195 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00007196 {
7197 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00007198 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7199 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00007200 if (Unqualified) {
7201 LHSPointee = LHSPointee.getUnqualifiedType();
7202 RHSPointee = RHSPointee.getUnqualifiedType();
7203 }
7204 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7205 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00007206 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00007207 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00007208 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00007209 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00007210 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00007211 return getPointerType(ResultType);
7212 }
Steve Naroffc0febd52008-12-10 17:49:55 +00007213 case Type::BlockPointer:
7214 {
7215 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00007216 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7217 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00007218 if (Unqualified) {
7219 LHSPointee = LHSPointee.getUnqualifiedType();
7220 RHSPointee = RHSPointee.getUnqualifiedType();
7221 }
7222 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7223 Unqualified);
Steve Naroffc0febd52008-12-10 17:49:55 +00007224 if (ResultType.isNull()) return QualType();
7225 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7226 return LHS;
7227 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7228 return RHS;
7229 return getBlockPointerType(ResultType);
7230 }
Eli Friedmanb001de72011-10-06 23:00:33 +00007231 case Type::Atomic:
7232 {
7233 // Merge two pointer types, while trying to preserve typedef info
7234 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7235 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7236 if (Unqualified) {
7237 LHSValue = LHSValue.getUnqualifiedType();
7238 RHSValue = RHSValue.getUnqualifiedType();
7239 }
7240 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7241 Unqualified);
7242 if (ResultType.isNull()) return QualType();
7243 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7244 return LHS;
7245 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7246 return RHS;
7247 return getAtomicType(ResultType);
7248 }
Chris Lattner1adb8832008-01-14 05:45:46 +00007249 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00007250 {
7251 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7252 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7253 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7254 return QualType();
7255
7256 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7257 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor447234d2010-07-29 15:18:02 +00007258 if (Unqualified) {
7259 LHSElem = LHSElem.getUnqualifiedType();
7260 RHSElem = RHSElem.getUnqualifiedType();
7261 }
7262
7263 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00007264 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00007265 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7266 return LHS;
7267 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7268 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00007269 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7270 ArrayType::ArraySizeModifier(), 0);
7271 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7272 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00007273 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7274 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00007275 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7276 return LHS;
7277 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7278 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00007279 if (LVAT) {
7280 // FIXME: This isn't correct! But tricky to implement because
7281 // the array's size has to be the size of LHS, but the type
7282 // has to be different.
7283 return LHS;
7284 }
7285 if (RVAT) {
7286 // FIXME: This isn't correct! But tricky to implement because
7287 // the array's size has to be the size of RHS, but the type
7288 // has to be different.
7289 return RHS;
7290 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00007291 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7292 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00007293 return getIncompleteArrayType(ResultType,
7294 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00007295 }
Chris Lattner1adb8832008-01-14 05:45:46 +00007296 case Type::FunctionNoProto:
Douglas Gregor447234d2010-07-29 15:18:02 +00007297 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregor72564e72009-02-26 23:50:07 +00007298 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00007299 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00007300 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00007301 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00007302 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00007303 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00007304 case Type::Complex:
7305 // Distinct complex types are incompatible.
7306 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00007307 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00007308 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00007309 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7310 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00007311 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00007312 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00007313 case Type::ObjCObject: {
7314 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00007315 // FIXME: This should be type compatibility, e.g. whether
7316 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00007317 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7318 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7319 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00007320 return LHS;
7321
Eli Friedman3d815e72008-08-22 00:56:42 +00007322 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00007323 }
Steve Naroff14108da2009-07-10 23:34:53 +00007324 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00007325 if (OfBlockPointer) {
7326 if (canAssignObjCInterfacesInBlockPointer(
7327 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00007328 RHS->getAs<ObjCObjectPointerType>(),
7329 BlockReturnType))
David Blaikie7530c032012-01-17 06:56:22 +00007330 return LHS;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00007331 return QualType();
7332 }
John McCall183700f2009-09-21 23:43:11 +00007333 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7334 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00007335 return LHS;
7336
Steve Naroffbc76dd02008-12-10 22:14:21 +00007337 return QualType();
David Blaikie7530c032012-01-17 06:56:22 +00007338 }
Steve Naroffec0550f2007-10-15 20:41:53 +00007339 }
Douglas Gregor72564e72009-02-26 23:50:07 +00007340
David Blaikie7530c032012-01-17 06:56:22 +00007341 llvm_unreachable("Invalid Type::Class!");
Steve Naroffec0550f2007-10-15 20:41:53 +00007342}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00007343
Fariborz Jahanian78213e42011-09-28 21:52:05 +00007344bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7345 const FunctionProtoType *FromFunctionType,
7346 const FunctionProtoType *ToFunctionType) {
7347 if (FromFunctionType->hasAnyConsumedArgs() !=
7348 ToFunctionType->hasAnyConsumedArgs())
7349 return false;
7350 FunctionProtoType::ExtProtoInfo FromEPI =
7351 FromFunctionType->getExtProtoInfo();
7352 FunctionProtoType::ExtProtoInfo ToEPI =
7353 ToFunctionType->getExtProtoInfo();
7354 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
7355 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
7356 ArgIdx != NumArgs; ++ArgIdx) {
7357 if (FromEPI.ConsumedArguments[ArgIdx] !=
7358 ToEPI.ConsumedArguments[ArgIdx])
7359 return false;
7360 }
7361 return true;
7362}
7363
Fariborz Jahanian2390a722010-05-19 21:37:30 +00007364/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7365/// 'RHS' attributes and returns the merged version; including for function
7366/// return types.
7367QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7368 QualType LHSCan = getCanonicalType(LHS),
7369 RHSCan = getCanonicalType(RHS);
7370 // If two types are identical, they are compatible.
7371 if (LHSCan == RHSCan)
7372 return LHS;
7373 if (RHSCan->isFunctionType()) {
7374 if (!LHSCan->isFunctionType())
7375 return QualType();
7376 QualType OldReturnType =
7377 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
7378 QualType NewReturnType =
7379 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
7380 QualType ResReturnType =
7381 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7382 if (ResReturnType.isNull())
7383 return QualType();
7384 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7385 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7386 // In either case, use OldReturnType to build the new function type.
7387 const FunctionType *F = LHS->getAs<FunctionType>();
7388 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalle23cf432010-12-14 08:05:40 +00007389 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7390 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner0567a792013-06-10 20:51:09 +00007391 QualType ResultType =
7392 getFunctionType(OldReturnType, FPT->getArgTypes(), EPI);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00007393 return ResultType;
7394 }
7395 }
7396 return QualType();
7397 }
7398
7399 // If the qualifiers are different, the types can still be merged.
7400 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7401 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7402 if (LQuals != RQuals) {
7403 // If any of these qualifiers are different, we have a type mismatch.
7404 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7405 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7406 return QualType();
7407
7408 // Exactly one GC qualifier difference is allowed: __strong is
7409 // okay if the other type has no GC qualifier but is an Objective
7410 // C object pointer (i.e. implicitly strong by default). We fix
7411 // this by pretending that the unqualified type was actually
7412 // qualified __strong.
7413 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7414 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7415 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7416
7417 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7418 return QualType();
7419
7420 if (GC_L == Qualifiers::Strong)
7421 return LHS;
7422 if (GC_R == Qualifiers::Strong)
7423 return RHS;
7424 return QualType();
7425 }
7426
7427 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7428 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7429 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7430 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7431 if (ResQT == LHSBaseQT)
7432 return LHS;
7433 if (ResQT == RHSBaseQT)
7434 return RHS;
7435 }
7436 return QualType();
7437}
7438
Chris Lattner5426bf62008-04-07 07:01:58 +00007439//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00007440// Integer Predicates
7441//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00007442
Jay Foad4ba2a172011-01-12 09:06:06 +00007443unsigned ASTContext::getIntWidth(QualType T) const {
John McCallf4c73712011-01-19 06:33:43 +00007444 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00007445 T = ET->getDecl()->getIntegerType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00007446 if (T->isBooleanType())
7447 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00007448 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00007449 return (unsigned)getTypeSize(T);
7450}
7451
Abramo Bagnara762f1592012-09-09 10:21:24 +00007452QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregorf6094622010-07-23 15:58:24 +00007453 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00007454
7455 // Turn <4 x signed int> -> <4 x unsigned int>
7456 if (const VectorType *VTy = T->getAs<VectorType>())
7457 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsone86d78c2010-11-10 21:56:12 +00007458 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattner6a2b9262009-10-17 20:33:28 +00007459
7460 // For enums, we return the unsigned version of the base type.
7461 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00007462 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00007463
7464 const BuiltinType *BTy = T->getAs<BuiltinType>();
7465 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00007466 switch (BTy->getKind()) {
7467 case BuiltinType::Char_S:
7468 case BuiltinType::SChar:
7469 return UnsignedCharTy;
7470 case BuiltinType::Short:
7471 return UnsignedShortTy;
7472 case BuiltinType::Int:
7473 return UnsignedIntTy;
7474 case BuiltinType::Long:
7475 return UnsignedLongTy;
7476 case BuiltinType::LongLong:
7477 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00007478 case BuiltinType::Int128:
7479 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00007480 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00007481 llvm_unreachable("Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00007482 }
7483}
7484
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00007485ASTMutationListener::~ASTMutationListener() { }
7486
Richard Smith9dadfab2013-05-11 05:45:24 +00007487void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7488 QualType ReturnType) {}
Chris Lattner86df27b2009-06-14 00:45:47 +00007489
7490//===----------------------------------------------------------------------===//
7491// Builtin Type Computation
7492//===----------------------------------------------------------------------===//
7493
7494/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattner33daae62010-10-01 22:42:38 +00007495/// pointer over the consumed characters. This returns the resultant type. If
7496/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7497/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7498/// a vector of "i*".
Chris Lattner14e0e742010-10-01 22:53:11 +00007499///
7500/// RequiresICE is filled in on return to indicate whether the value is required
7501/// to be an Integer Constant Expression.
Jay Foad4ba2a172011-01-12 09:06:06 +00007502static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00007503 ASTContext::GetBuiltinTypeError &Error,
Chris Lattner14e0e742010-10-01 22:53:11 +00007504 bool &RequiresICE,
Chris Lattner33daae62010-10-01 22:42:38 +00007505 bool AllowTypeModifiers) {
Chris Lattner86df27b2009-06-14 00:45:47 +00007506 // Modifiers.
7507 int HowLong = 0;
7508 bool Signed = false, Unsigned = false;
Chris Lattner14e0e742010-10-01 22:53:11 +00007509 RequiresICE = false;
Chris Lattner393bd8e2010-10-01 07:13:18 +00007510
Chris Lattner33daae62010-10-01 22:42:38 +00007511 // Read the prefixed modifiers first.
Chris Lattner86df27b2009-06-14 00:45:47 +00007512 bool Done = false;
7513 while (!Done) {
7514 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00007515 default: Done = true; --Str; break;
Chris Lattner393bd8e2010-10-01 07:13:18 +00007516 case 'I':
Chris Lattner14e0e742010-10-01 22:53:11 +00007517 RequiresICE = true;
Chris Lattner393bd8e2010-10-01 07:13:18 +00007518 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007519 case 'S':
7520 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7521 assert(!Signed && "Can't use 'S' modifier multiple times!");
7522 Signed = true;
7523 break;
7524 case 'U':
7525 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7526 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7527 Unsigned = true;
7528 break;
7529 case 'L':
7530 assert(HowLong <= 2 && "Can't have LLLL modifier");
7531 ++HowLong;
7532 break;
7533 }
7534 }
7535
7536 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00007537
Chris Lattner86df27b2009-06-14 00:45:47 +00007538 // Read the base type.
7539 switch (*Str++) {
David Blaikieb219cfc2011-09-23 05:06:16 +00007540 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattner86df27b2009-06-14 00:45:47 +00007541 case 'v':
7542 assert(HowLong == 0 && !Signed && !Unsigned &&
7543 "Bad modifiers used with 'v'!");
7544 Type = Context.VoidTy;
7545 break;
Jack Carter146522e2013-08-15 15:16:57 +00007546 case 'h':
7547 assert(HowLong == 0 && !Signed && !Unsigned &&
7548 "Bad modifiers used with 'f'!");
7549 Type = Context.HalfTy;
7550 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007551 case 'f':
7552 assert(HowLong == 0 && !Signed && !Unsigned &&
7553 "Bad modifiers used with 'f'!");
7554 Type = Context.FloatTy;
7555 break;
7556 case 'd':
7557 assert(HowLong < 2 && !Signed && !Unsigned &&
7558 "Bad modifiers used with 'd'!");
7559 if (HowLong)
7560 Type = Context.LongDoubleTy;
7561 else
7562 Type = Context.DoubleTy;
7563 break;
7564 case 's':
7565 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7566 if (Unsigned)
7567 Type = Context.UnsignedShortTy;
7568 else
7569 Type = Context.ShortTy;
7570 break;
7571 case 'i':
7572 if (HowLong == 3)
7573 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7574 else if (HowLong == 2)
7575 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7576 else if (HowLong == 1)
7577 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7578 else
7579 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7580 break;
7581 case 'c':
7582 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7583 if (Signed)
7584 Type = Context.SignedCharTy;
7585 else if (Unsigned)
7586 Type = Context.UnsignedCharTy;
7587 else
7588 Type = Context.CharTy;
7589 break;
7590 case 'b': // boolean
7591 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7592 Type = Context.BoolTy;
7593 break;
7594 case 'z': // size_t.
7595 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7596 Type = Context.getSizeType();
7597 break;
7598 case 'F':
7599 Type = Context.getCFConstantStringType();
7600 break;
Fariborz Jahanianba8bda02010-11-09 21:38:20 +00007601 case 'G':
7602 Type = Context.getObjCIdType();
7603 break;
7604 case 'H':
7605 Type = Context.getObjCSelType();
7606 break;
Fariborz Jahanianf7992132013-01-04 18:45:40 +00007607 case 'M':
7608 Type = Context.getObjCSuperType();
7609 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007610 case 'a':
7611 Type = Context.getBuiltinVaListType();
7612 assert(!Type.isNull() && "builtin va list type not initialized!");
7613 break;
7614 case 'A':
7615 // This is a "reference" to a va_list; however, what exactly
7616 // this means depends on how va_list is defined. There are two
7617 // different kinds of va_list: ones passed by value, and ones
7618 // passed by reference. An example of a by-value va_list is
7619 // x86, where va_list is a char*. An example of by-ref va_list
7620 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7621 // we want this argument to be a char*&; for x86-64, we want
7622 // it to be a __va_list_tag*.
7623 Type = Context.getBuiltinVaListType();
7624 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattner14e0e742010-10-01 22:53:11 +00007625 if (Type->isArrayType())
Chris Lattner86df27b2009-06-14 00:45:47 +00007626 Type = Context.getArrayDecayedType(Type);
Chris Lattner14e0e742010-10-01 22:53:11 +00007627 else
Chris Lattner86df27b2009-06-14 00:45:47 +00007628 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00007629 break;
7630 case 'V': {
7631 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00007632 unsigned NumElements = strtoul(Str, &End, 10);
7633 assert(End != Str && "Missing vector size");
Chris Lattner86df27b2009-06-14 00:45:47 +00007634 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00007635
Chris Lattner14e0e742010-10-01 22:53:11 +00007636 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7637 RequiresICE, false);
7638 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattner33daae62010-10-01 22:42:38 +00007639
7640 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner788b0fd2010-06-23 06:00:24 +00007641 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00007642 VectorType::GenericVector);
Chris Lattner86df27b2009-06-14 00:45:47 +00007643 break;
7644 }
Douglas Gregorb4bc99b2012-06-07 18:08:25 +00007645 case 'E': {
7646 char *End;
7647
7648 unsigned NumElements = strtoul(Str, &End, 10);
7649 assert(End != Str && "Missing vector size");
7650
7651 Str = End;
7652
7653 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7654 false);
7655 Type = Context.getExtVectorType(ElementType, NumElements);
7656 break;
7657 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00007658 case 'X': {
Chris Lattner14e0e742010-10-01 22:53:11 +00007659 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7660 false);
7661 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregord3a23b22009-09-28 21:45:01 +00007662 Type = Context.getComplexType(ElementType);
7663 break;
Fariborz Jahaniancc075e42011-08-23 23:33:09 +00007664 }
7665 case 'Y' : {
7666 Type = Context.getPointerDiffType();
7667 break;
7668 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00007669 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00007670 Type = Context.getFILEType();
7671 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00007672 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00007673 return QualType();
7674 }
Mike Stumpfd612db2009-07-28 23:47:15 +00007675 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00007676 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00007677 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00007678 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00007679 else
7680 Type = Context.getjmp_bufType();
7681
Mike Stumpfd612db2009-07-28 23:47:15 +00007682 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00007683 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00007684 return QualType();
7685 }
7686 break;
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +00007687 case 'K':
7688 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7689 Type = Context.getucontext_tType();
7690
7691 if (Type.isNull()) {
7692 Error = ASTContext::GE_Missing_ucontext;
7693 return QualType();
7694 }
7695 break;
Eli Friedman6902e412012-11-27 02:58:24 +00007696 case 'p':
7697 Type = Context.getProcessIDType();
7698 break;
Mike Stump782fa302009-07-28 02:25:19 +00007699 }
Mike Stump1eb44332009-09-09 15:08:12 +00007700
Chris Lattner33daae62010-10-01 22:42:38 +00007701 // If there are modifiers and if we're allowed to parse them, go for it.
7702 Done = !AllowTypeModifiers;
Chris Lattner86df27b2009-06-14 00:45:47 +00007703 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00007704 switch (char c = *Str++) {
Chris Lattner33daae62010-10-01 22:42:38 +00007705 default: Done = true; --Str; break;
7706 case '*':
7707 case '&': {
7708 // Both pointers and references can have their pointee types
7709 // qualified with an address space.
7710 char *End;
7711 unsigned AddrSpace = strtoul(Str, &End, 10);
7712 if (End != Str && AddrSpace != 0) {
7713 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7714 Str = End;
7715 }
7716 if (c == '*')
7717 Type = Context.getPointerType(Type);
7718 else
7719 Type = Context.getLValueReferenceType(Type);
7720 break;
7721 }
7722 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7723 case 'C':
7724 Type = Type.withConst();
7725 break;
7726 case 'D':
7727 Type = Context.getVolatileType(Type);
7728 break;
Ted Kremenek18932a02012-01-20 21:40:12 +00007729 case 'R':
7730 Type = Type.withRestrict();
7731 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007732 }
7733 }
Chris Lattner393bd8e2010-10-01 07:13:18 +00007734
Chris Lattner14e0e742010-10-01 22:53:11 +00007735 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner393bd8e2010-10-01 07:13:18 +00007736 "Integer constant 'I' type must be an integer");
Mike Stump1eb44332009-09-09 15:08:12 +00007737
Chris Lattner86df27b2009-06-14 00:45:47 +00007738 return Type;
7739}
7740
7741/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattner33daae62010-10-01 22:42:38 +00007742QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattner14e0e742010-10-01 22:53:11 +00007743 GetBuiltinTypeError &Error,
Jay Foad4ba2a172011-01-12 09:06:06 +00007744 unsigned *IntegerConstantArgs) const {
Chris Lattner33daae62010-10-01 22:42:38 +00007745 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump1eb44332009-09-09 15:08:12 +00007746
Chris Lattner5f9e2722011-07-23 10:55:15 +00007747 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00007748
Chris Lattner14e0e742010-10-01 22:53:11 +00007749 bool RequiresICE = false;
Chris Lattner86df27b2009-06-14 00:45:47 +00007750 Error = GE_None;
Chris Lattner14e0e742010-10-01 22:53:11 +00007751 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7752 RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00007753 if (Error != GE_None)
7754 return QualType();
Chris Lattner14e0e742010-10-01 22:53:11 +00007755
7756 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7757
Chris Lattner86df27b2009-06-14 00:45:47 +00007758 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattner14e0e742010-10-01 22:53:11 +00007759 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00007760 if (Error != GE_None)
7761 return QualType();
7762
Chris Lattner14e0e742010-10-01 22:53:11 +00007763 // If this argument is required to be an IntegerConstantExpression and the
7764 // caller cares, fill in the bitmask we return.
7765 if (RequiresICE && IntegerConstantArgs)
7766 *IntegerConstantArgs |= 1 << ArgTypes.size();
7767
Chris Lattner86df27b2009-06-14 00:45:47 +00007768 // Do array -> pointer decay. The builtin should use the decayed type.
7769 if (Ty->isArrayType())
7770 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00007771
Chris Lattner86df27b2009-06-14 00:45:47 +00007772 ArgTypes.push_back(Ty);
7773 }
7774
7775 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7776 "'.' should only occur at end of builtin type list!");
7777
Reid Kleckneref072032013-08-27 23:08:25 +00007778 FunctionType::ExtInfo EI(CC_C);
John McCall00ccbef2010-12-21 00:44:39 +00007779 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7780
7781 bool Variadic = (TypeStr[0] == '.');
7782
7783 // We really shouldn't be making a no-proto type here, especially in C++.
7784 if (ArgTypes.empty() && Variadic)
7785 return getFunctionNoProtoType(ResType, EI);
Douglas Gregorce056bc2010-02-21 22:15:06 +00007786
John McCalle23cf432010-12-14 08:05:40 +00007787 FunctionProtoType::ExtProtoInfo EPI;
John McCall00ccbef2010-12-21 00:44:39 +00007788 EPI.ExtInfo = EI;
7789 EPI.Variadic = Variadic;
John McCalle23cf432010-12-14 08:05:40 +00007790
Jordan Rosebea522f2013-03-08 21:51:21 +00007791 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattner86df27b2009-06-14 00:45:47 +00007792}
Eli Friedmana95d7572009-08-19 07:44:53 +00007793
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007794GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007795 if (!FD->isExternallyVisible())
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007796 return GVA_Internal;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007797
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007798 GVALinkage External = GVA_StrongExternal;
7799 switch (FD->getTemplateSpecializationKind()) {
7800 case TSK_Undeclared:
7801 case TSK_ExplicitSpecialization:
7802 External = GVA_StrongExternal;
7803 break;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007804
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007805 case TSK_ExplicitInstantiationDefinition:
7806 return GVA_ExplicitTemplateInstantiation;
7807
7808 case TSK_ExplicitInstantiationDeclaration:
7809 case TSK_ImplicitInstantiation:
7810 External = GVA_TemplateInstantiation;
7811 break;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007812 }
7813
7814 if (!FD->isInlined())
7815 return External;
David Majnemer13163702013-08-01 17:26:42 +00007816
7817 if ((!getLangOpts().CPlusPlus && !getLangOpts().MicrosoftMode) ||
7818 FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007819 // GNU or C99 inline semantics. Determine whether this symbol should be
7820 // externally visible.
7821 if (FD->isInlineDefinitionExternallyVisible())
7822 return External;
7823
7824 // C99 inline semantics, where the symbol is not externally visible.
7825 return GVA_C99Inline;
7826 }
7827
7828 // C++0x [temp.explicit]p9:
7829 // [ Note: The intent is that an inline function that is the subject of
7830 // an explicit instantiation declaration will still be implicitly
7831 // instantiated when used so that the body can be considered for
7832 // inlining, but that no out-of-line copy of the inline function would be
7833 // generated in the translation unit. -- end note ]
7834 if (FD->getTemplateSpecializationKind()
7835 == TSK_ExplicitInstantiationDeclaration)
7836 return GVA_C99Inline;
7837
7838 return GVA_CXXInline;
7839}
7840
7841GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007842 if (!VD->isExternallyVisible())
7843 return GVA_Internal;
7844
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007845 // If this is a static data member, compute the kind of template
7846 // specialization. Otherwise, this variable is not part of a
7847 // template.
7848 TemplateSpecializationKind TSK = TSK_Undeclared;
7849 if (VD->isStaticDataMember())
7850 TSK = VD->getTemplateSpecializationKind();
7851
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007852 switch (TSK) {
7853 case TSK_Undeclared:
7854 case TSK_ExplicitSpecialization:
7855 return GVA_StrongExternal;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007856
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007857 case TSK_ExplicitInstantiationDeclaration:
7858 llvm_unreachable("Variable should not be instantiated");
7859 // Fall through to treat this like any other instantiation.
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007860
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007861 case TSK_ExplicitInstantiationDefinition:
7862 return GVA_ExplicitTemplateInstantiation;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007863
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007864 case TSK_ImplicitInstantiation:
7865 return GVA_TemplateInstantiation;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007866 }
Rafael Espindola77b50252013-05-13 14:05:53 +00007867
7868 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007869}
7870
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +00007871bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007872 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7873 if (!VD->isFileVarDecl())
7874 return false;
Richard Smithf396ad92013-04-01 20:22:16 +00007875 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7876 // We never need to emit an uninstantiated function template.
7877 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
7878 return false;
7879 } else
7880 return false;
7881
7882 // If this is a member of a class template, we do not need to emit it.
7883 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007884 return false;
7885
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00007886 // Weak references don't produce any output by themselves.
7887 if (D->hasAttr<WeakRefAttr>())
7888 return false;
7889
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007890 // Aliases and used decls are required.
7891 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7892 return true;
7893
7894 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7895 // Forward declarations aren't required.
Sean Hunt10620eb2011-05-06 20:44:56 +00007896 if (!FD->doesThisDeclarationHaveABody())
Nick Lewyckydce67a72011-07-18 05:26:13 +00007897 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007898
7899 // Constructors and destructors are required.
7900 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7901 return true;
7902
John McCalld5617ee2013-01-25 22:31:03 +00007903 // The key function for a class is required. This rule only comes
7904 // into play when inline functions can be key functions, though.
7905 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7906 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7907 const CXXRecordDecl *RD = MD->getParent();
7908 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7909 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
7910 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7911 return true;
7912 }
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007913 }
7914 }
7915
7916 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7917
7918 // static, static inline, always_inline, and extern inline functions can
7919 // always be deferred. Normal inline functions can be deferred in C99/C++.
7920 // Implicit template instantiations can also be deferred in C++.
7921 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev3a5aca82012-02-02 06:06:34 +00007922 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007923 return false;
7924 return true;
7925 }
Douglas Gregor94da1582011-09-10 00:22:34 +00007926
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007927 const VarDecl *VD = cast<VarDecl>(D);
7928 assert(VD->isFileVarDecl() && "Expected file scoped var");
7929
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00007930 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7931 return false;
7932
Richard Smith5f9a7e32012-11-12 21:38:00 +00007933 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007934 GVALinkage L = GetGVALinkageForVariable(VD);
Richard Smith5f9a7e32012-11-12 21:38:00 +00007935 if (L != GVA_Internal && L != GVA_TemplateInstantiation)
7936 return true;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007937
Richard Smith5f9a7e32012-11-12 21:38:00 +00007938 // Variables that have destruction with side-effects are required.
7939 if (VD->getType().isDestructedType())
7940 return true;
7941
7942 // Variables that have initialization with side-effects are required.
7943 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
7944 return true;
7945
7946 return false;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007947}
Charles Davis071cc7d2010-08-16 03:33:14 +00007948
Reid Kleckneref072032013-08-27 23:08:25 +00007949CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
7950 bool IsCXXMethod) const {
Charles Davisee743f92010-11-09 18:04:24 +00007951 // Pass through to the C++ ABI object
Reid Kleckneref072032013-08-27 23:08:25 +00007952 if (IsCXXMethod)
7953 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007954
Reid Kleckneref072032013-08-27 23:08:25 +00007955 return (LangOpts.MRTD && !IsVariadic) ? CC_X86StdCall : CC_C;
Charles Davisee743f92010-11-09 18:04:24 +00007956}
7957
Jay Foad4ba2a172011-01-12 09:06:06 +00007958bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlssondae0cb52010-11-25 01:51:53 +00007959 // Pass through to the C++ ABI object
7960 return ABI->isNearlyEmpty(RD);
7961}
7962
Peter Collingbourne14110472011-01-13 18:57:25 +00007963MangleContext *ASTContext::createMangleContext() {
John McCallb8b2c9d2013-01-25 22:30:49 +00007964 switch (Target->getCXXABI().getKind()) {
Tim Northoverc264e162013-01-31 12:13:10 +00007965 case TargetCXXABI::GenericAArch64:
John McCallb8b2c9d2013-01-25 22:30:49 +00007966 case TargetCXXABI::GenericItanium:
7967 case TargetCXXABI::GenericARM:
7968 case TargetCXXABI::iOS:
Peter Collingbourne14110472011-01-13 18:57:25 +00007969 return createItaniumMangleContext(*this, getDiagnostics());
John McCallb8b2c9d2013-01-25 22:30:49 +00007970 case TargetCXXABI::Microsoft:
Peter Collingbourne14110472011-01-13 18:57:25 +00007971 return createMicrosoftMangleContext(*this, getDiagnostics());
7972 }
David Blaikieb219cfc2011-09-23 05:06:16 +00007973 llvm_unreachable("Unsupported ABI");
Peter Collingbourne14110472011-01-13 18:57:25 +00007974}
7975
Charles Davis071cc7d2010-08-16 03:33:14 +00007976CXXABI::~CXXABI() {}
Ted Kremenekba29bd22011-04-28 04:53:38 +00007977
7978size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufoef4579c2013-08-06 01:03:05 +00007979 return ASTRecordLayouts.getMemorySize() +
7980 llvm::capacity_in_bytes(ObjCLayouts) +
7981 llvm::capacity_in_bytes(KeyFunctions) +
7982 llvm::capacity_in_bytes(ObjCImpls) +
7983 llvm::capacity_in_bytes(BlockVarCopyInits) +
7984 llvm::capacity_in_bytes(DeclAttrs) +
7985 llvm::capacity_in_bytes(TemplateOrInstantiation) +
7986 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
7987 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
7988 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
7989 llvm::capacity_in_bytes(OverriddenMethods) +
7990 llvm::capacity_in_bytes(Types) +
7991 llvm::capacity_in_bytes(VariableArrayTypes) +
7992 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekba29bd22011-04-28 04:53:38 +00007993}
Ted Kremenekd211cb72011-10-06 05:00:56 +00007994
Stepan Dyatkovskiy7b7bef12013-09-05 11:23:21 +00007995/// getIntTypeForBitwidth -
7996/// sets integer QualTy according to specified details:
7997/// bitwidth, signed/unsigned.
7998/// Returns empty type if there is no appropriate target types.
7999QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
8000 unsigned Signed) const {
8001 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
8002 CanQualType QualTy = getFromTargetType(Ty);
8003 if (!QualTy && DestWidth == 128)
8004 return Signed ? Int128Ty : UnsignedInt128Ty;
8005 return QualTy;
8006}
8007
8008/// getRealTypeForBitwidth -
8009/// sets floating point QualTy according to specified bitwidth.
8010/// Returns empty type if there is no appropriate target types.
8011QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
8012 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
8013 switch (Ty) {
8014 case TargetInfo::Float:
8015 return FloatTy;
8016 case TargetInfo::Double:
8017 return DoubleTy;
8018 case TargetInfo::LongDouble:
8019 return LongDoubleTy;
8020 case TargetInfo::NoFloat:
8021 return QualType();
8022 }
8023
8024 llvm_unreachable("Unhandled TargetInfo::RealType value");
8025}
8026
Eli Friedman5e867c82013-07-10 00:30:46 +00008027void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
8028 if (Number > 1)
8029 MangleNumbers[ND] = Number;
David Blaikie66cff722012-11-14 01:52:05 +00008030}
8031
Eli Friedman5e867c82013-07-10 00:30:46 +00008032unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
8033 llvm::DenseMap<const NamedDecl *, unsigned>::const_iterator I =
8034 MangleNumbers.find(ND);
8035 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie66cff722012-11-14 01:52:05 +00008036}
8037
Eli Friedman5e867c82013-07-10 00:30:46 +00008038MangleNumberingContext &
8039ASTContext::getManglingNumberContext(const DeclContext *DC) {
Eli Friedman07369dd2013-07-01 20:22:57 +00008040 return MangleNumberingContexts[DC];
Douglas Gregor9e8c92a2012-02-20 19:44:39 +00008041}
8042
Ted Kremenekd211cb72011-10-06 05:00:56 +00008043void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8044 ParamIndices[D] = index;
8045}
8046
8047unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8048 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8049 assert(I != ParamIndices.end() &&
8050 "ParmIndices lacks entry set by ParmVarDecl");
8051 return I->second;
8052}
Fariborz Jahanian538bbe52013-05-28 17:37:39 +00008053
Richard Smith211c8dd2013-06-05 00:46:14 +00008054APValue *
8055ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8056 bool MayCreate) {
8057 assert(E && E->getStorageDuration() == SD_Static &&
8058 "don't need to cache the computed value for this temporary");
8059 if (MayCreate)
8060 return &MaterializedTemporaryValues[E];
8061
8062 llvm::DenseMap<const MaterializeTemporaryExpr *, APValue>::iterator I =
8063 MaterializedTemporaryValues.find(E);
8064 return I == MaterializedTemporaryValues.end() ? 0 : &I->second;
8065}
8066
Fariborz Jahanian538bbe52013-05-28 17:37:39 +00008067bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8068 const llvm::Triple &T = getTargetInfo().getTriple();
8069 if (!T.isOSDarwin())
8070 return false;
8071
8072 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8073 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8074 uint64_t Size = sizeChars.getQuantity();
8075 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8076 unsigned Align = alignChars.getQuantity();
8077 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8078 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8079}
Reid Klecknercff15122013-06-17 12:56:08 +00008080
8081namespace {
8082
8083 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8084 /// parents as defined by the \c RecursiveASTVisitor.
8085 ///
8086 /// Note that the relationship described here is purely in terms of AST
8087 /// traversal - there are other relationships (for example declaration context)
8088 /// in the AST that are better modeled by special matchers.
8089 ///
8090 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
8091 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
8092
8093 public:
8094 /// \brief Builds and returns the translation unit's parent map.
8095 ///
8096 /// The caller takes ownership of the returned \c ParentMap.
8097 static ASTContext::ParentMap *buildMap(TranslationUnitDecl &TU) {
8098 ParentMapASTVisitor Visitor(new ASTContext::ParentMap);
8099 Visitor.TraverseDecl(&TU);
8100 return Visitor.Parents;
8101 }
8102
8103 private:
8104 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8105
8106 ParentMapASTVisitor(ASTContext::ParentMap *Parents) : Parents(Parents) {
8107 }
8108
8109 bool shouldVisitTemplateInstantiations() const {
8110 return true;
8111 }
8112 bool shouldVisitImplicitCode() const {
8113 return true;
8114 }
8115 // Disables data recursion. We intercept Traverse* methods in the RAV, which
8116 // are not triggered during data recursion.
8117 bool shouldUseDataRecursionFor(clang::Stmt *S) const {
8118 return false;
8119 }
8120
8121 template <typename T>
8122 bool TraverseNode(T *Node, bool(VisitorBase:: *traverse) (T *)) {
8123 if (Node == NULL)
8124 return true;
8125 if (ParentStack.size() > 0)
8126 // FIXME: Currently we add the same parent multiple times, for example
8127 // when we visit all subexpressions of template instantiations; this is
8128 // suboptimal, bug benign: the only way to visit those is with
8129 // hasAncestor / hasParent, and those do not create new matches.
8130 // The plan is to enable DynTypedNode to be storable in a map or hash
8131 // map. The main problem there is to implement hash functions /
8132 // comparison operators for all types that DynTypedNode supports that
8133 // do not have pointer identity.
8134 (*Parents)[Node].push_back(ParentStack.back());
8135 ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node));
8136 bool Result = (this ->* traverse) (Node);
8137 ParentStack.pop_back();
8138 return Result;
8139 }
8140
8141 bool TraverseDecl(Decl *DeclNode) {
8142 return TraverseNode(DeclNode, &VisitorBase::TraverseDecl);
8143 }
8144
8145 bool TraverseStmt(Stmt *StmtNode) {
8146 return TraverseNode(StmtNode, &VisitorBase::TraverseStmt);
8147 }
8148
8149 ASTContext::ParentMap *Parents;
8150 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8151
8152 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8153 };
8154
8155} // end namespace
8156
8157ASTContext::ParentVector
8158ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
8159 assert(Node.getMemoizationData() &&
8160 "Invariant broken: only nodes that support memoization may be "
8161 "used in the parent map.");
8162 if (!AllParents) {
8163 // We always need to run over the whole translation unit, as
8164 // hasAncestor can escape any subtree.
8165 AllParents.reset(
8166 ParentMapASTVisitor::buildMap(*getTranslationUnitDecl()));
8167 }
8168 ParentMap::const_iterator I = AllParents->find(Node.getMemoizationData());
8169 if (I == AllParents->end()) {
8170 return ParentVector();
8171 }
8172 return I->second;
8173}
Fariborz Jahanianad4aaf12013-07-15 21:22:08 +00008174
8175bool
8176ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
8177 const ObjCMethodDecl *MethodImpl) {
8178 // No point trying to match an unavailable/deprecated mothod.
8179 if (MethodDecl->hasAttr<UnavailableAttr>()
8180 || MethodDecl->hasAttr<DeprecatedAttr>())
8181 return false;
8182 if (MethodDecl->getObjCDeclQualifier() !=
8183 MethodImpl->getObjCDeclQualifier())
8184 return false;
8185 if (!hasSameType(MethodDecl->getResultType(),
8186 MethodImpl->getResultType()))
8187 return false;
8188
8189 if (MethodDecl->param_size() != MethodImpl->param_size())
8190 return false;
8191
8192 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
8193 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
8194 EF = MethodDecl->param_end();
8195 IM != EM && IF != EF; ++IM, ++IF) {
8196 const ParmVarDecl *DeclVar = (*IF);
8197 const ParmVarDecl *ImplVar = (*IM);
8198 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
8199 return false;
8200 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
8201 return false;
8202 }
8203 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
8204
8205}