blob: 4ab987d844f7a7b08aafb19df7ed16a6e1854148 [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"
Reid Kleckner942f9fe2013-09-10 20:14:30 +000028#include "clang/AST/MangleNumberingContext.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000029#include "clang/AST/RecordLayout.h"
Reid Klecknercff15122013-06-17 12:56:08 +000030#include "clang/AST/RecursiveASTVisitor.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000031#include "clang/AST/TypeLoc.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000032#include "clang/Basic/Builtins.h"
Chris Lattnera9376d42009-03-28 03:45:20 +000033#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000034#include "clang/Basic/TargetInfo.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000035#include "llvm/ADT/SmallString.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000036#include "llvm/ADT/StringExtras.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000037#include "llvm/Support/Capacity.h"
Nate Begeman6fe7c8a2009-01-18 06:42:49 +000038#include "llvm/Support/MathExtras.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000039#include "llvm/Support/raw_ostream.h"
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +000040#include <map>
Anders Carlsson29445a02009-07-18 21:19:52 +000041
Reid Spencer5f016e22007-07-11 17:01:13 +000042using namespace clang;
43
Douglas Gregor18274032010-07-03 00:47:00 +000044unsigned ASTContext::NumImplicitDefaultConstructors;
45unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregor22584312010-07-02 23:41:54 +000046unsigned ASTContext::NumImplicitCopyConstructors;
47unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Sean Huntffe37fd2011-05-25 20:50:04 +000048unsigned ASTContext::NumImplicitMoveConstructors;
49unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregora376d102010-07-02 21:50:04 +000050unsigned ASTContext::NumImplicitCopyAssignmentOperators;
51unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Huntffe37fd2011-05-25 20:50:04 +000052unsigned ASTContext::NumImplicitMoveAssignmentOperators;
53unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor4923aa22010-07-02 20:37:36 +000054unsigned ASTContext::NumImplicitDestructors;
55unsigned ASTContext::NumImplicitDestructorsDeclared;
56
Reid Spencer5f016e22007-07-11 17:01:13 +000057enum FloatingRank {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +000058 HalfRank, FloatRank, DoubleRank, LongDoubleRank
Reid Spencer5f016e22007-07-11 17:01:13 +000059};
60
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +000061RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +000062 if (!CommentsLoaded && ExternalSource) {
63 ExternalSource->ReadComments();
64 CommentsLoaded = true;
65 }
66
67 assert(D);
68
Dmitri Gribenkoc3fee352012-06-28 16:19:39 +000069 // User can not attach documentation to implicit declarations.
70 if (D->isImplicit())
71 return NULL;
72
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +000073 // User can not attach documentation to implicit instantiations.
74 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
75 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
76 return NULL;
77 }
78
Dmitri Gribenkodce750b2012-08-20 22:36:31 +000079 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
80 if (VD->isStaticDataMember() &&
81 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
82 return NULL;
83 }
84
85 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
86 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
87 return NULL;
88 }
89
Dmitri Gribenkod1e5c0d2013-01-27 21:18:39 +000090 if (const ClassTemplateSpecializationDecl *CTSD =
91 dyn_cast<ClassTemplateSpecializationDecl>(D)) {
92 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
93 if (TSK == TSK_ImplicitInstantiation ||
94 TSK == TSK_Undeclared)
95 return NULL;
96 }
97
Dmitri Gribenkodce750b2012-08-20 22:36:31 +000098 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
99 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
100 return NULL;
101 }
Fariborz Jahanian099ecfb2013-04-17 21:05:20 +0000102 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
103 // When tag declaration (but not definition!) is part of the
104 // decl-specifier-seq of some other declaration, it doesn't get comment
105 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
106 return NULL;
107 }
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000108 // TODO: handle comments for function parameters properly.
109 if (isa<ParmVarDecl>(D))
110 return NULL;
111
Dmitri Gribenko96b09862012-07-31 22:37:06 +0000112 // TODO: we could look up template parameter documentation in the template
113 // documentation.
114 if (isa<TemplateTypeParmDecl>(D) ||
115 isa<NonTypeTemplateParmDecl>(D) ||
116 isa<TemplateTemplateParmDecl>(D))
117 return NULL;
118
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000119 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000120
121 // If there are no comments anywhere, we won't find anything.
122 if (RawComments.empty())
123 return NULL;
124
Dmitri Gribenkoabd56c82012-07-13 01:06:46 +0000125 // Find declaration location.
126 // For Objective-C declarations we generally don't expect to have multiple
127 // declarators, thus use declaration starting location as the "declaration
128 // location".
129 // For all other declarations multiple declarators are used quite frequently,
130 // so we use the location of the identifier as the "declaration location".
131 SourceLocation DeclLoc;
132 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko96b09862012-07-31 22:37:06 +0000133 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +0000134 isa<RedeclarableTemplateDecl>(D) ||
135 isa<ClassTemplateSpecializationDecl>(D))
Dmitri Gribenkoabd56c82012-07-13 01:06:46 +0000136 DeclLoc = D->getLocStart();
Fariborz Jahanianceaa1ec2013-07-24 22:58:51 +0000137 else {
Dmitri Gribenkoabd56c82012-07-13 01:06:46 +0000138 DeclLoc = D->getLocation();
Fariborz Jahanianceaa1ec2013-07-24 22:58:51 +0000139 // If location of the typedef name is in a macro, it is because being
140 // declared via a macro. Try using declaration's starting location
141 // as the "declaration location".
142 if (DeclLoc.isMacroID() && isa<TypedefDecl>(D))
143 DeclLoc = D->getLocStart();
144 }
Dmitri Gribenkoabd56c82012-07-13 01:06:46 +0000145
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000146 // If the declaration doesn't map directly to a location in a file, we
147 // can't find the comment.
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000148 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
149 return NULL;
150
151 // Find the comment that occurs just after this declaration.
Dmitri Gribenkoa444f182012-07-17 22:01:09 +0000152 ArrayRef<RawComment *>::iterator Comment;
153 {
154 // When searching for comments during parsing, the comment we are looking
155 // for is usually among the last two comments we parsed -- check them
156 // first.
Dmitri Gribenko6fd7d302013-04-10 15:35:17 +0000157 RawComment CommentAtDeclLoc(
158 SourceMgr, SourceRange(DeclLoc), false,
159 LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenkoa444f182012-07-17 22:01:09 +0000160 BeforeThanCompare<RawComment> Compare(SourceMgr);
161 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
162 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
163 if (!Found && RawComments.size() >= 2) {
164 MaybeBeforeDecl--;
165 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
166 }
167
168 if (Found) {
169 Comment = MaybeBeforeDecl + 1;
170 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
171 &CommentAtDeclLoc, Compare));
172 } else {
173 // Slow path.
174 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
175 &CommentAtDeclLoc, Compare);
176 }
177 }
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000178
179 // Decompose the location for the declaration and find the beginning of the
180 // file buffer.
181 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
182
183 // First check whether we have a trailing comment.
184 if (Comment != RawComments.end() &&
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000185 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
Fariborz Jahanian8c238be2013-08-06 23:29:00 +0000186 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
Fariborz Jahanian15c8e562013-08-07 16:40:29 +0000187 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000188 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000189 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000190 // Check that Doxygen trailing comment comes after the declaration, starts
191 // on the same line and in the same file as the declaration.
192 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
193 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
194 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
195 CommentBeginDecomp.second)) {
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000196 return *Comment;
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000197 }
198 }
199
200 // The comment just after the declaration was not a trailing comment.
201 // Let's look at the previous comment.
202 if (Comment == RawComments.begin())
203 return NULL;
204 --Comment;
205
206 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000207 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000208 return NULL;
209
210 // Decompose the end of the comment.
211 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000212 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000213
214 // If the comment and the declaration aren't in the same file, then they
215 // aren't related.
216 if (DeclLocDecomp.first != CommentEndDecomp.first)
217 return NULL;
218
219 // Get the corresponding buffer.
220 bool Invalid = false;
221 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
222 &Invalid).data();
223 if (Invalid)
224 return NULL;
225
226 // Extract text between the comment and declaration.
227 StringRef Text(Buffer + CommentEndDecomp.second,
228 DeclLocDecomp.second - CommentEndDecomp.second);
229
Dmitri Gribenko8bdb58a2012-06-27 23:43:37 +0000230 // There should be no other declarations or preprocessor directives between
231 // comment and declaration.
Argyrios Kyrtzidisdc663262013-07-26 18:38:12 +0000232 if (Text.find_first_of(";{}#@") != StringRef::npos)
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000233 return NULL;
234
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000235 return *Comment;
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000236}
237
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000238namespace {
239/// If we have a 'templated' declaration for a template, adjust 'D' to
240/// refer to the actual template.
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000241/// If we have an implicit instantiation, adjust 'D' to refer to template.
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000242const Decl *adjustDeclToTemplate(const Decl *D) {
Douglas Gregorcd81df22012-08-13 16:37:30 +0000243 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000244 // Is this function declaration part of a function template?
Douglas Gregorcd81df22012-08-13 16:37:30 +0000245 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000246 return FTD;
247
248 // Nothing to do if function is not an implicit instantiation.
249 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
250 return D;
251
252 // Function is an implicit instantiation of a function template?
253 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
254 return FTD;
255
256 // Function is instantiated from a member definition of a class template?
257 if (const FunctionDecl *MemberDecl =
258 FD->getInstantiatedFromMemberFunction())
259 return MemberDecl;
260
261 return D;
Douglas Gregorcd81df22012-08-13 16:37:30 +0000262 }
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000263 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
264 // Static data member is instantiated from a member definition of a class
265 // template?
266 if (VD->isStaticDataMember())
267 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
268 return MemberDecl;
269
270 return D;
271 }
272 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
273 // Is this class declaration part of a class template?
274 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
275 return CTD;
276
277 // Class is an implicit instantiation of a class template or partial
278 // specialization?
279 if (const ClassTemplateSpecializationDecl *CTSD =
280 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
281 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
282 return D;
283 llvm::PointerUnion<ClassTemplateDecl *,
284 ClassTemplatePartialSpecializationDecl *>
285 PU = CTSD->getSpecializedTemplateOrPartial();
286 return PU.is<ClassTemplateDecl*>() ?
287 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
288 static_cast<const Decl*>(
289 PU.get<ClassTemplatePartialSpecializationDecl *>());
290 }
291
292 // Class is instantiated from a member definition of a class template?
293 if (const MemberSpecializationInfo *Info =
294 CRD->getMemberSpecializationInfo())
295 return Info->getInstantiatedFrom();
296
297 return D;
298 }
299 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
300 // Enum is instantiated from a member definition of a class template?
301 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
302 return MemberDecl;
303
304 return D;
305 }
306 // FIXME: Adjust alias templates?
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000307 return D;
308}
309} // unnamed namespace
310
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000311const RawComment *ASTContext::getRawCommentForAnyRedecl(
312 const Decl *D,
313 const Decl **OriginalDecl) const {
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000314 D = adjustDeclToTemplate(D);
Douglas Gregorcd81df22012-08-13 16:37:30 +0000315
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000316 // Check whether we have cached a comment for this declaration already.
317 {
318 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
319 RedeclComments.find(D);
320 if (Pos != RedeclComments.end()) {
321 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000322 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
323 if (OriginalDecl)
324 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000325 return Raw.getRaw();
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000326 }
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000327 }
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000328 }
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000329
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000330 // Search for comments attached to declarations in the redeclaration chain.
331 const RawComment *RC = NULL;
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000332 const Decl *OriginalDeclForRC = NULL;
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000333 for (Decl::redecl_iterator I = D->redecls_begin(),
334 E = D->redecls_end();
335 I != E; ++I) {
336 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
337 RedeclComments.find(*I);
338 if (Pos != RedeclComments.end()) {
339 const RawCommentAndCacheFlags &Raw = Pos->second;
340 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
341 RC = Raw.getRaw();
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000342 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000343 break;
344 }
345 } else {
346 RC = getRawCommentForDeclNoCache(*I);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000347 OriginalDeclForRC = *I;
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000348 RawCommentAndCacheFlags Raw;
349 if (RC) {
350 Raw.setRaw(RC);
351 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
352 } else
353 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000354 Raw.setOriginalDecl(*I);
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000355 RedeclComments[*I] = Raw;
356 if (RC)
357 break;
358 }
359 }
360
Dmitri Gribenko8376f592012-06-28 16:25:36 +0000361 // If we found a comment, it should be a documentation comment.
362 assert(!RC || RC->isDocumentation());
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000363
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000364 if (OriginalDecl)
365 *OriginalDecl = OriginalDeclForRC;
366
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000367 // Update cache for every declaration in the redeclaration chain.
368 RawCommentAndCacheFlags Raw;
369 Raw.setRaw(RC);
370 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000371 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000372
373 for (Decl::redecl_iterator I = D->redecls_begin(),
374 E = D->redecls_end();
375 I != E; ++I) {
376 RawCommentAndCacheFlags &R = RedeclComments[*I];
377 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
378 R = Raw;
379 }
380
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000381 return RC;
382}
383
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000384static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
385 SmallVectorImpl<const NamedDecl *> &Redeclared) {
386 const DeclContext *DC = ObjCMethod->getDeclContext();
387 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
388 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
389 if (!ID)
390 return;
391 // Add redeclared method here.
Douglas Gregord3297242013-01-16 23:00:23 +0000392 for (ObjCInterfaceDecl::known_extensions_iterator
393 Ext = ID->known_extensions_begin(),
394 ExtEnd = ID->known_extensions_end();
395 Ext != ExtEnd; ++Ext) {
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000396 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregord3297242013-01-16 23:00:23 +0000397 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000398 ObjCMethod->isInstanceMethod()))
399 Redeclared.push_back(RedeclaredMethod);
400 }
401 }
402}
403
Fariborz Jahanian749ace62012-10-11 23:52:50 +0000404comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
405 const Decl *D) const {
406 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
407 ThisDeclInfo->CommentDecl = D;
408 ThisDeclInfo->IsFilled = false;
409 ThisDeclInfo->fill();
410 ThisDeclInfo->CommentDecl = FC->getDecl();
411 comments::FullComment *CFC =
412 new (*this) comments::FullComment(FC->getBlocks(),
413 ThisDeclInfo);
414 return CFC;
415
416}
417
Richard Smith0a74a4c2013-05-21 05:24:00 +0000418comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
419 const RawComment *RC = getRawCommentForDeclNoCache(D);
420 return RC ? RC->parse(*this, 0, D) : 0;
421}
422
Dmitri Gribenko19523542012-09-29 11:40:46 +0000423comments::FullComment *ASTContext::getCommentForDecl(
424 const Decl *D,
425 const Preprocessor *PP) const {
Fariborz Jahanianfbff0c42013-05-13 17:27:00 +0000426 if (D->isInvalidDecl())
427 return NULL;
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000428 D = adjustDeclToTemplate(D);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000429
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000430 const Decl *Canonical = D->getCanonicalDecl();
431 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
432 ParsedComments.find(Canonical);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000433
434 if (Pos != ParsedComments.end()) {
Fariborz Jahanian749ace62012-10-11 23:52:50 +0000435 if (Canonical != D) {
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000436 comments::FullComment *FC = Pos->second;
Fariborz Jahanian749ace62012-10-11 23:52:50 +0000437 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000438 return CFC;
439 }
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000440 return Pos->second;
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000441 }
442
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000443 const Decl *OriginalDecl;
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000444
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000445 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000446 if (!RC) {
447 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko1e905da2012-11-03 14:24:57 +0000448 SmallVector<const NamedDecl*, 8> Overridden;
Fariborz Jahanianc328d9c2013-01-12 00:28:34 +0000449 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian23799e32013-01-25 23:08:39 +0000450 if (OMD && OMD->isPropertyAccessor())
451 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
452 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
453 return cloneFullComment(FC, D);
Fariborz Jahanianc328d9c2013-01-12 00:28:34 +0000454 if (OMD)
Dmitri Gribenko1e905da2012-11-03 14:24:57 +0000455 addRedeclaredMethods(OMD, Overridden);
456 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian23799e32013-01-25 23:08:39 +0000457 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
458 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
459 return cloneFullComment(FC, D);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000460 }
Fariborz Jahanian4857fdc2013-05-02 15:44:16 +0000461 else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenkod1e5c0d2013-01-27 21:18:39 +0000462 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian23799e32013-01-25 23:08:39 +0000463 // does not have one of its own.
Fariborz Jahanian41170b52013-01-25 22:48:32 +0000464 QualType QT = TD->getUnderlyingType();
Dmitri Gribenkod1e5c0d2013-01-27 21:18:39 +0000465 if (const TagType *TT = QT->getAs<TagType>())
466 if (const Decl *TD = TT->getDecl())
467 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian23799e32013-01-25 23:08:39 +0000468 return cloneFullComment(FC, D);
Fariborz Jahanian41170b52013-01-25 22:48:32 +0000469 }
Fariborz Jahanian622bb4a2013-04-26 20:55:38 +0000470 else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
471 while (IC->getSuperClass()) {
472 IC = IC->getSuperClass();
473 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
474 return cloneFullComment(FC, D);
475 }
476 }
477 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
478 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
479 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
480 return cloneFullComment(FC, D);
481 }
482 else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
483 if (!(RD = RD->getDefinition()))
484 return NULL;
485 // Check non-virtual bases.
486 for (CXXRecordDecl::base_class_const_iterator I =
487 RD->bases_begin(), E = RD->bases_end(); I != E; ++I) {
Fariborz Jahanian91efca02013-04-26 23:34:36 +0000488 if (I->isVirtual() || (I->getAccessSpecifier() != AS_public))
Fariborz Jahanian622bb4a2013-04-26 20:55:38 +0000489 continue;
490 QualType Ty = I->getType();
491 if (Ty.isNull())
492 continue;
493 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
494 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
495 continue;
496
497 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
498 return cloneFullComment(FC, D);
499 }
500 }
501 // Check virtual bases.
502 for (CXXRecordDecl::base_class_const_iterator I =
503 RD->vbases_begin(), E = RD->vbases_end(); I != E; ++I) {
Fariborz Jahanian91efca02013-04-26 23:34:36 +0000504 if (I->getAccessSpecifier() != AS_public)
505 continue;
Fariborz Jahanian622bb4a2013-04-26 20:55:38 +0000506 QualType Ty = I->getType();
507 if (Ty.isNull())
508 continue;
509 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
510 if (!(VirtualBase= VirtualBase->getDefinition()))
511 continue;
512 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
513 return cloneFullComment(FC, D);
514 }
515 }
516 }
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000517 return NULL;
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000518 }
519
Dmitri Gribenko4b41c652012-08-22 18:12:19 +0000520 // If the RawComment was attached to other redeclaration of this Decl, we
521 // should parse the comment in context of that other Decl. This is important
522 // because comments can contain references to parameter names which can be
523 // different across redeclarations.
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000524 if (D != OriginalDecl)
Dmitri Gribenko19523542012-09-29 11:40:46 +0000525 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000526
Dmitri Gribenko19523542012-09-29 11:40:46 +0000527 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000528 ParsedComments[Canonical] = FC;
529 return FC;
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000530}
531
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000532void
533ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
534 TemplateTemplateParmDecl *Parm) {
535 ID.AddInteger(Parm->getDepth());
536 ID.AddInteger(Parm->getPosition());
Douglas Gregor61c4d282011-01-05 15:48:55 +0000537 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000538
539 TemplateParameterList *Params = Parm->getTemplateParameters();
540 ID.AddInteger(Params->size());
541 for (TemplateParameterList::const_iterator P = Params->begin(),
542 PEnd = Params->end();
543 P != PEnd; ++P) {
544 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
545 ID.AddInteger(0);
546 ID.AddBoolean(TTP->isParameterPack());
547 continue;
548 }
549
550 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
551 ID.AddInteger(1);
Douglas Gregor61c4d282011-01-05 15:48:55 +0000552 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman9e9c4542012-03-07 01:09:33 +0000553 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000554 if (NTTP->isExpandedParameterPack()) {
555 ID.AddBoolean(true);
556 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman9e9c4542012-03-07 01:09:33 +0000557 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
558 QualType T = NTTP->getExpansionType(I);
559 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
560 }
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000561 } else
562 ID.AddBoolean(false);
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000563 continue;
564 }
565
566 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
567 ID.AddInteger(2);
568 Profile(ID, TTP);
569 }
570}
571
572TemplateTemplateParmDecl *
573ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad4ba2a172011-01-12 09:06:06 +0000574 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000575 // Check if we already have a canonical template template parameter.
576 llvm::FoldingSetNodeID ID;
577 CanonicalTemplateTemplateParm::Profile(ID, TTP);
578 void *InsertPos = 0;
579 CanonicalTemplateTemplateParm *Canonical
580 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
581 if (Canonical)
582 return Canonical->getParam();
583
584 // Build a canonical template parameter list.
585 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000586 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000587 CanonParams.reserve(Params->size());
588 for (TemplateParameterList::const_iterator P = Params->begin(),
589 PEnd = Params->end();
590 P != PEnd; ++P) {
591 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
592 CanonParams.push_back(
593 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnara344577e2011-03-06 15:48:19 +0000594 SourceLocation(),
595 SourceLocation(),
596 TTP->getDepth(),
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000597 TTP->getIndex(), 0, false,
598 TTP->isParameterPack()));
599 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000600 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
601 QualType T = getCanonicalType(NTTP->getType());
602 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
603 NonTypeTemplateParmDecl *Param;
604 if (NTTP->isExpandedParameterPack()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000605 SmallVector<QualType, 2> ExpandedTypes;
606 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000607 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
608 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
609 ExpandedTInfos.push_back(
610 getTrivialTypeSourceInfo(ExpandedTypes.back()));
611 }
612
613 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000614 SourceLocation(),
615 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000616 NTTP->getDepth(),
617 NTTP->getPosition(), 0,
618 T,
619 TInfo,
620 ExpandedTypes.data(),
621 ExpandedTypes.size(),
622 ExpandedTInfos.data());
623 } else {
624 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000625 SourceLocation(),
626 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000627 NTTP->getDepth(),
628 NTTP->getPosition(), 0,
629 T,
630 NTTP->isParameterPack(),
631 TInfo);
632 }
633 CanonParams.push_back(Param);
634
635 } else
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000636 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
637 cast<TemplateTemplateParmDecl>(*P)));
638 }
639
640 TemplateTemplateParmDecl *CanonTTP
641 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
642 SourceLocation(), TTP->getDepth(),
Douglas Gregor61c4d282011-01-05 15:48:55 +0000643 TTP->getPosition(),
644 TTP->isParameterPack(),
645 0,
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000646 TemplateParameterList::Create(*this, SourceLocation(),
647 SourceLocation(),
648 CanonParams.data(),
649 CanonParams.size(),
650 SourceLocation()));
651
652 // Get the new insert position for the node we care about.
653 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
654 assert(Canonical == 0 && "Shouldn't be in the map!");
655 (void)Canonical;
656
657 // Create the canonical template template parameter entry.
658 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
659 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
660 return CanonTTP;
661}
662
Charles Davis071cc7d2010-08-16 03:33:14 +0000663CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCallee79a4c2010-08-21 22:46:04 +0000664 if (!LangOpts.CPlusPlus) return 0;
665
John McCallb8b2c9d2013-01-25 22:30:49 +0000666 switch (T.getCXXABI().getKind()) {
667 case TargetCXXABI::GenericARM:
668 case TargetCXXABI::iOS:
John McCallee79a4c2010-08-21 22:46:04 +0000669 return CreateARMCXXABI(*this);
Tim Northoverc264e162013-01-31 12:13:10 +0000670 case TargetCXXABI::GenericAArch64: // Same as Itanium at this level
John McCallb8b2c9d2013-01-25 22:30:49 +0000671 case TargetCXXABI::GenericItanium:
Charles Davis071cc7d2010-08-16 03:33:14 +0000672 return CreateItaniumCXXABI(*this);
John McCallb8b2c9d2013-01-25 22:30:49 +0000673 case TargetCXXABI::Microsoft:
Charles Davis20cf7172010-08-19 02:18:14 +0000674 return CreateMicrosoftCXXABI(*this);
675 }
David Blaikie7530c032012-01-17 06:56:22 +0000676 llvm_unreachable("Invalid CXXABI type!");
Charles Davis071cc7d2010-08-16 03:33:14 +0000677}
678
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000679static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000680 const LangOptions &LOpts) {
681 if (LOpts.FakeAddressSpaceMap) {
682 // The fake address space map must have a distinct entry for each
683 // language-specific address space.
684 static const unsigned FakeAddrSpaceMap[] = {
685 1, // opencl_global
686 2, // opencl_local
Peter Collingbourne4dc34eb2012-05-20 21:08:35 +0000687 3, // opencl_constant
688 4, // cuda_device
689 5, // cuda_constant
690 6 // cuda_shared
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000691 };
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000692 return &FakeAddrSpaceMap;
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000693 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000694 return &T.getAddressSpaceMap();
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000695 }
696}
697
Douglas Gregor3e3cd932011-09-01 20:23:19 +0000698ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000699 const TargetInfo *t,
Daniel Dunbare91593e2008-08-11 04:54:23 +0000700 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000701 Builtin::Context &builtins,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000702 unsigned size_reserve,
703 bool DelayInitialization)
704 : FunctionProtoTypes(this_()),
705 TemplateSpecializationTypes(this_()),
706 DependentTemplateSpecializationTypes(this_()),
707 SubstTemplateTemplateParmPacks(this_()),
708 GlobalNestedNameSpecifier(0),
Nico Webercac18ad2013-06-20 21:44:55 +0000709 Int128Decl(0), UInt128Decl(0), Float128StubDecl(0),
Meador Ingec5613b22012-06-16 03:34:49 +0000710 BuiltinVaListDecl(0),
Douglas Gregora6ea10e2012-01-17 18:09:05 +0000711 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Fariborz Jahanian96171302012-08-30 18:49:41 +0000712 BOOLDecl(0),
Douglas Gregore97179c2011-09-08 01:46:34 +0000713 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000714 FILEDecl(0),
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +0000715 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
716 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
717 cudaConfigureCallDecl(0),
Douglas Gregore6649772011-12-03 00:30:27 +0000718 NullTypeSourceInfo(QualType()),
719 FirstLocalImport(), LastLocalImport(),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000720 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregor30c42402011-09-27 22:38:19 +0000721 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000722 Idents(idents), Selectors(sels),
723 BuiltinInfo(builtins),
724 DeclarationNames(*this),
Douglas Gregor30c42402011-09-27 22:38:19 +0000725 ExternalSource(0), Listener(0),
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000726 Comments(SM), CommentsLoaded(false),
Dmitri Gribenko6ebf0912013-02-22 14:21:27 +0000727 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
Rafael Espindola42b78612013-05-29 19:51:12 +0000728 LastSDM(0, 0)
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000729{
Mike Stump1eb44332009-09-09 15:08:12 +0000730 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +0000731 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000732
733 if (!DelayInitialization) {
734 assert(t && "No target supplied for ASTContext initialization");
735 InitBuiltinTypes(*t);
736 }
Daniel Dunbare91593e2008-08-11 04:54:23 +0000737}
738
Reid Spencer5f016e22007-07-11 17:01:13 +0000739ASTContext::~ASTContext() {
Ted Kremenek3478eb62010-02-11 07:12:28 +0000740 // Release the DenseMaps associated with DeclContext objects.
741 // FIXME: Is this the ideal solution?
742 ReleaseDeclContextMaps();
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000743
Manuel Klimekf0f353b2013-06-03 13:51:33 +0000744 // Call all of the deallocation functions on all of their targets.
745 for (DeallocationMap::const_iterator I = Deallocations.begin(),
746 E = Deallocations.end(); I != E; ++I)
747 for (unsigned J = 0, N = I->second.size(); J != N; ++J)
748 (I->first)((I->second)[J]);
749
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000750 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000751 // because they can contain DenseMaps.
752 for (llvm::DenseMap<const ObjCContainerDecl*,
753 const ASTRecordLayout*>::iterator
754 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
755 // Increment in loop to prevent using deallocated memory.
756 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
757 R->Destroy(*this);
758
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000759 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
760 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
761 // Increment in loop to prevent using deallocated memory.
762 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
763 R->Destroy(*this);
764 }
Douglas Gregor63200642010-08-30 16:49:28 +0000765
766 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
767 AEnd = DeclAttrs.end();
768 A != AEnd; ++A)
769 A->second->~AttrVec();
Reid Kleckner942f9fe2013-09-10 20:14:30 +0000770
771 for (llvm::DenseMap<const DeclContext *, MangleNumberingContext *>::iterator
772 I = MangleNumberingContexts.begin(),
773 E = MangleNumberingContexts.end();
774 I != E; ++I)
775 delete I->second;
Douglas Gregor63200642010-08-30 16:49:28 +0000776}
Douglas Gregorab452ba2009-03-26 23:50:42 +0000777
Douglas Gregor00545312010-05-23 18:26:36 +0000778void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Manuel Klimekf0f353b2013-06-03 13:51:33 +0000779 Deallocations[Callback].push_back(Data);
Douglas Gregor00545312010-05-23 18:26:36 +0000780}
781
Mike Stump1eb44332009-09-09 15:08:12 +0000782void
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000783ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregor2cf26342009-04-09 22:27:44 +0000784 ExternalSource.reset(Source.take());
785}
786
Reid Spencer5f016e22007-07-11 17:01:13 +0000787void ASTContext::PrintStats() const {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000788 llvm::errs() << "\n*** AST Context Stats:\n";
789 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000790
Douglas Gregordbe833d2009-05-26 14:40:08 +0000791 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000792#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000793#define ABSTRACT_TYPE(Name, Parent)
794#include "clang/AST/TypeNodes.def"
795 0 // Extra
796 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000797
Reid Spencer5f016e22007-07-11 17:01:13 +0000798 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
799 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000800 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000801 }
802
Douglas Gregordbe833d2009-05-26 14:40:08 +0000803 unsigned Idx = 0;
804 unsigned TotalBytes = 0;
805#define TYPE(Name, Parent) \
806 if (counts[Idx]) \
Chandler Carruthcd92a652011-07-04 05:32:14 +0000807 llvm::errs() << " " << counts[Idx] << " " << #Name \
808 << " types\n"; \
Douglas Gregordbe833d2009-05-26 14:40:08 +0000809 TotalBytes += counts[Idx] * sizeof(Name##Type); \
810 ++Idx;
811#define ABSTRACT_TYPE(Name, Parent)
812#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000813
Chandler Carruthcd92a652011-07-04 05:32:14 +0000814 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
815
Douglas Gregor4923aa22010-07-02 20:37:36 +0000816 // Implicit special member functions.
Chandler Carruthcd92a652011-07-04 05:32:14 +0000817 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
818 << NumImplicitDefaultConstructors
819 << " implicit default constructors created\n";
820 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
821 << NumImplicitCopyConstructors
822 << " implicit copy constructors created\n";
David Blaikie4e4d0842012-03-11 07:00:24 +0000823 if (getLangOpts().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000824 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
825 << NumImplicitMoveConstructors
826 << " implicit move constructors created\n";
827 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
828 << NumImplicitCopyAssignmentOperators
829 << " implicit copy assignment operators created\n";
David Blaikie4e4d0842012-03-11 07:00:24 +0000830 if (getLangOpts().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000831 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
832 << NumImplicitMoveAssignmentOperators
833 << " implicit move assignment operators created\n";
834 llvm::errs() << NumImplicitDestructorsDeclared << "/"
835 << NumImplicitDestructors
836 << " implicit destructors created\n";
837
Douglas Gregor2cf26342009-04-09 22:27:44 +0000838 if (ExternalSource.get()) {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000839 llvm::errs() << "\n";
Douglas Gregor2cf26342009-04-09 22:27:44 +0000840 ExternalSource->PrintStats();
841 }
Chandler Carruthcd92a652011-07-04 05:32:14 +0000842
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000843 BumpAlloc.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000844}
845
Douglas Gregor772eeae2011-08-12 06:49:56 +0000846TypedefDecl *ASTContext::getInt128Decl() const {
847 if (!Int128Decl) {
848 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
849 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
850 getTranslationUnitDecl(),
851 SourceLocation(),
852 SourceLocation(),
853 &Idents.get("__int128_t"),
854 TInfo);
855 }
856
857 return Int128Decl;
858}
859
860TypedefDecl *ASTContext::getUInt128Decl() const {
861 if (!UInt128Decl) {
862 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
863 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
864 getTranslationUnitDecl(),
865 SourceLocation(),
866 SourceLocation(),
867 &Idents.get("__uint128_t"),
868 TInfo);
869 }
870
871 return UInt128Decl;
872}
Reid Spencer5f016e22007-07-11 17:01:13 +0000873
Nico Webercac18ad2013-06-20 21:44:55 +0000874TypeDecl *ASTContext::getFloat128StubType() const {
Nico Weber3f7c1b12013-06-21 01:29:36 +0000875 assert(LangOpts.CPlusPlus && "should only be called for c++");
Nico Webercac18ad2013-06-20 21:44:55 +0000876 if (!Float128StubDecl) {
Nico Weber9b9bdba2013-06-20 23:30:30 +0000877 Float128StubDecl = CXXRecordDecl::Create(const_cast<ASTContext &>(*this),
878 TTK_Struct,
879 getTranslationUnitDecl(),
880 SourceLocation(),
881 SourceLocation(),
882 &Idents.get("__float128"));
Nico Webercac18ad2013-06-20 21:44:55 +0000883 }
884
885 return Float128StubDecl;
886}
887
John McCalle27ec8a2009-10-23 23:03:21 +0000888void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000889 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000890 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000891 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000892}
893
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000894void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
895 assert((!this->Target || this->Target == &Target) &&
896 "Incorrect target reinitialization");
Reid Spencer5f016e22007-07-11 17:01:13 +0000897 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000898
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000899 this->Target = &Target;
900
901 ABI.reset(createCXXABI(Target));
902 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
903
Reid Spencer5f016e22007-07-11 17:01:13 +0000904 // C99 6.2.5p19.
905 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000906
Reid Spencer5f016e22007-07-11 17:01:13 +0000907 // C99 6.2.5p2.
908 InitBuiltinType(BoolTy, BuiltinType::Bool);
909 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000910 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000911 InitBuiltinType(CharTy, BuiltinType::Char_S);
912 else
913 InitBuiltinType(CharTy, BuiltinType::Char_U);
914 // C99 6.2.5p4.
915 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
916 InitBuiltinType(ShortTy, BuiltinType::Short);
917 InitBuiltinType(IntTy, BuiltinType::Int);
918 InitBuiltinType(LongTy, BuiltinType::Long);
919 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000920
Reid Spencer5f016e22007-07-11 17:01:13 +0000921 // C99 6.2.5p6.
922 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
923 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
924 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
925 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
926 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000927
Reid Spencer5f016e22007-07-11 17:01:13 +0000928 // C99 6.2.5p10.
929 InitBuiltinType(FloatTy, BuiltinType::Float);
930 InitBuiltinType(DoubleTy, BuiltinType::Double);
931 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000932
Chris Lattner2df9ced2009-04-30 02:43:43 +0000933 // GNU extension, 128-bit integers.
934 InitBuiltinType(Int128Ty, BuiltinType::Int128);
935 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
936
Hans Wennborg15f92ba2013-05-10 10:08:40 +0000937 // C++ 3.9.1p5
938 if (TargetInfo::isTypeSigned(Target.getWCharType()))
939 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
940 else // -fshort-wchar makes wchar_t be unsigned.
941 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
942 if (LangOpts.CPlusPlus && LangOpts.WChar)
943 WideCharTy = WCharTy;
944 else {
945 // C99 (or C++ using -fno-wchar).
946 WideCharTy = getFromTargetType(Target.getWCharType());
947 }
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000948
James Molloy392da482012-05-04 10:55:22 +0000949 WIntTy = getFromTargetType(Target.getWIntType());
950
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000951 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
952 InitBuiltinType(Char16Ty, BuiltinType::Char16);
953 else // C99
954 Char16Ty = getFromTargetType(Target.getChar16Type());
955
956 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
957 InitBuiltinType(Char32Ty, BuiltinType::Char32);
958 else // C99
959 Char32Ty = getFromTargetType(Target.getChar32Type());
960
Douglas Gregor898574e2008-12-05 23:32:09 +0000961 // Placeholder type for type-dependent expressions whose type is
962 // completely unknown. No code should ever check a type against
963 // DependentTy and users should never see it; however, it is here to
964 // help diagnose failures to properly check for type-dependent
965 // expressions.
966 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000967
John McCall2a984ca2010-10-12 00:20:44 +0000968 // Placeholder type for functions.
969 InitBuiltinType(OverloadTy, BuiltinType::Overload);
970
John McCall864c0412011-04-26 20:42:42 +0000971 // Placeholder type for bound members.
972 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
973
John McCall3c3b7f92011-10-25 17:37:35 +0000974 // Placeholder type for pseudo-objects.
975 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
976
John McCall1de4d4e2011-04-07 08:22:57 +0000977 // "any" type; useful for debugger-like clients.
978 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
979
John McCall0ddaeb92011-10-17 18:09:15 +0000980 // Placeholder type for unbridged ARC casts.
981 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
982
Eli Friedmana6c66ce2012-08-31 00:14:07 +0000983 // Placeholder type for builtin functions.
984 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
985
Reid Spencer5f016e22007-07-11 17:01:13 +0000986 // C99 6.2.5p11.
987 FloatComplexTy = getComplexType(FloatTy);
988 DoubleComplexTy = getComplexType(DoubleTy);
989 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000990
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000991 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000992 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
993 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000994 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeib13621d2012-12-18 14:38:23 +0000995
996 if (LangOpts.OpenCL) {
997 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
998 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
999 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
1000 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
1001 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
1002 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
Guy Benyeie6b9d802013-01-20 12:31:11 +00001003
Guy Benyei21f18c42013-02-07 10:55:47 +00001004 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyeie6b9d802013-01-20 12:31:11 +00001005 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Guy Benyeib13621d2012-12-18 14:38:23 +00001006 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001007
1008 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian93a49942012-04-16 21:03:30 +00001009 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1010 SignedCharTy : BoolTy);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001011
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001012 ObjCConstantStringType = QualType();
Fariborz Jahanianf7992132013-01-04 18:45:40 +00001013
1014 ObjCSuperType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00001015
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001016 // void * type
1017 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001018
1019 // nullptr type (C++0x 2.14.7)
1020 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001021
1022 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1023 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingefb40e3f2012-07-01 15:57:25 +00001024
1025 // Builtin type used to help define __builtin_va_list.
1026 VaListTagTy = QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001027}
1028
David Blaikied6471f72011-09-25 23:23:43 +00001029DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00001030 return SourceMgr.getDiagnostics();
1031}
1032
Douglas Gregor63200642010-08-30 16:49:28 +00001033AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1034 AttrVec *&Result = DeclAttrs[D];
1035 if (!Result) {
1036 void *Mem = Allocate(sizeof(AttrVec));
1037 Result = new (Mem) AttrVec;
1038 }
1039
1040 return *Result;
1041}
1042
1043/// \brief Erase the attributes corresponding to the given declaration.
1044void ASTContext::eraseDeclAttrs(const Decl *D) {
1045 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1046 if (Pos != DeclAttrs.end()) {
1047 Pos->second->~AttrVec();
1048 DeclAttrs.erase(Pos);
1049 }
1050}
1051
Larisse Voufoef4579c2013-08-06 01:03:05 +00001052// FIXME: Remove ?
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001053MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +00001054ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001055 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufoef4579c2013-08-06 01:03:05 +00001056 return getTemplateOrSpecializationInfo(Var)
1057 .dyn_cast<MemberSpecializationInfo *>();
1058}
1059
1060ASTContext::TemplateOrSpecializationInfo
1061ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1062 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1063 TemplateOrInstantiation.find(Var);
1064 if (Pos == TemplateOrInstantiation.end())
1065 return TemplateOrSpecializationInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00001066
Douglas Gregor7caa6822009-07-24 20:34:43 +00001067 return Pos->second;
1068}
1069
Mike Stump1eb44332009-09-09 15:08:12 +00001070void
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001071ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +00001072 TemplateSpecializationKind TSK,
1073 SourceLocation PointOfInstantiation) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001074 assert(Inst->isStaticDataMember() && "Not a static data member");
1075 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufoef4579c2013-08-06 01:03:05 +00001076 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1077 Tmpl, TSK, PointOfInstantiation));
1078}
1079
1080void
1081ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1082 TemplateOrSpecializationInfo TSI) {
1083 assert(!TemplateOrInstantiation[Inst] &&
1084 "Already noted what the variable was instantiated from");
1085 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregor7caa6822009-07-24 20:34:43 +00001086}
1087
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001088FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1089 const FunctionDecl *FD){
1090 assert(FD && "Specialization is 0");
1091 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet0d95f0d2011-08-14 14:28:49 +00001092 = ClassScopeSpecializationPattern.find(FD);
1093 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001094 return 0;
1095
1096 return Pos->second;
1097}
1098
1099void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1100 FunctionDecl *Pattern) {
1101 assert(FD && "Specialization is 0");
1102 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet0d95f0d2011-08-14 14:28:49 +00001103 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001104}
1105
John McCall7ba107a2009-11-18 02:36:19 +00001106NamedDecl *
John McCalled976492009-12-04 22:46:56 +00001107ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +00001108 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +00001109 = InstantiatedFromUsingDecl.find(UUD);
1110 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +00001111 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001112
Anders Carlsson0d8df782009-08-29 19:37:28 +00001113 return Pos->second;
1114}
1115
1116void
John McCalled976492009-12-04 22:46:56 +00001117ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1118 assert((isa<UsingDecl>(Pattern) ||
1119 isa<UnresolvedUsingValueDecl>(Pattern) ||
1120 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1121 "pattern decl is not a using decl");
1122 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1123 InstantiatedFromUsingDecl[Inst] = Pattern;
1124}
1125
1126UsingShadowDecl *
1127ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1128 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1129 = InstantiatedFromUsingShadowDecl.find(Inst);
1130 if (Pos == InstantiatedFromUsingShadowDecl.end())
1131 return 0;
1132
1133 return Pos->second;
1134}
1135
1136void
1137ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1138 UsingShadowDecl *Pattern) {
1139 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1140 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00001141}
1142
Anders Carlssond8b285f2009-09-01 04:26:58 +00001143FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1144 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1145 = InstantiatedFromUnnamedFieldDecl.find(Field);
1146 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1147 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001148
Anders Carlssond8b285f2009-09-01 04:26:58 +00001149 return Pos->second;
1150}
1151
1152void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1153 FieldDecl *Tmpl) {
1154 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1155 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1156 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1157 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +00001158
Anders Carlssond8b285f2009-09-01 04:26:58 +00001159 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1160}
1161
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001162ASTContext::overridden_cxx_method_iterator
1163ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1164 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001165 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001166 if (Pos == OverriddenMethods.end())
1167 return 0;
1168
1169 return Pos->second.begin();
1170}
1171
1172ASTContext::overridden_cxx_method_iterator
1173ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1174 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001175 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001176 if (Pos == OverriddenMethods.end())
1177 return 0;
1178
1179 return Pos->second.end();
1180}
1181
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +00001182unsigned
1183ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1184 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001185 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +00001186 if (Pos == OverriddenMethods.end())
1187 return 0;
1188
1189 return Pos->second.size();
1190}
1191
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001192void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1193 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001194 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001195 OverriddenMethods[Method].push_back(Overridden);
1196}
1197
Dmitri Gribenko1e905da2012-11-03 14:24:57 +00001198void ASTContext::getOverriddenMethods(
1199 const NamedDecl *D,
1200 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001201 assert(D);
1202
1203 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis685d1042013-04-17 00:09:03 +00001204 Overridden.append(overridden_methods_begin(CXXMethod),
1205 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001206 return;
1207 }
1208
1209 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1210 if (!Method)
1211 return;
1212
Argyrios Kyrtzidis740ae672012-10-09 18:19:01 +00001213 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1214 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisbc0a2bb2012-10-09 20:08:43 +00001215 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001216}
1217
Douglas Gregore6649772011-12-03 00:30:27 +00001218void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1219 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1220 assert(!Import->isFromASTFile() && "Non-local import declaration");
1221 if (!FirstLocalImport) {
1222 FirstLocalImport = Import;
1223 LastLocalImport = Import;
1224 return;
1225 }
1226
1227 LastLocalImport->NextLocalImport = Import;
1228 LastLocalImport = Import;
1229}
1230
Chris Lattner464175b2007-07-18 17:52:12 +00001231//===----------------------------------------------------------------------===//
1232// Type Sizing and Analysis
1233//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +00001234
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001235/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1236/// scalar floating point type.
1237const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +00001238 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001239 assert(BT && "Not a floating point type!");
1240 switch (BT->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001241 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001242 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001243 case BuiltinType::Float: return Target->getFloatFormat();
1244 case BuiltinType::Double: return Target->getDoubleFormat();
1245 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001246 }
1247}
1248
Rafael Espindola1c56c9d2013-08-08 19:53:46 +00001249CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001250 unsigned Align = Target->getCharWidth();
Eli Friedmandcdafb62009-02-22 02:56:25 +00001251
John McCall4081a5c2010-10-08 18:24:19 +00001252 bool UseAlignAttrOnly = false;
1253 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1254 Align = AlignFromAttr;
Eli Friedmandcdafb62009-02-22 02:56:25 +00001255
John McCall4081a5c2010-10-08 18:24:19 +00001256 // __attribute__((aligned)) can increase or decrease alignment
1257 // *except* on a struct or struct member, where it only increases
1258 // alignment unless 'packed' is also specified.
1259 //
Peter Collingbourne82d0b0a2011-09-29 18:04:28 +00001260 // It is an error for alignas to decrease alignment, so we can
John McCall4081a5c2010-10-08 18:24:19 +00001261 // ignore that possibility; Sema should diagnose it.
1262 if (isa<FieldDecl>(D)) {
1263 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1264 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1265 } else {
1266 UseAlignAttrOnly = true;
1267 }
1268 }
Fariborz Jahanian78a7d7d2011-05-05 21:19:14 +00001269 else if (isa<FieldDecl>(D))
1270 UseAlignAttrOnly =
1271 D->hasAttr<PackedAttr>() ||
1272 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall4081a5c2010-10-08 18:24:19 +00001273
John McCallba4f5d52011-01-20 07:57:12 +00001274 // If we're using the align attribute only, just ignore everything
1275 // else about the declaration and its type.
John McCall4081a5c2010-10-08 18:24:19 +00001276 if (UseAlignAttrOnly) {
John McCallba4f5d52011-01-20 07:57:12 +00001277 // do nothing
1278
John McCall4081a5c2010-10-08 18:24:19 +00001279 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00001280 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001281 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Rafael Espindola1c56c9d2013-08-08 19:53:46 +00001282 if (ForAlignof)
Sebastian Redl5d484e82009-11-23 17:18:46 +00001283 T = RT->getPointeeType();
1284 else
1285 T = getPointerType(RT->getPointeeType());
1286 }
1287 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall3b657512011-01-19 10:06:00 +00001288 // Adjust alignments of declarations with array type by the
1289 // large-array alignment on the target.
Rafael Espindolab82f77f2013-08-07 18:08:19 +00001290 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola1c56c9d2013-08-08 19:53:46 +00001291 unsigned MinWidth = Target->getLargeArrayMinWidth();
1292 if (!ForAlignof && MinWidth) {
Rafael Espindolab82f77f2013-08-07 18:08:19 +00001293 if (isa<VariableArrayType>(arrayType))
1294 Align = std::max(Align, Target->getLargeArrayAlign());
1295 else if (isa<ConstantArrayType>(arrayType) &&
1296 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1297 Align = std::max(Align, Target->getLargeArrayAlign());
1298 }
Eli Friedmandcdafb62009-02-22 02:56:25 +00001299
John McCall3b657512011-01-19 10:06:00 +00001300 // Walk through any array types while we're at it.
1301 T = getBaseElementType(arrayType);
1302 }
Chad Rosier9f1210c2011-07-26 07:03:04 +00001303 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Ulrich Weigand6b203512013-05-06 16:23:57 +00001304 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1305 if (VD->hasGlobalStorage())
1306 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1307 }
Eli Friedmandcdafb62009-02-22 02:56:25 +00001308 }
John McCallba4f5d52011-01-20 07:57:12 +00001309
1310 // Fields can be subject to extra alignment constraints, like if
1311 // the field is packed, the struct is packed, or the struct has a
1312 // a max-field-alignment constraint (#pragma pack). So calculate
1313 // the actual alignment of the field within the struct, and then
1314 // (as we're expected to) constrain that by the alignment of the type.
Matt Beaumont-Gay147fab92013-06-25 22:19:15 +00001315 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1316 const RecordDecl *Parent = Field->getParent();
1317 // We can only produce a sensible answer if the record is valid.
1318 if (!Parent->isInvalidDecl()) {
1319 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCallba4f5d52011-01-20 07:57:12 +00001320
Matt Beaumont-Gay147fab92013-06-25 22:19:15 +00001321 // Start with the record's overall alignment.
1322 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCallba4f5d52011-01-20 07:57:12 +00001323
Matt Beaumont-Gay147fab92013-06-25 22:19:15 +00001324 // Use the GCD of that and the offset within the record.
1325 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1326 if (Offset > 0) {
1327 // Alignment is always a power of 2, so the GCD will be a power of 2,
1328 // which means we get to do this crazy thing instead of Euclid's.
1329 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1330 if (LowBitOfOffset < FieldAlign)
1331 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1332 }
1333
1334 Align = std::min(Align, FieldAlign);
John McCallba4f5d52011-01-20 07:57:12 +00001335 }
Charles Davis05f62472010-02-23 04:52:00 +00001336 }
Chris Lattneraf707ab2009-01-24 21:53:27 +00001337 }
Eli Friedmandcdafb62009-02-22 02:56:25 +00001338
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001339 return toCharUnitsFromBits(Align);
Chris Lattneraf707ab2009-01-24 21:53:27 +00001340}
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001341
John McCall929bbfb2012-08-21 04:10:00 +00001342// getTypeInfoDataSizeInChars - Return the size of a type, in
1343// chars. If the type is a record, its data size is returned. This is
1344// the size of the memcpy that's performed when assigning this type
1345// using a trivial copy/move assignment operator.
1346std::pair<CharUnits, CharUnits>
1347ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1348 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1349
1350 // In C++, objects can sometimes be allocated into the tail padding
1351 // of a base-class subobject. We decide whether that's possible
1352 // during class layout, so here we can just trust the layout results.
1353 if (getLangOpts().CPlusPlus) {
1354 if (const RecordType *RT = T->getAs<RecordType>()) {
1355 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1356 sizeAndAlign.first = layout.getDataSize();
1357 }
1358 }
1359
1360 return sizeAndAlign;
1361}
1362
Richard Trieu910f17e2013-05-14 21:59:17 +00001363/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1364/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1365std::pair<CharUnits, CharUnits>
1366static getConstantArrayInfoInChars(const ASTContext &Context,
1367 const ConstantArrayType *CAT) {
1368 std::pair<CharUnits, CharUnits> EltInfo =
1369 Context.getTypeInfoInChars(CAT->getElementType());
1370 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieu1069b732013-05-14 23:41:50 +00001371 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1372 (uint64_t)(-1)/Size) &&
Richard Trieu910f17e2013-05-14 21:59:17 +00001373 "Overflow in array type char size evaluation");
1374 uint64_t Width = EltInfo.first.getQuantity() * Size;
1375 unsigned Align = EltInfo.second.getQuantity();
1376 Width = llvm::RoundUpToAlignment(Width, Align);
1377 return std::make_pair(CharUnits::fromQuantity(Width),
1378 CharUnits::fromQuantity(Align));
1379}
1380
John McCallea1471e2010-05-20 01:18:31 +00001381std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +00001382ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu910f17e2013-05-14 21:59:17 +00001383 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1384 return getConstantArrayInfoInChars(*this, CAT);
John McCallea1471e2010-05-20 01:18:31 +00001385 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001386 return std::make_pair(toCharUnitsFromBits(Info.first),
1387 toCharUnitsFromBits(Info.second));
John McCallea1471e2010-05-20 01:18:31 +00001388}
1389
1390std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +00001391ASTContext::getTypeInfoInChars(QualType T) const {
John McCallea1471e2010-05-20 01:18:31 +00001392 return getTypeInfoInChars(T.getTypePtr());
1393}
1394
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001395std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1396 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1397 if (it != MemoizedTypeInfo.end())
1398 return it->second;
1399
1400 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1401 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1402 return Info;
1403}
1404
1405/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1406/// method does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +00001407///
1408/// FIXME: Pointers into different addr spaces could have different sizes and
1409/// alignment requirements: getPointerInfo should take an AddrSpace, this
1410/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +00001411std::pair<uint64_t, unsigned>
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001412ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5e301002009-02-27 18:32:39 +00001413 uint64_t Width=0;
1414 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +00001415 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +00001416#define TYPE(Class, Base)
1417#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +00001418#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +00001419#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikiedc809782013-07-13 21:08:03 +00001420#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1421 case Type::Class: \
1422 assert(!T->isDependentType() && "should not see dependent types here"); \
1423 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregor72564e72009-02-26 23:50:07 +00001424#include "clang/AST/TypeNodes.def"
John McCalld3d49bb2011-06-28 16:49:23 +00001425 llvm_unreachable("Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +00001426
Chris Lattner692233e2007-07-13 22:27:08 +00001427 case Type::FunctionNoProto:
1428 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +00001429 // GCC extension: alignof(function) = 32 bits
1430 Width = 0;
1431 Align = 32;
1432 break;
1433
Douglas Gregor72564e72009-02-26 23:50:07 +00001434 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +00001435 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +00001436 Width = 0;
1437 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1438 break;
1439
Steve Narofffb22d962007-08-30 01:06:46 +00001440 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001441 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001442
Chris Lattner98be4942008-03-05 18:54:05 +00001443 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarafea966a2011-12-13 11:23:52 +00001444 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001445 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1446 "Overflow in array type bit size evaluation");
Abramo Bagnarafea966a2011-12-13 11:23:52 +00001447 Width = EltInfo.first*Size;
Chris Lattner030d8842007-07-19 22:06:24 +00001448 Align = EltInfo.second;
Argyrios Kyrtzidiscd88b412011-04-26 21:05:39 +00001449 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattner030d8842007-07-19 22:06:24 +00001450 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +00001451 }
Nate Begeman213541a2008-04-18 23:10:10 +00001452 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +00001453 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +00001454 const VectorType *VT = cast<VectorType>(T);
1455 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1456 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +00001457 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +00001458 // If the alignment is not a power of 2, round up to the next power of 2.
1459 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +00001460 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +00001461 Align = llvm::NextPowerOf2(Align);
1462 Width = llvm::RoundUpToAlignment(Width, Align);
1463 }
Chad Rosierf9e9af72012-07-13 23:57:43 +00001464 // Adjust the alignment based on the target max.
1465 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1466 if (TargetVectorAlign && TargetVectorAlign < Align)
1467 Align = TargetVectorAlign;
Chris Lattner030d8842007-07-19 22:06:24 +00001468 break;
1469 }
Chris Lattner5d2a6302007-07-18 18:26:58 +00001470
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001471 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +00001472 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001473 default: llvm_unreachable("Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +00001474 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +00001475 // GCC extension: alignof(void) = 8 bits.
1476 Width = 0;
1477 Align = 8;
1478 break;
1479
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001480 case BuiltinType::Bool:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001481 Width = Target->getBoolWidth();
1482 Align = Target->getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001483 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001484 case BuiltinType::Char_S:
1485 case BuiltinType::Char_U:
1486 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001487 case BuiltinType::SChar:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001488 Width = Target->getCharWidth();
1489 Align = Target->getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001490 break;
Chris Lattner3f59c972010-12-25 23:25:43 +00001491 case BuiltinType::WChar_S:
1492 case BuiltinType::WChar_U:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001493 Width = Target->getWCharWidth();
1494 Align = Target->getWCharAlign();
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00001495 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001496 case BuiltinType::Char16:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001497 Width = Target->getChar16Width();
1498 Align = Target->getChar16Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001499 break;
1500 case BuiltinType::Char32:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001501 Width = Target->getChar32Width();
1502 Align = Target->getChar32Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001503 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001504 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001505 case BuiltinType::Short:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001506 Width = Target->getShortWidth();
1507 Align = Target->getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001508 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001509 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001510 case BuiltinType::Int:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001511 Width = Target->getIntWidth();
1512 Align = Target->getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001513 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001514 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001515 case BuiltinType::Long:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001516 Width = Target->getLongWidth();
1517 Align = Target->getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001518 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001519 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001520 case BuiltinType::LongLong:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001521 Width = Target->getLongLongWidth();
1522 Align = Target->getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001523 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +00001524 case BuiltinType::Int128:
1525 case BuiltinType::UInt128:
1526 Width = 128;
1527 Align = 128; // int128_t is 128-bit aligned on all targets.
1528 break;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001529 case BuiltinType::Half:
1530 Width = Target->getHalfWidth();
1531 Align = Target->getHalfAlign();
1532 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001533 case BuiltinType::Float:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001534 Width = Target->getFloatWidth();
1535 Align = Target->getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001536 break;
1537 case BuiltinType::Double:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001538 Width = Target->getDoubleWidth();
1539 Align = Target->getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001540 break;
1541 case BuiltinType::LongDouble:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001542 Width = Target->getLongDoubleWidth();
1543 Align = Target->getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001544 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001545 case BuiltinType::NullPtr:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001546 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1547 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +00001548 break;
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +00001549 case BuiltinType::ObjCId:
1550 case BuiltinType::ObjCClass:
1551 case BuiltinType::ObjCSel:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001552 Width = Target->getPointerWidth(0);
1553 Align = Target->getPointerAlign(0);
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +00001554 break;
Guy Benyei21f18c42013-02-07 10:55:47 +00001555 case BuiltinType::OCLSampler:
1556 // Samplers are modeled as integers.
1557 Width = Target->getIntWidth();
1558 Align = Target->getIntAlign();
1559 break;
Guy Benyeie6b9d802013-01-20 12:31:11 +00001560 case BuiltinType::OCLEvent:
Guy Benyeib13621d2012-12-18 14:38:23 +00001561 case BuiltinType::OCLImage1d:
1562 case BuiltinType::OCLImage1dArray:
1563 case BuiltinType::OCLImage1dBuffer:
1564 case BuiltinType::OCLImage2d:
1565 case BuiltinType::OCLImage2dArray:
1566 case BuiltinType::OCLImage3d:
1567 // Currently these types are pointers to opaque types.
1568 Width = Target->getPointerWidth(0);
1569 Align = Target->getPointerAlign(0);
1570 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001571 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +00001572 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001573 case Type::ObjCObjectPointer:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001574 Width = Target->getPointerWidth(0);
1575 Align = Target->getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001576 break;
Steve Naroff485eeff2008-09-24 15:05:44 +00001577 case Type::BlockPointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001578 unsigned AS = getTargetAddressSpace(
1579 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001580 Width = Target->getPointerWidth(AS);
1581 Align = Target->getPointerAlign(AS);
Steve Naroff485eeff2008-09-24 15:05:44 +00001582 break;
1583 }
Sebastian Redl5d484e82009-11-23 17:18:46 +00001584 case Type::LValueReference:
1585 case Type::RValueReference: {
1586 // alignof and sizeof should never enter this code path here, so we go
1587 // the pointer route.
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001588 unsigned AS = getTargetAddressSpace(
1589 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001590 Width = Target->getPointerWidth(AS);
1591 Align = Target->getPointerAlign(AS);
Sebastian Redl5d484e82009-11-23 17:18:46 +00001592 break;
1593 }
Chris Lattnerf72a4432008-03-08 08:34:58 +00001594 case Type::Pointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001595 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001596 Width = Target->getPointerWidth(AS);
1597 Align = Target->getPointerAlign(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +00001598 break;
1599 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00001600 case Type::MemberPointer: {
Charles Davis071cc7d2010-08-16 03:33:14 +00001601 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Reid Kleckner84e9ab42013-03-28 20:02:56 +00001602 llvm::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson1cca74e2009-05-17 02:06:04 +00001603 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +00001604 }
Chris Lattner5d2a6302007-07-18 18:26:58 +00001605 case Type::Complex: {
1606 // Complex types have the same alignment as their elements, but twice the
1607 // size.
Mike Stump1eb44332009-09-09 15:08:12 +00001608 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +00001609 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001610 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +00001611 Align = EltInfo.second;
1612 break;
1613 }
John McCallc12c5bb2010-05-15 11:32:37 +00001614 case Type::ObjCObject:
1615 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner12df2462013-06-24 17:51:48 +00001616 case Type::Decayed:
1617 return getTypeInfo(cast<DecayedType>(T)->getDecayedType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +00001618 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001619 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +00001620 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001621 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001622 Align = toBits(Layout.getAlignment());
Devang Patel44a3dde2008-06-04 21:54:36 +00001623 break;
1624 }
Douglas Gregor72564e72009-02-26 23:50:07 +00001625 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00001626 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001627 const TagType *TT = cast<TagType>(T);
1628
1629 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor22ce41d2011-04-20 17:29:44 +00001630 Width = 8;
1631 Align = 8;
Chris Lattner8389eab2008-08-09 21:35:13 +00001632 break;
1633 }
Mike Stump1eb44332009-09-09 15:08:12 +00001634
Daniel Dunbar1d751182008-11-08 05:48:37 +00001635 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +00001636 return getTypeInfo(ET->getDecl()->getIntegerType());
1637
Daniel Dunbar1d751182008-11-08 05:48:37 +00001638 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +00001639 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001640 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001641 Align = toBits(Layout.getAlignment());
Chris Lattnerdc0d73e2007-07-23 22:46:22 +00001642 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001643 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001644
Chris Lattner9fcfe922009-10-22 05:17:15 +00001645 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +00001646 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1647 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +00001648
Richard Smith34b41d92011-02-20 03:19:35 +00001649 case Type::Auto: {
1650 const AutoType *A = cast<AutoType>(T);
Richard Smithdc7a4f52013-04-30 13:56:41 +00001651 assert(!A->getDeducedType().isNull() &&
1652 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gaydc856af2011-02-22 20:00:16 +00001653 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith34b41d92011-02-20 03:19:35 +00001654 }
1655
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001656 case Type::Paren:
1657 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1658
Douglas Gregor18857642009-04-30 17:32:17 +00001659 case Type::Typedef: {
Richard Smith162e1c12011-04-15 14:24:37 +00001660 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregordf1367a2010-08-27 00:11:28 +00001661 std::pair<uint64_t, unsigned> Info
1662 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattnerc1de52d2011-02-19 22:55:41 +00001663 // If the typedef has an aligned attribute on it, it overrides any computed
1664 // alignment we have. This violates the GCC documentation (which says that
1665 // attribute(aligned) can only round up) but matches its implementation.
1666 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1667 Align = AttrAlign;
1668 else
1669 Align = Info.second;
Douglas Gregordf1367a2010-08-27 00:11:28 +00001670 Width = Info.first;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001671 break;
Chris Lattner71763312008-04-06 22:05:18 +00001672 }
Douglas Gregor18857642009-04-30 17:32:17 +00001673
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001674 case Type::Elaborated:
1675 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +00001676
John McCall9d156a72011-01-06 01:58:22 +00001677 case Type::Attributed:
1678 return getTypeInfo(
1679 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1680
Eli Friedmanb001de72011-10-06 23:00:33 +00001681 case Type::Atomic: {
John McCall9eda3ab2013-03-07 21:37:17 +00001682 // Start with the base type information.
Eli Friedman2be46072011-10-14 20:59:01 +00001683 std::pair<uint64_t, unsigned> Info
1684 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1685 Width = Info.first;
1686 Align = Info.second;
John McCall9eda3ab2013-03-07 21:37:17 +00001687
1688 // If the size of the type doesn't exceed the platform's max
1689 // atomic promotion width, make the size and alignment more
1690 // favorable to atomic operations:
1691 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1692 // Round the size up to a power of 2.
1693 if (!llvm::isPowerOf2_64(Width))
1694 Width = llvm::NextPowerOf2(Width);
1695
1696 // Set the alignment equal to the size.
Eli Friedman2be46072011-10-14 20:59:01 +00001697 Align = static_cast<unsigned>(Width);
1698 }
Eli Friedmanb001de72011-10-06 23:00:33 +00001699 }
1700
Douglas Gregor18857642009-04-30 17:32:17 +00001701 }
Mike Stump1eb44332009-09-09 15:08:12 +00001702
Eli Friedman2be46072011-10-14 20:59:01 +00001703 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001704 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +00001705}
1706
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001707/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1708CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1709 return CharUnits::fromQuantity(BitSize / getCharWidth());
1710}
1711
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001712/// toBits - Convert a size in characters to a size in characters.
1713int64_t ASTContext::toBits(CharUnits CharSize) const {
1714 return CharSize.getQuantity() * getCharWidth();
1715}
1716
Ken Dyckbdc601b2009-12-22 14:23:30 +00001717/// getTypeSizeInChars - Return the size of the specified type, in characters.
1718/// This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001719CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu910f17e2013-05-14 21:59:17 +00001720 return getTypeInfoInChars(T).first;
Ken Dyckbdc601b2009-12-22 14:23:30 +00001721}
Jay Foad4ba2a172011-01-12 09:06:06 +00001722CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu910f17e2013-05-14 21:59:17 +00001723 return getTypeInfoInChars(T).first;
Ken Dyckbdc601b2009-12-22 14:23:30 +00001724}
1725
Ken Dyck16e20cc2010-01-26 17:25:18 +00001726/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +00001727/// characters. This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001728CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001729 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001730}
Jay Foad4ba2a172011-01-12 09:06:06 +00001731CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001732 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001733}
1734
Chris Lattner34ebde42009-01-27 18:08:34 +00001735/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1736/// type for the current target in bits. This can be different than the ABI
1737/// alignment in cases where it is beneficial for performance to overalign
1738/// a data type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001739unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattner34ebde42009-01-27 18:08:34 +00001740 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +00001741
1742 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +00001743 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +00001744 T = CT->getElementType().getTypePtr();
1745 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosiercde7a1d2012-03-21 20:20:47 +00001746 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1747 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman1eed6022009-05-25 21:27:19 +00001748 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1749
Chris Lattner34ebde42009-01-27 18:08:34 +00001750 return ABIAlign;
1751}
1752
Ulrich Weigand6b203512013-05-06 16:23:57 +00001753/// getAlignOfGlobalVar - Return the alignment in bits that should be given
1754/// to a global variable of the specified type.
1755unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1756 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1757}
1758
1759/// getAlignOfGlobalVarInChars - Return the alignment in characters that
1760/// should be given to a global variable of the specified type.
1761CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1762 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1763}
1764
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001765/// DeepCollectObjCIvars -
1766/// This routine first collects all declared, but not synthesized, ivars in
1767/// super class and then collects all ivars, including those synthesized for
1768/// current class. This routine is used for implementation of current class
1769/// when all ivars, declared and synthesized are known.
Fariborz Jahanian98200742009-05-12 18:14:29 +00001770///
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001771void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1772 bool leafClass,
Jordy Rosedb8264e2011-07-22 02:08:32 +00001773 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001774 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1775 DeepCollectObjCIvars(SuperClass, false, Ivars);
1776 if (!leafClass) {
1777 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1778 E = OI->ivar_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001779 Ivars.push_back(*I);
Chad Rosier30601782011-08-17 23:08:45 +00001780 } else {
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001781 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosedb8264e2011-07-22 02:08:32 +00001782 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001783 Iv= Iv->getNextIvar())
1784 Ivars.push_back(Iv);
1785 }
Fariborz Jahanian98200742009-05-12 18:14:29 +00001786}
1787
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001788/// CollectInheritedProtocols - Collect all protocols in current class and
1789/// those inherited by it.
1790void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001791 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001792 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001793 // We can use protocol_iterator here instead of
1794 // all_referenced_protocol_iterator since we are walking all categories.
1795 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1796 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001797 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001798 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001799 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001800 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001801 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001802 CollectInheritedProtocols(*P, Protocols);
1803 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001804 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001805
1806 // Categories of this Interface.
Douglas Gregord3297242013-01-16 23:00:23 +00001807 for (ObjCInterfaceDecl::visible_categories_iterator
1808 Cat = OI->visible_categories_begin(),
1809 CatEnd = OI->visible_categories_end();
1810 Cat != CatEnd; ++Cat) {
1811 CollectInheritedProtocols(*Cat, Protocols);
1812 }
1813
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001814 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1815 while (SD) {
1816 CollectInheritedProtocols(SD, Protocols);
1817 SD = SD->getSuperClass();
1818 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001819 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001820 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001821 PE = OC->protocol_end(); P != PE; ++P) {
1822 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001823 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001824 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1825 PE = Proto->protocol_end(); P != PE; ++P)
1826 CollectInheritedProtocols(*P, Protocols);
1827 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001828 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001829 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1830 PE = OP->protocol_end(); P != PE; ++P) {
1831 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001832 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001833 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1834 PE = Proto->protocol_end(); P != PE; ++P)
1835 CollectInheritedProtocols(*P, Protocols);
1836 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001837 }
1838}
1839
Jay Foad4ba2a172011-01-12 09:06:06 +00001840unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001841 unsigned count = 0;
1842 // Count ivars declared in class extension.
Douglas Gregord3297242013-01-16 23:00:23 +00001843 for (ObjCInterfaceDecl::known_extensions_iterator
1844 Ext = OI->known_extensions_begin(),
1845 ExtEnd = OI->known_extensions_end();
1846 Ext != ExtEnd; ++Ext) {
1847 count += Ext->ivar_size();
1848 }
1849
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001850 // Count ivar defined in this class's implementation. This
1851 // includes synthesized ivars.
1852 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001853 count += ImplDecl->ivar_size();
1854
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001855 return count;
1856}
1857
Argyrios Kyrtzidis8deabc12012-02-03 05:58:16 +00001858bool ASTContext::isSentinelNullExpr(const Expr *E) {
1859 if (!E)
1860 return false;
1861
1862 // nullptr_t is always treated as null.
1863 if (E->getType()->isNullPtrType()) return true;
1864
1865 if (E->getType()->isAnyPointerType() &&
1866 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1867 Expr::NPC_ValueDependentIsNull))
1868 return true;
1869
1870 // Unfortunately, __null has type 'int'.
1871 if (isa<GNUNullExpr>(E)) return true;
1872
1873 return false;
1874}
1875
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +00001876/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1877ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1878 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1879 I = ObjCImpls.find(D);
1880 if (I != ObjCImpls.end())
1881 return cast<ObjCImplementationDecl>(I->second);
1882 return 0;
1883}
1884/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1885ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1886 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1887 I = ObjCImpls.find(D);
1888 if (I != ObjCImpls.end())
1889 return cast<ObjCCategoryImplDecl>(I->second);
1890 return 0;
1891}
1892
1893/// \brief Set the implementation of ObjCInterfaceDecl.
1894void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1895 ObjCImplementationDecl *ImplD) {
1896 assert(IFaceD && ImplD && "Passed null params");
1897 ObjCImpls[IFaceD] = ImplD;
1898}
1899/// \brief Set the implementation of ObjCCategoryDecl.
1900void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1901 ObjCCategoryImplDecl *ImplD) {
1902 assert(CatD && ImplD && "Passed null params");
1903 ObjCImpls[CatD] = ImplD;
1904}
1905
Dmitri Gribenkob35cc2d2013-02-03 13:23:21 +00001906const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
1907 const NamedDecl *ND) const {
1908 if (const ObjCInterfaceDecl *ID =
1909 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001910 return ID;
Dmitri Gribenkob35cc2d2013-02-03 13:23:21 +00001911 if (const ObjCCategoryDecl *CD =
1912 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001913 return CD->getClassInterface();
Dmitri Gribenkob35cc2d2013-02-03 13:23:21 +00001914 if (const ObjCImplDecl *IMD =
1915 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001916 return IMD->getClassInterface();
1917
1918 return 0;
1919}
1920
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001921/// \brief Get the copy initialization expression of VarDecl,or NULL if
1922/// none exists.
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001923Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001924 assert(VD && "Passed null params");
1925 assert(VD->hasAttr<BlocksAttr>() &&
1926 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001927 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001928 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001929 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1930}
1931
1932/// \brief Set the copy inialization expression of a block var decl.
1933void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1934 assert(VD && Init && "Passed null params");
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001935 assert(VD->hasAttr<BlocksAttr>() &&
1936 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001937 BlockVarCopyInits[VD] = Init;
1938}
1939
John McCalla93c9342009-12-07 02:54:59 +00001940TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001941 unsigned DataSize) const {
John McCall109de5e2009-10-21 00:23:54 +00001942 if (!DataSize)
1943 DataSize = TypeLoc::getFullDataSizeForType(T);
1944 else
1945 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001946 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001947
John McCalla93c9342009-12-07 02:54:59 +00001948 TypeSourceInfo *TInfo =
1949 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1950 new (TInfo) TypeSourceInfo(T);
1951 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001952}
1953
John McCalla93c9342009-12-07 02:54:59 +00001954TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001955 SourceLocation L) const {
John McCalla93c9342009-12-07 02:54:59 +00001956 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregorc21c7e92011-01-25 19:13:18 +00001957 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCalla4eb74d2009-10-23 21:14:09 +00001958 return DI;
1959}
1960
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001961const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001962ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001963 return getObjCLayout(D, 0);
1964}
1965
1966const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001967ASTContext::getASTObjCImplementationLayout(
1968 const ObjCImplementationDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001969 return getObjCLayout(D->getClassInterface(), D);
1970}
1971
Chris Lattnera7674d82007-07-13 22:13:22 +00001972//===----------------------------------------------------------------------===//
1973// Type creation/memoization methods
1974//===----------------------------------------------------------------------===//
1975
Jay Foad4ba2a172011-01-12 09:06:06 +00001976QualType
John McCall3b657512011-01-19 10:06:00 +00001977ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1978 unsigned fastQuals = quals.getFastQualifiers();
1979 quals.removeFastQualifiers();
John McCall0953e762009-09-24 19:53:00 +00001980
1981 // Check if we've already instantiated this type.
1982 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001983 ExtQuals::Profile(ID, baseType, quals);
1984 void *insertPos = 0;
1985 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1986 assert(eq->getQualifiers() == quals);
1987 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001988 }
1989
John McCall3b657512011-01-19 10:06:00 +00001990 // If the base type is not canonical, make the appropriate canonical type.
1991 QualType canon;
1992 if (!baseType->isCanonicalUnqualified()) {
1993 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall200fa532012-02-08 00:46:36 +00001994 canonSplit.Quals.addConsistentQualifiers(quals);
1995 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00001996
1997 // Re-find the insert position.
1998 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1999 }
2000
2001 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2002 ExtQualNodes.InsertNode(eq, insertPos);
2003 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00002004}
2005
Jay Foad4ba2a172011-01-12 09:06:06 +00002006QualType
2007ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002008 QualType CanT = getCanonicalType(T);
2009 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00002010 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00002011
John McCall0953e762009-09-24 19:53:00 +00002012 // If we are composing extended qualifiers together, merge together
2013 // into one ExtQuals node.
2014 QualifierCollector Quals;
2015 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002016
John McCall0953e762009-09-24 19:53:00 +00002017 // If this type already has an address space specified, it cannot get
2018 // another one.
2019 assert(!Quals.hasAddressSpace() &&
2020 "Type cannot be in multiple addr spaces!");
2021 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00002022
John McCall0953e762009-09-24 19:53:00 +00002023 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00002024}
2025
Chris Lattnerb7d25532009-02-18 22:53:11 +00002026QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00002027 Qualifiers::GC GCAttr) const {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00002028 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00002029 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00002030 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00002031
John McCall7f040a92010-12-24 02:08:15 +00002032 if (const PointerType *ptr = T->getAs<PointerType>()) {
2033 QualType Pointee = ptr->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00002034 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00002035 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2036 return getPointerType(ResultType);
2037 }
2038 }
Mike Stump1eb44332009-09-09 15:08:12 +00002039
John McCall0953e762009-09-24 19:53:00 +00002040 // If we are composing extended qualifiers together, merge together
2041 // into one ExtQuals node.
2042 QualifierCollector Quals;
2043 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002044
John McCall0953e762009-09-24 19:53:00 +00002045 // If this type already has an ObjCGC specified, it cannot get
2046 // another one.
2047 assert(!Quals.hasObjCGCAttr() &&
2048 "Type cannot have multiple ObjCGCs!");
2049 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00002050
John McCall0953e762009-09-24 19:53:00 +00002051 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00002052}
Chris Lattnera7674d82007-07-13 22:13:22 +00002053
John McCalle6a365d2010-12-19 02:44:49 +00002054const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2055 FunctionType::ExtInfo Info) {
2056 if (T->getExtInfo() == Info)
2057 return T;
2058
2059 QualType Result;
2060 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
2061 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
2062 } else {
2063 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2064 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2065 EPI.ExtInfo = Info;
Reid Kleckner0567a792013-06-10 20:51:09 +00002066 Result = getFunctionType(FPT->getResultType(), FPT->getArgTypes(), EPI);
John McCalle6a365d2010-12-19 02:44:49 +00002067 }
2068
2069 return cast<FunctionType>(Result.getTypePtr());
2070}
2071
Richard Smith60e141e2013-05-04 07:00:32 +00002072void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2073 QualType ResultType) {
Richard Smith9dadfab2013-05-11 05:45:24 +00002074 FD = FD->getMostRecentDecl();
2075 while (true) {
Richard Smith60e141e2013-05-04 07:00:32 +00002076 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2077 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2078 FD->setType(getFunctionType(ResultType, FPT->getArgTypes(), EPI));
Richard Smith9dadfab2013-05-11 05:45:24 +00002079 if (FunctionDecl *Next = FD->getPreviousDecl())
2080 FD = Next;
2081 else
2082 break;
Richard Smith60e141e2013-05-04 07:00:32 +00002083 }
Richard Smith9dadfab2013-05-11 05:45:24 +00002084 if (ASTMutationListener *L = getASTMutationListener())
2085 L->DeducedReturnType(FD, ResultType);
Richard Smith60e141e2013-05-04 07:00:32 +00002086}
2087
Reid Spencer5f016e22007-07-11 17:01:13 +00002088/// getComplexType - Return the uniqued reference to the type for a complex
2089/// number with the specified element type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002090QualType ASTContext::getComplexType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002091 // Unique pointers, to guarantee there is only one pointer of a particular
2092 // structure.
2093 llvm::FoldingSetNodeID ID;
2094 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00002095
Reid Spencer5f016e22007-07-11 17:01:13 +00002096 void *InsertPos = 0;
2097 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2098 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002099
Reid Spencer5f016e22007-07-11 17:01:13 +00002100 // If the pointee type isn't canonical, this won't be a canonical type either,
2101 // so fill in the canonical type field.
2102 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002103 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002104 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00002105
Reid Spencer5f016e22007-07-11 17:01:13 +00002106 // Get the new insert position for the node we care about.
2107 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002108 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002109 }
John McCall6b304a02009-09-24 23:30:46 +00002110 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00002111 Types.push_back(New);
2112 ComplexTypes.InsertNode(New, InsertPos);
2113 return QualType(New, 0);
2114}
2115
Reid Spencer5f016e22007-07-11 17:01:13 +00002116/// getPointerType - Return the uniqued reference to the type for a pointer to
2117/// the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002118QualType ASTContext::getPointerType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002119 // Unique pointers, to guarantee there is only one pointer of a particular
2120 // structure.
2121 llvm::FoldingSetNodeID ID;
2122 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00002123
Reid Spencer5f016e22007-07-11 17:01:13 +00002124 void *InsertPos = 0;
2125 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2126 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002127
Reid Spencer5f016e22007-07-11 17:01:13 +00002128 // If the pointee type isn't canonical, this won't be a canonical type either,
2129 // so fill in the canonical type field.
2130 QualType Canonical;
Bob Wilsonc90cc932013-03-15 17:12:43 +00002131 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002132 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00002133
Bob Wilsonc90cc932013-03-15 17:12:43 +00002134 // Get the new insert position for the node we care about.
2135 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2136 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2137 }
John McCall6b304a02009-09-24 23:30:46 +00002138 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00002139 Types.push_back(New);
2140 PointerTypes.InsertNode(New, InsertPos);
2141 return QualType(New, 0);
2142}
2143
Reid Kleckner12df2462013-06-24 17:51:48 +00002144QualType ASTContext::getDecayedType(QualType T) const {
2145 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2146
2147 llvm::FoldingSetNodeID ID;
2148 DecayedType::Profile(ID, T);
2149 void *InsertPos = 0;
2150 if (DecayedType *DT = DecayedTypes.FindNodeOrInsertPos(ID, InsertPos))
2151 return QualType(DT, 0);
2152
2153 QualType Decayed;
2154
2155 // C99 6.7.5.3p7:
2156 // A declaration of a parameter as "array of type" shall be
2157 // adjusted to "qualified pointer to type", where the type
2158 // qualifiers (if any) are those specified within the [ and ] of
2159 // the array type derivation.
2160 if (T->isArrayType())
2161 Decayed = getArrayDecayedType(T);
2162
2163 // C99 6.7.5.3p8:
2164 // A declaration of a parameter as "function returning type"
2165 // shall be adjusted to "pointer to function returning type", as
2166 // in 6.3.2.1.
2167 if (T->isFunctionType())
2168 Decayed = getPointerType(T);
2169
2170 QualType Canonical = getCanonicalType(Decayed);
2171
2172 // Get the new insert position for the node we care about.
2173 DecayedType *NewIP = DecayedTypes.FindNodeOrInsertPos(ID, InsertPos);
2174 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2175
2176 DecayedType *New =
2177 new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2178 Types.push_back(New);
2179 DecayedTypes.InsertNode(New, InsertPos);
2180 return QualType(New, 0);
2181}
2182
Mike Stump1eb44332009-09-09 15:08:12 +00002183/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00002184/// a pointer to the specified block.
Jay Foad4ba2a172011-01-12 09:06:06 +00002185QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff296e8d52008-08-28 19:20:44 +00002186 assert(T->isFunctionType() && "block of function types only");
2187 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00002188 // structure.
2189 llvm::FoldingSetNodeID ID;
2190 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00002191
Steve Naroff5618bd42008-08-27 16:04:49 +00002192 void *InsertPos = 0;
2193 if (BlockPointerType *PT =
2194 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2195 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002196
2197 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00002198 // type either so fill in the canonical type field.
2199 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002200 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00002201 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00002202
Steve Naroff5618bd42008-08-27 16:04:49 +00002203 // Get the new insert position for the node we care about.
2204 BlockPointerType *NewIP =
2205 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002206 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00002207 }
John McCall6b304a02009-09-24 23:30:46 +00002208 BlockPointerType *New
2209 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00002210 Types.push_back(New);
2211 BlockPointerTypes.InsertNode(New, InsertPos);
2212 return QualType(New, 0);
2213}
2214
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002215/// getLValueReferenceType - Return the uniqued reference to the type for an
2216/// lvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002217QualType
2218ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor9625e442011-05-21 22:16:50 +00002219 assert(getCanonicalType(T) != OverloadTy &&
2220 "Unresolved overloaded function type");
2221
Reid Spencer5f016e22007-07-11 17:01:13 +00002222 // Unique pointers, to guarantee there is only one pointer of a particular
2223 // structure.
2224 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00002225 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00002226
2227 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002228 if (LValueReferenceType *RT =
2229 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002230 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002231
John McCall54e14c42009-10-22 22:37:11 +00002232 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2233
Reid Spencer5f016e22007-07-11 17:01:13 +00002234 // If the referencee type isn't canonical, this won't be a canonical type
2235 // either, so fill in the canonical type field.
2236 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00002237 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2238 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2239 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002240
Reid Spencer5f016e22007-07-11 17:01:13 +00002241 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002242 LValueReferenceType *NewIP =
2243 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002244 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002245 }
2246
John McCall6b304a02009-09-24 23:30:46 +00002247 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00002248 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2249 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00002250 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002251 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00002252
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002253 return QualType(New, 0);
2254}
2255
2256/// getRValueReferenceType - Return the uniqued reference to the type for an
2257/// rvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002258QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002259 // Unique pointers, to guarantee there is only one pointer of a particular
2260 // structure.
2261 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00002262 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002263
2264 void *InsertPos = 0;
2265 if (RValueReferenceType *RT =
2266 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2267 return QualType(RT, 0);
2268
John McCall54e14c42009-10-22 22:37:11 +00002269 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2270
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002271 // If the referencee type isn't canonical, this won't be a canonical type
2272 // either, so fill in the canonical type field.
2273 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00002274 if (InnerRef || !T.isCanonical()) {
2275 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2276 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002277
2278 // Get the new insert position for the node we care about.
2279 RValueReferenceType *NewIP =
2280 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002281 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002282 }
2283
John McCall6b304a02009-09-24 23:30:46 +00002284 RValueReferenceType *New
2285 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002286 Types.push_back(New);
2287 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002288 return QualType(New, 0);
2289}
2290
Sebastian Redlf30208a2009-01-24 21:16:55 +00002291/// getMemberPointerType - Return the uniqued reference to the type for a
2292/// member pointer to the specified type, in the specified class.
Jay Foad4ba2a172011-01-12 09:06:06 +00002293QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redlf30208a2009-01-24 21:16:55 +00002294 // Unique pointers, to guarantee there is only one pointer of a particular
2295 // structure.
2296 llvm::FoldingSetNodeID ID;
2297 MemberPointerType::Profile(ID, T, Cls);
2298
2299 void *InsertPos = 0;
2300 if (MemberPointerType *PT =
2301 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2302 return QualType(PT, 0);
2303
2304 // If the pointee or class type isn't canonical, this won't be a canonical
2305 // type either, so fill in the canonical type field.
2306 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00002307 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00002308 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2309
2310 // Get the new insert position for the node we care about.
2311 MemberPointerType *NewIP =
2312 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002313 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redlf30208a2009-01-24 21:16:55 +00002314 }
John McCall6b304a02009-09-24 23:30:46 +00002315 MemberPointerType *New
2316 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00002317 Types.push_back(New);
2318 MemberPointerTypes.InsertNode(New, InsertPos);
2319 return QualType(New, 0);
2320}
2321
Mike Stump1eb44332009-09-09 15:08:12 +00002322/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00002323/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002324QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00002325 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00002326 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002327 unsigned IndexTypeQuals) const {
Sebastian Redl923d56d2009-11-05 15:52:31 +00002328 assert((EltTy->isDependentType() ||
2329 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00002330 "Constant array of VLAs is illegal!");
2331
Chris Lattner38aeec72009-05-13 04:12:56 +00002332 // Convert the array size into a canonical width matching the pointer size for
2333 // the target.
2334 llvm::APInt ArySize(ArySizeIn);
Jay Foad9f71a8f2010-12-07 08:25:34 +00002335 ArySize =
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002336 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump1eb44332009-09-09 15:08:12 +00002337
Reid Spencer5f016e22007-07-11 17:01:13 +00002338 llvm::FoldingSetNodeID ID;
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002339 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00002340
Reid Spencer5f016e22007-07-11 17:01:13 +00002341 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002342 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002343 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002344 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002345
John McCall3b657512011-01-19 10:06:00 +00002346 // If the element type isn't canonical or has qualifiers, this won't
2347 // be a canonical type either, so fill in the canonical type field.
2348 QualType Canon;
2349 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2350 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00002351 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002352 ASM, IndexTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00002353 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00002354
Reid Spencer5f016e22007-07-11 17:01:13 +00002355 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00002356 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002357 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002358 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002359 }
Mike Stump1eb44332009-09-09 15:08:12 +00002360
John McCall6b304a02009-09-24 23:30:46 +00002361 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002362 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002363 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002364 Types.push_back(New);
2365 return QualType(New, 0);
2366}
2367
John McCallce889032011-01-18 08:40:38 +00002368/// getVariableArrayDecayedType - Turns the given type, which may be
2369/// variably-modified, into the corresponding type with all the known
2370/// sizes replaced with [*].
2371QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2372 // Vastly most common case.
2373 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002374
John McCallce889032011-01-18 08:40:38 +00002375 QualType result;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002376
John McCallce889032011-01-18 08:40:38 +00002377 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00002378 const Type *ty = split.Ty;
John McCallce889032011-01-18 08:40:38 +00002379 switch (ty->getTypeClass()) {
2380#define TYPE(Class, Base)
2381#define ABSTRACT_TYPE(Class, Base)
2382#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2383#include "clang/AST/TypeNodes.def"
2384 llvm_unreachable("didn't desugar past all non-canonical types?");
2385
2386 // These types should never be variably-modified.
2387 case Type::Builtin:
2388 case Type::Complex:
2389 case Type::Vector:
2390 case Type::ExtVector:
2391 case Type::DependentSizedExtVector:
2392 case Type::ObjCObject:
2393 case Type::ObjCInterface:
2394 case Type::ObjCObjectPointer:
2395 case Type::Record:
2396 case Type::Enum:
2397 case Type::UnresolvedUsing:
2398 case Type::TypeOfExpr:
2399 case Type::TypeOf:
2400 case Type::Decltype:
Sean Huntca63c202011-05-24 22:41:36 +00002401 case Type::UnaryTransform:
John McCallce889032011-01-18 08:40:38 +00002402 case Type::DependentName:
2403 case Type::InjectedClassName:
2404 case Type::TemplateSpecialization:
2405 case Type::DependentTemplateSpecialization:
2406 case Type::TemplateTypeParm:
2407 case Type::SubstTemplateTypeParmPack:
Richard Smith34b41d92011-02-20 03:19:35 +00002408 case Type::Auto:
John McCallce889032011-01-18 08:40:38 +00002409 case Type::PackExpansion:
2410 llvm_unreachable("type should never be variably-modified");
2411
2412 // These types can be variably-modified but should never need to
2413 // further decay.
2414 case Type::FunctionNoProto:
2415 case Type::FunctionProto:
2416 case Type::BlockPointer:
2417 case Type::MemberPointer:
2418 return type;
2419
2420 // These types can be variably-modified. All these modifications
2421 // preserve structure except as noted by comments.
2422 // TODO: if we ever care about optimizing VLAs, there are no-op
2423 // optimizations available here.
2424 case Type::Pointer:
2425 result = getPointerType(getVariableArrayDecayedType(
2426 cast<PointerType>(ty)->getPointeeType()));
2427 break;
2428
2429 case Type::LValueReference: {
2430 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2431 result = getLValueReferenceType(
2432 getVariableArrayDecayedType(lv->getPointeeType()),
2433 lv->isSpelledAsLValue());
2434 break;
2435 }
2436
2437 case Type::RValueReference: {
2438 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2439 result = getRValueReferenceType(
2440 getVariableArrayDecayedType(lv->getPointeeType()));
2441 break;
2442 }
2443
Eli Friedmanb001de72011-10-06 23:00:33 +00002444 case Type::Atomic: {
2445 const AtomicType *at = cast<AtomicType>(ty);
2446 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2447 break;
2448 }
2449
John McCallce889032011-01-18 08:40:38 +00002450 case Type::ConstantArray: {
2451 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2452 result = getConstantArrayType(
2453 getVariableArrayDecayedType(cat->getElementType()),
2454 cat->getSize(),
2455 cat->getSizeModifier(),
2456 cat->getIndexTypeCVRQualifiers());
2457 break;
2458 }
2459
2460 case Type::DependentSizedArray: {
2461 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2462 result = getDependentSizedArrayType(
2463 getVariableArrayDecayedType(dat->getElementType()),
2464 dat->getSizeExpr(),
2465 dat->getSizeModifier(),
2466 dat->getIndexTypeCVRQualifiers(),
2467 dat->getBracketsRange());
2468 break;
2469 }
2470
2471 // Turn incomplete types into [*] types.
2472 case Type::IncompleteArray: {
2473 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2474 result = getVariableArrayType(
2475 getVariableArrayDecayedType(iat->getElementType()),
2476 /*size*/ 0,
2477 ArrayType::Normal,
2478 iat->getIndexTypeCVRQualifiers(),
2479 SourceRange());
2480 break;
2481 }
2482
2483 // Turn VLA types into [*] types.
2484 case Type::VariableArray: {
2485 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2486 result = getVariableArrayType(
2487 getVariableArrayDecayedType(vat->getElementType()),
2488 /*size*/ 0,
2489 ArrayType::Star,
2490 vat->getIndexTypeCVRQualifiers(),
2491 vat->getBracketsRange());
2492 break;
2493 }
2494 }
2495
2496 // Apply the top-level qualifiers from the original.
John McCall200fa532012-02-08 00:46:36 +00002497 return getQualifiedType(result, split.Quals);
John McCallce889032011-01-18 08:40:38 +00002498}
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002499
Steve Naroffbdbf7b02007-08-30 18:14:25 +00002500/// getVariableArrayType - Returns a non-unique reference to the type for a
2501/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002502QualType ASTContext::getVariableArrayType(QualType EltTy,
2503 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00002504 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002505 unsigned IndexTypeQuals,
Jay Foad4ba2a172011-01-12 09:06:06 +00002506 SourceRange Brackets) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00002507 // Since we don't unique expressions, it isn't possible to unique VLA's
2508 // that have an expression provided for their size.
John McCall3b657512011-01-19 10:06:00 +00002509 QualType Canon;
Douglas Gregor715e9c82010-05-23 16:10:32 +00002510
John McCall3b657512011-01-19 10:06:00 +00002511 // Be sure to pull qualifiers off the element type.
2512 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2513 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00002514 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002515 IndexTypeQuals, Brackets);
John McCall200fa532012-02-08 00:46:36 +00002516 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor715e9c82010-05-23 16:10:32 +00002517 }
2518
John McCall6b304a02009-09-24 23:30:46 +00002519 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002520 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002521
2522 VariableArrayTypes.push_back(New);
2523 Types.push_back(New);
2524 return QualType(New, 0);
2525}
2526
Douglas Gregor898574e2008-12-05 23:32:09 +00002527/// getDependentSizedArrayType - Returns a non-unique reference to
2528/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00002529/// type.
John McCall3b657512011-01-19 10:06:00 +00002530QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2531 Expr *numElements,
Douglas Gregor898574e2008-12-05 23:32:09 +00002532 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00002533 unsigned elementTypeQuals,
2534 SourceRange brackets) const {
2535 assert((!numElements || numElements->isTypeDependent() ||
2536 numElements->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00002537 "Size must be type- or value-dependent!");
2538
John McCall3b657512011-01-19 10:06:00 +00002539 // Dependently-sized array types that do not have a specified number
2540 // of elements will have their sizes deduced from a dependent
2541 // initializer. We do no canonicalization here at all, which is okay
2542 // because they can't be used in most locations.
2543 if (!numElements) {
2544 DependentSizedArrayType *newType
2545 = new (*this, TypeAlignment)
2546 DependentSizedArrayType(*this, elementType, QualType(),
2547 numElements, ASM, elementTypeQuals,
2548 brackets);
2549 Types.push_back(newType);
2550 return QualType(newType, 0);
2551 }
2552
2553 // Otherwise, we actually build a new type every time, but we
2554 // also build a canonical type.
2555
2556 SplitQualType canonElementType = getCanonicalType(elementType).split();
2557
2558 void *insertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00002559 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00002560 DependentSizedArrayType::Profile(ID, *this,
John McCall200fa532012-02-08 00:46:36 +00002561 QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002562 ASM, elementTypeQuals, numElements);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002563
John McCall3b657512011-01-19 10:06:00 +00002564 // Look for an existing type with these properties.
2565 DependentSizedArrayType *canonTy =
2566 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002567
John McCall3b657512011-01-19 10:06:00 +00002568 // If we don't have one, build one.
2569 if (!canonTy) {
2570 canonTy = new (*this, TypeAlignment)
John McCall200fa532012-02-08 00:46:36 +00002571 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002572 QualType(), numElements, ASM, elementTypeQuals,
2573 brackets);
2574 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2575 Types.push_back(canonTy);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002576 }
2577
John McCall3b657512011-01-19 10:06:00 +00002578 // Apply qualifiers from the element type to the array.
2579 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall200fa532012-02-08 00:46:36 +00002580 canonElementType.Quals);
Mike Stump1eb44332009-09-09 15:08:12 +00002581
John McCall3b657512011-01-19 10:06:00 +00002582 // If we didn't need extra canonicalization for the element type,
2583 // then just use that as our result.
John McCall200fa532012-02-08 00:46:36 +00002584 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall3b657512011-01-19 10:06:00 +00002585 return canon;
2586
2587 // Otherwise, we need to build a type which follows the spelling
2588 // of the element type.
2589 DependentSizedArrayType *sugaredType
2590 = new (*this, TypeAlignment)
2591 DependentSizedArrayType(*this, elementType, canon, numElements,
2592 ASM, elementTypeQuals, brackets);
2593 Types.push_back(sugaredType);
2594 return QualType(sugaredType, 0);
Douglas Gregor898574e2008-12-05 23:32:09 +00002595}
2596
John McCall3b657512011-01-19 10:06:00 +00002597QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanc5773c42008-02-15 18:16:39 +00002598 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00002599 unsigned elementTypeQuals) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00002600 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00002601 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002602
John McCall3b657512011-01-19 10:06:00 +00002603 void *insertPos = 0;
2604 if (IncompleteArrayType *iat =
2605 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2606 return QualType(iat, 0);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002607
2608 // If the element type isn't canonical, this won't be a canonical type
John McCall3b657512011-01-19 10:06:00 +00002609 // either, so fill in the canonical type field. We also have to pull
2610 // qualifiers off the element type.
2611 QualType canon;
Eli Friedmanc5773c42008-02-15 18:16:39 +00002612
John McCall3b657512011-01-19 10:06:00 +00002613 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2614 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall200fa532012-02-08 00:46:36 +00002615 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002616 ASM, elementTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00002617 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002618
2619 // Get the new insert position for the node we care about.
John McCall3b657512011-01-19 10:06:00 +00002620 IncompleteArrayType *existing =
2621 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2622 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00002623 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00002624
John McCall3b657512011-01-19 10:06:00 +00002625 IncompleteArrayType *newType = new (*this, TypeAlignment)
2626 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002627
John McCall3b657512011-01-19 10:06:00 +00002628 IncompleteArrayTypes.InsertNode(newType, insertPos);
2629 Types.push_back(newType);
2630 return QualType(newType, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00002631}
2632
Steve Naroff73322922007-07-18 18:00:27 +00002633/// getVectorType - Return the unique reference to a vector type of
2634/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00002635QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad4ba2a172011-01-12 09:06:06 +00002636 VectorType::VectorKind VecKind) const {
John McCall3b657512011-01-19 10:06:00 +00002637 assert(vecType->isBuiltinType());
Mike Stump1eb44332009-09-09 15:08:12 +00002638
Reid Spencer5f016e22007-07-11 17:01:13 +00002639 // Check if we've already instantiated a vector of this type.
2640 llvm::FoldingSetNodeID ID;
Bob Wilsone86d78c2010-11-10 21:56:12 +00002641 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner788b0fd2010-06-23 06:00:24 +00002642
Reid Spencer5f016e22007-07-11 17:01:13 +00002643 void *InsertPos = 0;
2644 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2645 return QualType(VTP, 0);
2646
2647 // If the element type isn't canonical, this won't be a canonical type either,
2648 // so fill in the canonical type field.
2649 QualType Canonical;
Douglas Gregor255210e2010-08-06 10:14:59 +00002650 if (!vecType.isCanonical()) {
Bob Wilson231da7e2010-11-16 00:32:20 +00002651 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump1eb44332009-09-09 15:08:12 +00002652
Reid Spencer5f016e22007-07-11 17:01:13 +00002653 // Get the new insert position for the node we care about.
2654 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002655 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002656 }
John McCall6b304a02009-09-24 23:30:46 +00002657 VectorType *New = new (*this, TypeAlignment)
Bob Wilsone86d78c2010-11-10 21:56:12 +00002658 VectorType(vecType, NumElts, Canonical, VecKind);
Reid Spencer5f016e22007-07-11 17:01:13 +00002659 VectorTypes.InsertNode(New, InsertPos);
2660 Types.push_back(New);
2661 return QualType(New, 0);
2662}
2663
Nate Begeman213541a2008-04-18 23:10:10 +00002664/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00002665/// the specified element type and size. VectorType must be a built-in type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002666QualType
2667ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor4ac01402011-06-15 16:02:29 +00002668 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump1eb44332009-09-09 15:08:12 +00002669
Steve Naroff73322922007-07-18 18:00:27 +00002670 // Check if we've already instantiated a vector of this type.
2671 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00002672 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsone86d78c2010-11-10 21:56:12 +00002673 VectorType::GenericVector);
Steve Naroff73322922007-07-18 18:00:27 +00002674 void *InsertPos = 0;
2675 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2676 return QualType(VTP, 0);
2677
2678 // If the element type isn't canonical, this won't be a canonical type either,
2679 // so fill in the canonical type field.
2680 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002681 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00002682 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00002683
Steve Naroff73322922007-07-18 18:00:27 +00002684 // Get the new insert position for the node we care about.
2685 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002686 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00002687 }
John McCall6b304a02009-09-24 23:30:46 +00002688 ExtVectorType *New = new (*this, TypeAlignment)
2689 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00002690 VectorTypes.InsertNode(New, InsertPos);
2691 Types.push_back(New);
2692 return QualType(New, 0);
2693}
2694
Jay Foad4ba2a172011-01-12 09:06:06 +00002695QualType
2696ASTContext::getDependentSizedExtVectorType(QualType vecType,
2697 Expr *SizeExpr,
2698 SourceLocation AttrLoc) const {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002699 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00002700 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002701 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002702
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002703 void *InsertPos = 0;
2704 DependentSizedExtVectorType *Canon
2705 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2706 DependentSizedExtVectorType *New;
2707 if (Canon) {
2708 // We already have a canonical version of this array type; use it as
2709 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00002710 New = new (*this, TypeAlignment)
2711 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2712 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002713 } else {
2714 QualType CanonVecTy = getCanonicalType(vecType);
2715 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00002716 New = new (*this, TypeAlignment)
2717 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2718 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002719
2720 DependentSizedExtVectorType *CanonCheck
2721 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2722 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2723 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002724 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2725 } else {
2726 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2727 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00002728 New = new (*this, TypeAlignment)
2729 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002730 }
2731 }
Mike Stump1eb44332009-09-09 15:08:12 +00002732
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00002733 Types.push_back(New);
2734 return QualType(New, 0);
2735}
2736
Douglas Gregor72564e72009-02-26 23:50:07 +00002737/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00002738///
Jay Foad4ba2a172011-01-12 09:06:06 +00002739QualType
2740ASTContext::getFunctionNoProtoType(QualType ResultTy,
2741 const FunctionType::ExtInfo &Info) const {
Reid Kleckneref072032013-08-27 23:08:25 +00002742 const CallingConv CallConv = Info.getCC();
2743
Reid Spencer5f016e22007-07-11 17:01:13 +00002744 // Unique functions, to guarantee there is only one function of a particular
2745 // structure.
2746 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00002747 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00002748
Reid Spencer5f016e22007-07-11 17:01:13 +00002749 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002750 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00002751 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002752 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002753
Reid Spencer5f016e22007-07-11 17:01:13 +00002754 QualType Canonical;
Reid Kleckneref072032013-08-27 23:08:25 +00002755 if (!ResultTy.isCanonical()) {
2756 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), Info);
Mike Stump1eb44332009-09-09 15:08:12 +00002757
Reid Spencer5f016e22007-07-11 17:01:13 +00002758 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002759 FunctionNoProtoType *NewIP =
2760 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002761 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002762 }
Mike Stump1eb44332009-09-09 15:08:12 +00002763
Roman Divackycfe9af22011-03-01 17:40:53 +00002764 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall6b304a02009-09-24 23:30:46 +00002765 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divackycfe9af22011-03-01 17:40:53 +00002766 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00002767 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00002768 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002769 return QualType(New, 0);
2770}
2771
Douglas Gregor02dd7982013-01-17 23:36:45 +00002772/// \brief Determine whether \p T is canonical as the result type of a function.
2773static bool isCanonicalResultType(QualType T) {
2774 return T.isCanonical() &&
2775 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2776 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2777}
2778
Reid Spencer5f016e22007-07-11 17:01:13 +00002779/// getFunctionType - Return a normal function type with a typed argument
2780/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad4ba2a172011-01-12 09:06:06 +00002781QualType
Jordan Rosebea522f2013-03-08 21:51:21 +00002782ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad4ba2a172011-01-12 09:06:06 +00002783 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rosebea522f2013-03-08 21:51:21 +00002784 size_t NumArgs = ArgArray.size();
2785
Reid Spencer5f016e22007-07-11 17:01:13 +00002786 // Unique functions, to guarantee there is only one function of a particular
2787 // structure.
2788 llvm::FoldingSetNodeID ID;
Jordan Rosebea522f2013-03-08 21:51:21 +00002789 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
2790 *this);
Reid Spencer5f016e22007-07-11 17:01:13 +00002791
2792 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002793 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00002794 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002795 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00002796
2797 // Determine whether the type being created is already canonical or not.
Richard Smitheefb3d52012-02-10 09:58:53 +00002798 bool isCanonical =
Douglas Gregor02dd7982013-01-17 23:36:45 +00002799 EPI.ExceptionSpecType == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smitheefb3d52012-02-10 09:58:53 +00002800 !EPI.HasTrailingReturn;
Reid Spencer5f016e22007-07-11 17:01:13 +00002801 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002802 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00002803 isCanonical = false;
2804
2805 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00002806 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002807 QualType Canonical;
Reid Kleckneref072032013-08-27 23:08:25 +00002808 if (!isCanonical) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002809 SmallVector<QualType, 16> CanonicalArgs;
Reid Spencer5f016e22007-07-11 17:01:13 +00002810 CanonicalArgs.reserve(NumArgs);
2811 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002812 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00002813
John McCalle23cf432010-12-14 08:05:40 +00002814 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smitheefb3d52012-02-10 09:58:53 +00002815 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002816 CanonicalEPI.ExceptionSpecType = EST_None;
2817 CanonicalEPI.NumExceptions = 0;
John McCalle23cf432010-12-14 08:05:40 +00002818
Douglas Gregor02dd7982013-01-17 23:36:45 +00002819 // Result types do not have ARC lifetime qualifiers.
2820 QualType CanResultTy = getCanonicalType(ResultTy);
2821 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2822 Qualifiers Qs = CanResultTy.getQualifiers();
2823 Qs.removeObjCLifetime();
2824 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2825 }
2826
Jordan Rosebea522f2013-03-08 21:51:21 +00002827 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl465226e2009-05-27 22:11:52 +00002828
Reid Spencer5f016e22007-07-11 17:01:13 +00002829 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002830 FunctionProtoType *NewIP =
2831 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002832 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002833 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002834
John McCallf85e1932011-06-15 23:02:42 +00002835 // FunctionProtoType objects are allocated with extra bytes after
2836 // them for three variable size arrays at the end:
2837 // - parameter types
2838 // - exception types
2839 // - consumed-arguments flags
2840 // Instead of the exception types, there could be a noexcept
Richard Smithb9d0b762012-07-27 04:22:15 +00002841 // expression, or information used to resolve the exception
2842 // specification.
John McCalle23cf432010-12-14 08:05:40 +00002843 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redl60618fa2011-03-12 11:50:43 +00002844 NumArgs * sizeof(QualType);
Richard Smithb9d0b762012-07-27 04:22:15 +00002845 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redl60618fa2011-03-12 11:50:43 +00002846 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithb9d0b762012-07-27 04:22:15 +00002847 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002848 Size += sizeof(Expr*);
Richard Smithe6975e92012-04-17 00:58:00 +00002849 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smith13bffc52012-04-19 00:08:28 +00002850 Size += 2 * sizeof(FunctionDecl*);
Richard Smithb9d0b762012-07-27 04:22:15 +00002851 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2852 Size += sizeof(FunctionDecl*);
Sebastian Redl60618fa2011-03-12 11:50:43 +00002853 }
John McCallf85e1932011-06-15 23:02:42 +00002854 if (EPI.ConsumedArguments)
2855 Size += NumArgs * sizeof(bool);
2856
John McCalle23cf432010-12-14 08:05:40 +00002857 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divackycfe9af22011-03-01 17:40:53 +00002858 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rosebea522f2013-03-08 21:51:21 +00002859 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00002860 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00002861 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002862 return QualType(FTP, 0);
2863}
2864
John McCall3cb0ebd2010-03-10 03:28:59 +00002865#ifndef NDEBUG
2866static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2867 if (!isa<CXXRecordDecl>(D)) return false;
2868 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2869 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2870 return true;
2871 if (RD->getDescribedClassTemplate() &&
2872 !isa<ClassTemplateSpecializationDecl>(RD))
2873 return true;
2874 return false;
2875}
2876#endif
2877
2878/// getInjectedClassNameType - Return the unique reference to the
2879/// injected class name type for the specified templated declaration.
2880QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00002881 QualType TST) const {
John McCall3cb0ebd2010-03-10 03:28:59 +00002882 assert(NeedsInjectedClassNameType(Decl));
2883 if (Decl->TypeForDecl) {
2884 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregoref96ee02012-01-14 16:38:05 +00002885 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00002886 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2887 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2888 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2889 } else {
John McCallf4c73712011-01-19 06:33:43 +00002890 Type *newType =
John McCall31f17ec2010-04-27 00:57:59 +00002891 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCallf4c73712011-01-19 06:33:43 +00002892 Decl->TypeForDecl = newType;
2893 Types.push_back(newType);
John McCall3cb0ebd2010-03-10 03:28:59 +00002894 }
2895 return QualType(Decl->TypeForDecl, 0);
2896}
2897
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002898/// getTypeDeclType - Return the unique reference to the type for the
2899/// specified type declaration.
Jay Foad4ba2a172011-01-12 09:06:06 +00002900QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00002901 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00002902 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00002903
Richard Smith162e1c12011-04-15 14:24:37 +00002904 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002905 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00002906
John McCallbecb8d52010-03-10 06:48:02 +00002907 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2908 "Template type parameter types are always available.");
2909
John McCall19c85762010-02-16 03:57:14 +00002910 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002911 assert(!Record->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002912 "struct/union has previous declaration");
2913 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002914 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00002915 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002916 assert(!Enum->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002917 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002918 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00002919 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00002920 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCallf4c73712011-01-19 06:33:43 +00002921 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2922 Decl->TypeForDecl = newType;
2923 Types.push_back(newType);
Mike Stump9fdbab32009-07-31 02:02:20 +00002924 } else
John McCallbecb8d52010-03-10 06:48:02 +00002925 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002926
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002927 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002928}
2929
Reid Spencer5f016e22007-07-11 17:01:13 +00002930/// getTypedefType - Return the unique reference to the type for the
Richard Smith162e1c12011-04-15 14:24:37 +00002931/// specified typedef name decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002932QualType
Richard Smith162e1c12011-04-15 14:24:37 +00002933ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2934 QualType Canonical) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002935 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002936
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002937 if (Canonical.isNull())
2938 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCallf4c73712011-01-19 06:33:43 +00002939 TypedefType *newType = new(*this, TypeAlignment)
John McCall6b304a02009-09-24 23:30:46 +00002940 TypedefType(Type::Typedef, Decl, Canonical);
John McCallf4c73712011-01-19 06:33:43 +00002941 Decl->TypeForDecl = newType;
2942 Types.push_back(newType);
2943 return QualType(newType, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002944}
2945
Jay Foad4ba2a172011-01-12 09:06:06 +00002946QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002947 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2948
Douglas Gregoref96ee02012-01-14 16:38:05 +00002949 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002950 if (PrevDecl->TypeForDecl)
2951 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2952
John McCallf4c73712011-01-19 06:33:43 +00002953 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2954 Decl->TypeForDecl = newType;
2955 Types.push_back(newType);
2956 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002957}
2958
Jay Foad4ba2a172011-01-12 09:06:06 +00002959QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002960 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2961
Douglas Gregoref96ee02012-01-14 16:38:05 +00002962 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002963 if (PrevDecl->TypeForDecl)
2964 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2965
John McCallf4c73712011-01-19 06:33:43 +00002966 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2967 Decl->TypeForDecl = newType;
2968 Types.push_back(newType);
2969 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002970}
2971
John McCall9d156a72011-01-06 01:58:22 +00002972QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2973 QualType modifiedType,
2974 QualType equivalentType) {
2975 llvm::FoldingSetNodeID id;
2976 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2977
2978 void *insertPos = 0;
2979 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2980 if (type) return QualType(type, 0);
2981
2982 QualType canon = getCanonicalType(equivalentType);
2983 type = new (*this, TypeAlignment)
2984 AttributedType(canon, attrKind, modifiedType, equivalentType);
2985
2986 Types.push_back(type);
2987 AttributedTypes.InsertNode(type, insertPos);
2988
2989 return QualType(type, 0);
2990}
2991
2992
John McCall49a832b2009-10-18 09:09:24 +00002993/// \brief Retrieve a substitution-result type.
2994QualType
2995ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad4ba2a172011-01-12 09:06:06 +00002996 QualType Replacement) const {
John McCall467b27b2009-10-22 20:10:53 +00002997 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00002998 && "replacement types must always be canonical");
2999
3000 llvm::FoldingSetNodeID ID;
3001 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
3002 void *InsertPos = 0;
3003 SubstTemplateTypeParmType *SubstParm
3004 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3005
3006 if (!SubstParm) {
3007 SubstParm = new (*this, TypeAlignment)
3008 SubstTemplateTypeParmType(Parm, Replacement);
3009 Types.push_back(SubstParm);
3010 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3011 }
3012
3013 return QualType(SubstParm, 0);
3014}
3015
Douglas Gregorc3069d62011-01-14 02:55:32 +00003016/// \brief Retrieve a
3017QualType ASTContext::getSubstTemplateTypeParmPackType(
3018 const TemplateTypeParmType *Parm,
3019 const TemplateArgument &ArgPack) {
3020#ifndef NDEBUG
3021 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
3022 PEnd = ArgPack.pack_end();
3023 P != PEnd; ++P) {
3024 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3025 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
3026 }
3027#endif
3028
3029 llvm::FoldingSetNodeID ID;
3030 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
3031 void *InsertPos = 0;
3032 if (SubstTemplateTypeParmPackType *SubstParm
3033 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3034 return QualType(SubstParm, 0);
3035
3036 QualType Canon;
3037 if (!Parm->isCanonicalUnqualified()) {
3038 Canon = getCanonicalType(QualType(Parm, 0));
3039 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3040 ArgPack);
3041 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3042 }
3043
3044 SubstTemplateTypeParmPackType *SubstParm
3045 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3046 ArgPack);
3047 Types.push_back(SubstParm);
3048 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3049 return QualType(SubstParm, 0);
3050}
3051
Douglas Gregorfab9d672009-02-05 23:33:38 +00003052/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00003053/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003054/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00003055QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003056 bool ParameterPack,
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003057 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregorfab9d672009-02-05 23:33:38 +00003058 llvm::FoldingSetNodeID ID;
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003059 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregorfab9d672009-02-05 23:33:38 +00003060 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003061 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00003062 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3063
3064 if (TypeParm)
3065 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00003066
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003067 if (TTPDecl) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003068 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003069 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003070
3071 TemplateTypeParmType *TypeCheck
3072 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3073 assert(!TypeCheck && "Template type parameter canonical type broken");
3074 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003075 } else
John McCall6b304a02009-09-24 23:30:46 +00003076 TypeParm = new (*this, TypeAlignment)
3077 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00003078
3079 Types.push_back(TypeParm);
3080 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3081
3082 return QualType(TypeParm, 0);
3083}
3084
John McCall3cb0ebd2010-03-10 03:28:59 +00003085TypeSourceInfo *
3086ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3087 SourceLocation NameLoc,
3088 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003089 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003090 assert(!Name.getAsDependentTemplateName() &&
3091 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00003092 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCall3cb0ebd2010-03-10 03:28:59 +00003093
3094 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie39e6ab42013-02-18 22:06:02 +00003095 TemplateSpecializationTypeLoc TL =
3096 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara55d23c92012-02-06 14:41:24 +00003097 TL.setTemplateKeywordLoc(SourceLocation());
John McCall3cb0ebd2010-03-10 03:28:59 +00003098 TL.setTemplateNameLoc(NameLoc);
3099 TL.setLAngleLoc(Args.getLAngleLoc());
3100 TL.setRAngleLoc(Args.getRAngleLoc());
3101 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3102 TL.setArgLocInfo(i, Args[i].getLocInfo());
3103 return DI;
3104}
3105
Mike Stump1eb44332009-09-09 15:08:12 +00003106QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00003107ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00003108 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003109 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003110 assert(!Template.getAsDependentTemplateName() &&
3111 "No dependent template names here!");
3112
John McCalld5532b62009-11-23 01:53:49 +00003113 unsigned NumArgs = Args.size();
3114
Chris Lattner5f9e2722011-07-23 10:55:15 +00003115 SmallVector<TemplateArgument, 4> ArgVec;
John McCall833ca992009-10-29 08:12:44 +00003116 ArgVec.reserve(NumArgs);
3117 for (unsigned i = 0; i != NumArgs; ++i)
3118 ArgVec.push_back(Args[i].getArgument());
3119
John McCall31f17ec2010-04-27 00:57:59 +00003120 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003121 Underlying);
John McCall833ca992009-10-29 08:12:44 +00003122}
3123
Douglas Gregorb70126a2012-02-03 17:16:23 +00003124#ifndef NDEBUG
3125static bool hasAnyPackExpansions(const TemplateArgument *Args,
3126 unsigned NumArgs) {
3127 for (unsigned I = 0; I != NumArgs; ++I)
3128 if (Args[I].isPackExpansion())
3129 return true;
3130
3131 return true;
3132}
3133#endif
3134
John McCall833ca992009-10-29 08:12:44 +00003135QualType
3136ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003137 const TemplateArgument *Args,
3138 unsigned NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003139 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003140 assert(!Template.getAsDependentTemplateName() &&
3141 "No dependent template names here!");
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00003142 // Look through qualified template names.
3143 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3144 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003145
Douglas Gregorb70126a2012-02-03 17:16:23 +00003146 bool IsTypeAlias =
Richard Smith3e4c6c42011-05-05 21:57:07 +00003147 Template.getAsTemplateDecl() &&
3148 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00003149 QualType CanonType;
3150 if (!Underlying.isNull())
3151 CanonType = getCanonicalType(Underlying);
3152 else {
Douglas Gregorb70126a2012-02-03 17:16:23 +00003153 // We can get here with an alias template when the specialization contains
3154 // a pack expansion that does not match up with a parameter pack.
3155 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3156 "Caller must compute aliased type");
3157 IsTypeAlias = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00003158 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3159 NumArgs);
3160 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00003161
Douglas Gregor1275ae02009-07-28 23:00:59 +00003162 // Allocate the (non-canonical) template specialization type, but don't
3163 // try to unique it: these types typically have location information that
3164 // we don't unique and don't want to lose.
Richard Smith3e4c6c42011-05-05 21:57:07 +00003165 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3166 sizeof(TemplateArgument) * NumArgs +
Douglas Gregorb70126a2012-02-03 17:16:23 +00003167 (IsTypeAlias? sizeof(QualType) : 0),
John McCall6b304a02009-09-24 23:30:46 +00003168 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00003169 TemplateSpecializationType *Spec
Douglas Gregorb70126a2012-02-03 17:16:23 +00003170 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3171 IsTypeAlias ? Underlying : QualType());
Mike Stump1eb44332009-09-09 15:08:12 +00003172
Douglas Gregor55f6b142009-02-09 18:46:07 +00003173 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00003174 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00003175}
3176
Mike Stump1eb44332009-09-09 15:08:12 +00003177QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003178ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3179 const TemplateArgument *Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00003180 unsigned NumArgs) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003181 assert(!Template.getAsDependentTemplateName() &&
3182 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00003183
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00003184 // Look through qualified template names.
3185 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3186 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003187
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003188 // Build the canonical template specialization type.
3189 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003190 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003191 CanonArgs.reserve(NumArgs);
3192 for (unsigned I = 0; I != NumArgs; ++I)
3193 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3194
3195 // Determine whether this canonical template specialization type already
3196 // exists.
3197 llvm::FoldingSetNodeID ID;
3198 TemplateSpecializationType::Profile(ID, CanonTemplate,
3199 CanonArgs.data(), NumArgs, *this);
3200
3201 void *InsertPos = 0;
3202 TemplateSpecializationType *Spec
3203 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3204
3205 if (!Spec) {
3206 // Allocate a new canonical template specialization type.
3207 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3208 sizeof(TemplateArgument) * NumArgs),
3209 TypeAlignment);
3210 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3211 CanonArgs.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003212 QualType(), QualType());
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003213 Types.push_back(Spec);
3214 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3215 }
3216
3217 assert(Spec->isDependentType() &&
3218 "Non-dependent template-id type must have a canonical type");
3219 return QualType(Spec, 0);
3220}
3221
3222QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003223ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3224 NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00003225 QualType NamedType) const {
Douglas Gregore4e5b052009-03-19 00:18:19 +00003226 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003227 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003228
3229 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003230 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003231 if (T)
3232 return QualType(T, 0);
3233
Douglas Gregor789b1f62010-02-04 18:10:26 +00003234 QualType Canon = NamedType;
3235 if (!Canon.isCanonical()) {
3236 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003237 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3238 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00003239 (void)CheckT;
3240 }
3241
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003242 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003243 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003244 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003245 return QualType(T, 0);
3246}
3247
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003248QualType
Jay Foad4ba2a172011-01-12 09:06:06 +00003249ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003250 llvm::FoldingSetNodeID ID;
3251 ParenType::Profile(ID, InnerType);
3252
3253 void *InsertPos = 0;
3254 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3255 if (T)
3256 return QualType(T, 0);
3257
3258 QualType Canon = InnerType;
3259 if (!Canon.isCanonical()) {
3260 Canon = getCanonicalType(InnerType);
3261 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3262 assert(!CheckT && "Paren canonical type broken");
3263 (void)CheckT;
3264 }
3265
3266 T = new (*this) ParenType(InnerType, Canon);
3267 Types.push_back(T);
3268 ParenTypes.InsertNode(T, InsertPos);
3269 return QualType(T, 0);
3270}
3271
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003272QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3273 NestedNameSpecifier *NNS,
3274 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00003275 QualType Canon) const {
Douglas Gregord57959a2009-03-27 23:10:48 +00003276 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
3277
3278 if (Canon.isNull()) {
3279 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003280 ElaboratedTypeKeyword CanonKeyword = Keyword;
3281 if (Keyword == ETK_None)
3282 CanonKeyword = ETK_Typename;
3283
3284 if (CanonNNS != NNS || CanonKeyword != Keyword)
3285 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00003286 }
3287
3288 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003289 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00003290
3291 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00003292 DependentNameType *T
3293 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00003294 if (T)
3295 return QualType(T, 0);
3296
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003297 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00003298 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00003299 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00003300 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00003301}
3302
Mike Stump1eb44332009-09-09 15:08:12 +00003303QualType
John McCall33500952010-06-11 00:33:02 +00003304ASTContext::getDependentTemplateSpecializationType(
3305 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003306 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00003307 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00003308 const TemplateArgumentListInfo &Args) const {
John McCall33500952010-06-11 00:33:02 +00003309 // TODO: avoid this copy
Chris Lattner5f9e2722011-07-23 10:55:15 +00003310 SmallVector<TemplateArgument, 16> ArgCopy;
John McCall33500952010-06-11 00:33:02 +00003311 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3312 ArgCopy.push_back(Args[I].getArgument());
3313 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3314 ArgCopy.size(),
3315 ArgCopy.data());
3316}
3317
3318QualType
3319ASTContext::getDependentTemplateSpecializationType(
3320 ElaboratedTypeKeyword Keyword,
3321 NestedNameSpecifier *NNS,
3322 const IdentifierInfo *Name,
3323 unsigned NumArgs,
Jay Foad4ba2a172011-01-12 09:06:06 +00003324 const TemplateArgument *Args) const {
Douglas Gregoraa2187d2011-02-28 00:04:36 +00003325 assert((!NNS || NNS->isDependent()) &&
3326 "nested-name-specifier must be dependent");
Douglas Gregor17343172009-04-01 00:28:59 +00003327
Douglas Gregor789b1f62010-02-04 18:10:26 +00003328 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00003329 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3330 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003331
3332 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00003333 DependentTemplateSpecializationType *T
3334 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003335 if (T)
3336 return QualType(T, 0);
3337
John McCall33500952010-06-11 00:33:02 +00003338 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003339
John McCall33500952010-06-11 00:33:02 +00003340 ElaboratedTypeKeyword CanonKeyword = Keyword;
3341 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3342
3343 bool AnyNonCanonArgs = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003344 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCall33500952010-06-11 00:33:02 +00003345 for (unsigned I = 0; I != NumArgs; ++I) {
3346 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3347 if (!CanonArgs[I].structurallyEquals(Args[I]))
3348 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00003349 }
3350
John McCall33500952010-06-11 00:33:02 +00003351 QualType Canon;
3352 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3353 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3354 Name, NumArgs,
3355 CanonArgs.data());
3356
3357 // Find the insert position again.
3358 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3359 }
3360
3361 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3362 sizeof(TemplateArgument) * NumArgs),
3363 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00003364 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00003365 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00003366 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00003367 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00003368 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00003369}
3370
Douglas Gregorcded4f62011-01-14 17:04:44 +00003371QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikiedc84cd52013-02-20 22:23:23 +00003372 Optional<unsigned> NumExpansions) {
Douglas Gregor7536dd52010-12-20 02:24:11 +00003373 llvm::FoldingSetNodeID ID;
Douglas Gregorcded4f62011-01-14 17:04:44 +00003374 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003375
3376 assert(Pattern->containsUnexpandedParameterPack() &&
3377 "Pack expansions must expand one or more parameter packs");
3378 void *InsertPos = 0;
3379 PackExpansionType *T
3380 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3381 if (T)
3382 return QualType(T, 0);
3383
3384 QualType Canon;
3385 if (!Pattern.isCanonical()) {
Richard Smithd8672ef2012-07-16 00:20:35 +00003386 Canon = getCanonicalType(Pattern);
3387 // The canonical type might not contain an unexpanded parameter pack, if it
3388 // contains an alias template specialization which ignores one of its
3389 // parameters.
3390 if (Canon->containsUnexpandedParameterPack()) {
3391 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003392
Richard Smithd8672ef2012-07-16 00:20:35 +00003393 // Find the insert position again, in case we inserted an element into
3394 // PackExpansionTypes and invalidated our insert position.
3395 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3396 }
Douglas Gregor7536dd52010-12-20 02:24:11 +00003397 }
3398
Douglas Gregorcded4f62011-01-14 17:04:44 +00003399 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003400 Types.push_back(T);
3401 PackExpansionTypes.InsertNode(T, InsertPos);
3402 return QualType(T, 0);
3403}
3404
Chris Lattner88cb27a2008-04-07 04:56:42 +00003405/// CmpProtocolNames - Comparison predicate for sorting protocols
3406/// alphabetically.
3407static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3408 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003409 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00003410}
3411
John McCallc12c5bb2010-05-15 11:32:37 +00003412static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00003413 unsigned NumProtocols) {
3414 if (NumProtocols == 0) return true;
3415
Douglas Gregor61cc2962012-01-02 02:00:30 +00003416 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3417 return false;
3418
John McCall54e14c42009-10-22 22:37:11 +00003419 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregor61cc2962012-01-02 02:00:30 +00003420 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3421 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCall54e14c42009-10-22 22:37:11 +00003422 return false;
3423 return true;
3424}
3425
3426static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00003427 unsigned &NumProtocols) {
3428 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00003429
Chris Lattner88cb27a2008-04-07 04:56:42 +00003430 // Sort protocols, keyed by name.
3431 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3432
Douglas Gregor61cc2962012-01-02 02:00:30 +00003433 // Canonicalize.
3434 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3435 Protocols[I] = Protocols[I]->getCanonicalDecl();
3436
Chris Lattner88cb27a2008-04-07 04:56:42 +00003437 // Remove duplicates.
3438 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3439 NumProtocols = ProtocolsEnd-Protocols;
3440}
3441
John McCallc12c5bb2010-05-15 11:32:37 +00003442QualType ASTContext::getObjCObjectType(QualType BaseType,
3443 ObjCProtocolDecl * const *Protocols,
Jay Foad4ba2a172011-01-12 09:06:06 +00003444 unsigned NumProtocols) const {
John McCallc12c5bb2010-05-15 11:32:37 +00003445 // If the base type is an interface and there aren't any protocols
3446 // to add, then the interface type will do just fine.
3447 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3448 return BaseType;
3449
3450 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003451 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00003452 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003453 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00003454 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3455 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003456
John McCallc12c5bb2010-05-15 11:32:37 +00003457 // Build the canonical type, which has the canonical base type and
3458 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00003459 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00003460 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3461 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3462 if (!ProtocolsSorted) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003463 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer02379412010-04-27 17:12:11 +00003464 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00003465 unsigned UniqueCount = NumProtocols;
3466
John McCall54e14c42009-10-22 22:37:11 +00003467 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00003468 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3469 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00003470 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00003471 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3472 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00003473 }
3474
3475 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00003476 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3477 }
3478
3479 unsigned Size = sizeof(ObjCObjectTypeImpl);
3480 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3481 void *Mem = Allocate(Size, TypeAlignment);
3482 ObjCObjectTypeImpl *T =
3483 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3484
3485 Types.push_back(T);
3486 ObjCObjectTypes.InsertNode(T, InsertPos);
3487 return QualType(T, 0);
3488}
3489
3490/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3491/// the given object type.
Jay Foad4ba2a172011-01-12 09:06:06 +00003492QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCallc12c5bb2010-05-15 11:32:37 +00003493 llvm::FoldingSetNodeID ID;
3494 ObjCObjectPointerType::Profile(ID, ObjectT);
3495
3496 void *InsertPos = 0;
3497 if (ObjCObjectPointerType *QT =
3498 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3499 return QualType(QT, 0);
3500
3501 // Find the canonical object type.
3502 QualType Canonical;
3503 if (!ObjectT.isCanonical()) {
3504 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3505
3506 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00003507 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3508 }
3509
Douglas Gregorfd6a0882010-02-08 22:59:26 +00003510 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00003511 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3512 ObjCObjectPointerType *QType =
3513 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00003514
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003515 Types.push_back(QType);
3516 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00003517 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003518}
Chris Lattner88cb27a2008-04-07 04:56:42 +00003519
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003520/// getObjCInterfaceType - Return the unique reference to the type for the
3521/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregor0af55012011-12-16 03:12:41 +00003522QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3523 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003524 if (Decl->TypeForDecl)
3525 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00003526
Douglas Gregor0af55012011-12-16 03:12:41 +00003527 if (PrevDecl) {
3528 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3529 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3530 return QualType(PrevDecl->TypeForDecl, 0);
3531 }
3532
Douglas Gregor8d2dbbf2011-12-16 16:34:57 +00003533 // Prefer the definition, if there is one.
3534 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3535 Decl = Def;
3536
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003537 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3538 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3539 Decl->TypeForDecl = T;
3540 Types.push_back(T);
3541 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00003542}
3543
Douglas Gregor72564e72009-02-26 23:50:07 +00003544/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3545/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00003546/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00003547/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00003548/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00003549QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003550 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00003551 if (tofExpr->isTypeDependent()) {
3552 llvm::FoldingSetNodeID ID;
3553 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00003554
Douglas Gregorb1975722009-07-30 23:18:24 +00003555 void *InsertPos = 0;
3556 DependentTypeOfExprType *Canon
3557 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3558 if (Canon) {
3559 // We already have a "canonical" version of an identical, dependent
3560 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00003561 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00003562 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00003563 } else {
Douglas Gregorb1975722009-07-30 23:18:24 +00003564 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00003565 Canon
3566 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00003567 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3568 toe = Canon;
3569 }
3570 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003571 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00003572 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00003573 }
Steve Naroff9752f252007-08-01 18:02:17 +00003574 Types.push_back(toe);
3575 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00003576}
3577
Steve Naroff9752f252007-08-01 18:02:17 +00003578/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3579/// TypeOfType AST's. The only motivation to unique these nodes would be
3580/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00003581/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00003582/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00003583QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00003584 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00003585 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00003586 Types.push_back(tot);
3587 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00003588}
3589
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00003590
Anders Carlsson395b4752009-06-24 19:06:50 +00003591/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3592/// DecltypeType AST's. The only motivation to unique these nodes would be
3593/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00003594/// an issue. This doesn't effect the type checker, since it operates
David Blaikie39e02032011-11-06 22:28:03 +00003595/// on canonical types (which are always unique).
Douglas Gregorf8af9822012-02-12 18:42:33 +00003596QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003597 DecltypeType *dt;
Douglas Gregor561f8122011-07-01 01:22:09 +00003598
3599 // C++0x [temp.type]p2:
3600 // If an expression e involves a template parameter, decltype(e) denotes a
3601 // unique dependent type. Two such decltype-specifiers refer to the same
3602 // type only if their expressions are equivalent (14.5.6.1).
3603 if (e->isInstantiationDependent()) {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003604 llvm::FoldingSetNodeID ID;
3605 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00003606
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003607 void *InsertPos = 0;
3608 DependentDecltypeType *Canon
3609 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3610 if (Canon) {
3611 // We already have a "canonical" version of an equivalent, dependent
3612 // decltype type. Use that as our canonical type.
Richard Smith0d729102012-08-13 20:08:14 +00003613 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003614 QualType((DecltypeType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00003615 } else {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003616 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00003617 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003618 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3619 dt = Canon;
3620 }
3621 } else {
Douglas Gregorf8af9822012-02-12 18:42:33 +00003622 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3623 getCanonicalType(UnderlyingType));
Douglas Gregordd0257c2009-07-08 00:03:05 +00003624 }
Anders Carlsson395b4752009-06-24 19:06:50 +00003625 Types.push_back(dt);
3626 return QualType(dt, 0);
3627}
3628
Sean Huntca63c202011-05-24 22:41:36 +00003629/// getUnaryTransformationType - We don't unique these, since the memory
3630/// savings are minimal and these are rare.
3631QualType ASTContext::getUnaryTransformType(QualType BaseType,
3632 QualType UnderlyingType,
3633 UnaryTransformType::UTTKind Kind)
3634 const {
3635 UnaryTransformType *Ty =
Douglas Gregor69d97752011-05-25 17:51:54 +00003636 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3637 Kind,
3638 UnderlyingType->isDependentType() ?
Peter Collingbourne12fc4b02012-03-05 16:02:06 +00003639 QualType() : getCanonicalType(UnderlyingType));
Sean Huntca63c202011-05-24 22:41:36 +00003640 Types.push_back(Ty);
3641 return QualType(Ty, 0);
3642}
3643
Richard Smith60e141e2013-05-04 07:00:32 +00003644/// getAutoType - Return the uniqued reference to the 'auto' type which has been
3645/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3646/// canonical deduced-but-dependent 'auto' type.
3647QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
Manuel Klimek152b4e42013-08-22 12:12:24 +00003648 bool IsDependent) const {
3649 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
Richard Smith60e141e2013-05-04 07:00:32 +00003650 return getAutoDeductType();
Manuel Klimek152b4e42013-08-22 12:12:24 +00003651
Richard Smith60e141e2013-05-04 07:00:32 +00003652 // Look in the folding set for an existing type.
Richard Smith483b9f32011-02-21 20:05:19 +00003653 void *InsertPos = 0;
Richard Smith60e141e2013-05-04 07:00:32 +00003654 llvm::FoldingSetNodeID ID;
Manuel Klimek152b4e42013-08-22 12:12:24 +00003655 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
Richard Smith60e141e2013-05-04 07:00:32 +00003656 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3657 return QualType(AT, 0);
Richard Smith483b9f32011-02-21 20:05:19 +00003658
Richard Smitha2c36462013-04-26 16:15:35 +00003659 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smithdc7a4f52013-04-30 13:56:41 +00003660 IsDecltypeAuto,
Manuel Klimek152b4e42013-08-22 12:12:24 +00003661 IsDependent);
Richard Smith483b9f32011-02-21 20:05:19 +00003662 Types.push_back(AT);
3663 if (InsertPos)
3664 AutoTypes.InsertNode(AT, InsertPos);
3665 return QualType(AT, 0);
Richard Smith34b41d92011-02-20 03:19:35 +00003666}
3667
Eli Friedmanb001de72011-10-06 23:00:33 +00003668/// getAtomicType - Return the uniqued reference to the atomic type for
3669/// the given value type.
3670QualType ASTContext::getAtomicType(QualType T) const {
3671 // Unique pointers, to guarantee there is only one pointer of a particular
3672 // structure.
3673 llvm::FoldingSetNodeID ID;
3674 AtomicType::Profile(ID, T);
3675
3676 void *InsertPos = 0;
3677 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3678 return QualType(AT, 0);
3679
3680 // If the atomic value type isn't canonical, this won't be a canonical type
3681 // either, so fill in the canonical type field.
3682 QualType Canonical;
3683 if (!T.isCanonical()) {
3684 Canonical = getAtomicType(getCanonicalType(T));
3685
3686 // Get the new insert position for the node we care about.
3687 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3688 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3689 }
3690 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3691 Types.push_back(New);
3692 AtomicTypes.InsertNode(New, InsertPos);
3693 return QualType(New, 0);
3694}
3695
Richard Smithad762fc2011-04-14 22:09:26 +00003696/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3697QualType ASTContext::getAutoDeductType() const {
3698 if (AutoDeductTy.isNull())
Richard Smith60e141e2013-05-04 07:00:32 +00003699 AutoDeductTy = QualType(
3700 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
Manuel Klimek152b4e42013-08-22 12:12:24 +00003701 /*dependent*/false),
Richard Smith60e141e2013-05-04 07:00:32 +00003702 0);
Richard Smithad762fc2011-04-14 22:09:26 +00003703 return AutoDeductTy;
3704}
3705
3706/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3707QualType ASTContext::getAutoRRefDeductType() const {
3708 if (AutoRRefDeductTy.isNull())
3709 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3710 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3711 return AutoRRefDeductTy;
3712}
3713
Reid Spencer5f016e22007-07-11 17:01:13 +00003714/// getTagDeclType - Return the unique reference to the type for the
3715/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad4ba2a172011-01-12 09:06:06 +00003716QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenekd778f882007-11-26 21:16:01 +00003717 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00003718 // FIXME: What is the design on getTagDeclType when it requires casting
3719 // away const? mutable?
3720 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003721}
3722
Mike Stump1eb44332009-09-09 15:08:12 +00003723/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3724/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3725/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00003726CanQualType ASTContext::getSizeType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003727 return getFromTargetType(Target->getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00003728}
3729
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003730/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3731CanQualType ASTContext::getIntMaxType() const {
3732 return getFromTargetType(Target->getIntMaxType());
3733}
3734
3735/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3736CanQualType ASTContext::getUIntMaxType() const {
3737 return getFromTargetType(Target->getUIntMaxType());
3738}
3739
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00003740/// getSignedWCharType - Return the type of "signed wchar_t".
3741/// Used when in C++, as a GCC extension.
3742QualType ASTContext::getSignedWCharType() const {
3743 // FIXME: derive from "Target" ?
3744 return WCharTy;
3745}
3746
3747/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3748/// Used when in C++, as a GCC extension.
3749QualType ASTContext::getUnsignedWCharType() const {
3750 // FIXME: derive from "Target" ?
3751 return UnsignedIntTy;
3752}
3753
Enea Zaffanella9677eb82013-01-26 17:08:37 +00003754QualType ASTContext::getIntPtrType() const {
3755 return getFromTargetType(Target->getIntPtrType());
3756}
3757
3758QualType ASTContext::getUIntPtrType() const {
3759 return getCorrespondingUnsignedType(getIntPtrType());
3760}
3761
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003762/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattner8b9023b2007-07-13 03:05:23 +00003763/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3764QualType ASTContext::getPointerDiffType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003765 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00003766}
3767
Eli Friedman6902e412012-11-27 02:58:24 +00003768/// \brief Return the unique type for "pid_t" defined in
3769/// <sys/types.h>. We need this to compute the correct type for vfork().
3770QualType ASTContext::getProcessIDType() const {
3771 return getFromTargetType(Target->getProcessIDType());
3772}
3773
Chris Lattnere6327742008-04-02 05:18:44 +00003774//===----------------------------------------------------------------------===//
3775// Type Operators
3776//===----------------------------------------------------------------------===//
3777
Jay Foad4ba2a172011-01-12 09:06:06 +00003778CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCall54e14c42009-10-22 22:37:11 +00003779 // Push qualifiers into arrays, and then discard any remaining
3780 // qualifiers.
3781 T = getCanonicalType(T);
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003782 T = getVariableArrayDecayedType(T);
John McCall54e14c42009-10-22 22:37:11 +00003783 const Type *Ty = T.getTypePtr();
John McCall54e14c42009-10-22 22:37:11 +00003784 QualType Result;
3785 if (isa<ArrayType>(Ty)) {
3786 Result = getArrayDecayedType(QualType(Ty,0));
3787 } else if (isa<FunctionType>(Ty)) {
3788 Result = getPointerType(QualType(Ty, 0));
3789 } else {
3790 Result = QualType(Ty, 0);
3791 }
3792
3793 return CanQualType::CreateUnsafe(Result);
3794}
3795
John McCall62c28c82011-01-18 07:41:22 +00003796QualType ASTContext::getUnqualifiedArrayType(QualType type,
3797 Qualifiers &quals) {
3798 SplitQualType splitType = type.getSplitUnqualifiedType();
3799
3800 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3801 // the unqualified desugared type and then drops it on the floor.
3802 // We then have to strip that sugar back off with
3803 // getUnqualifiedDesugaredType(), which is silly.
3804 const ArrayType *AT =
John McCall200fa532012-02-08 00:46:36 +00003805 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall62c28c82011-01-18 07:41:22 +00003806
3807 // If we don't have an array, just use the results in splitType.
Douglas Gregor9dadd942010-05-17 18:45:21 +00003808 if (!AT) {
John McCall200fa532012-02-08 00:46:36 +00003809 quals = splitType.Quals;
3810 return QualType(splitType.Ty, 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003811 }
3812
John McCall62c28c82011-01-18 07:41:22 +00003813 // Otherwise, recurse on the array's element type.
3814 QualType elementType = AT->getElementType();
3815 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3816
3817 // If that didn't change the element type, AT has no qualifiers, so we
3818 // can just use the results in splitType.
3819 if (elementType == unqualElementType) {
3820 assert(quals.empty()); // from the recursive call
John McCall200fa532012-02-08 00:46:36 +00003821 quals = splitType.Quals;
3822 return QualType(splitType.Ty, 0);
John McCall62c28c82011-01-18 07:41:22 +00003823 }
3824
3825 // Otherwise, add in the qualifiers from the outermost type, then
3826 // build the type back up.
John McCall200fa532012-02-08 00:46:36 +00003827 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003828
Douglas Gregor9dadd942010-05-17 18:45:21 +00003829 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003830 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003831 CAT->getSizeModifier(), 0);
3832 }
3833
Douglas Gregor9dadd942010-05-17 18:45:21 +00003834 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003835 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003836 }
3837
Douglas Gregor9dadd942010-05-17 18:45:21 +00003838 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003839 return getVariableArrayType(unqualElementType,
John McCall3fa5cae2010-10-26 07:05:15 +00003840 VAT->getSizeExpr(),
Douglas Gregor9dadd942010-05-17 18:45:21 +00003841 VAT->getSizeModifier(),
3842 VAT->getIndexTypeCVRQualifiers(),
3843 VAT->getBracketsRange());
3844 }
3845
3846 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall62c28c82011-01-18 07:41:22 +00003847 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003848 DSAT->getSizeModifier(), 0,
3849 SourceRange());
3850}
3851
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003852/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3853/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3854/// they point to and return true. If T1 and T2 aren't pointer types
3855/// or pointer-to-member types, or if they are not similar at this
3856/// level, returns false and leaves T1 and T2 unchanged. Top-level
3857/// qualifiers on T1 and T2 are ignored. This function will typically
3858/// be called in a loop that successively "unwraps" pointer and
3859/// pointer-to-member types to compare them at each level.
3860bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3861 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3862 *T2PtrType = T2->getAs<PointerType>();
3863 if (T1PtrType && T2PtrType) {
3864 T1 = T1PtrType->getPointeeType();
3865 T2 = T2PtrType->getPointeeType();
3866 return true;
3867 }
3868
3869 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3870 *T2MPType = T2->getAs<MemberPointerType>();
3871 if (T1MPType && T2MPType &&
3872 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3873 QualType(T2MPType->getClass(), 0))) {
3874 T1 = T1MPType->getPointeeType();
3875 T2 = T2MPType->getPointeeType();
3876 return true;
3877 }
3878
David Blaikie4e4d0842012-03-11 07:00:24 +00003879 if (getLangOpts().ObjC1) {
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003880 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3881 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3882 if (T1OPType && T2OPType) {
3883 T1 = T1OPType->getPointeeType();
3884 T2 = T2OPType->getPointeeType();
3885 return true;
3886 }
3887 }
3888
3889 // FIXME: Block pointers, too?
3890
3891 return false;
3892}
3893
Jay Foad4ba2a172011-01-12 09:06:06 +00003894DeclarationNameInfo
3895ASTContext::getNameForTemplate(TemplateName Name,
3896 SourceLocation NameLoc) const {
John McCall14606042011-06-30 08:33:18 +00003897 switch (Name.getKind()) {
3898 case TemplateName::QualifiedTemplate:
3899 case TemplateName::Template:
Abramo Bagnara25777432010-08-11 22:01:17 +00003900 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCall14606042011-06-30 08:33:18 +00003901 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3902 NameLoc);
Abramo Bagnara25777432010-08-11 22:01:17 +00003903
John McCall14606042011-06-30 08:33:18 +00003904 case TemplateName::OverloadedTemplate: {
3905 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3906 // DNInfo work in progress: CHECKME: what about DNLoc?
3907 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3908 }
3909
3910 case TemplateName::DependentTemplate: {
3911 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnara25777432010-08-11 22:01:17 +00003912 DeclarationName DName;
John McCall80ad16f2009-11-24 18:42:40 +00003913 if (DTN->isIdentifier()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00003914 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3915 return DeclarationNameInfo(DName, NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003916 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00003917 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3918 // DNInfo work in progress: FIXME: source locations?
3919 DeclarationNameLoc DNLoc;
3920 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3921 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3922 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003923 }
3924 }
3925
John McCall14606042011-06-30 08:33:18 +00003926 case TemplateName::SubstTemplateTemplateParm: {
3927 SubstTemplateTemplateParmStorage *subst
3928 = Name.getAsSubstTemplateTemplateParm();
3929 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3930 NameLoc);
3931 }
3932
3933 case TemplateName::SubstTemplateTemplateParmPack: {
3934 SubstTemplateTemplateParmPackStorage *subst
3935 = Name.getAsSubstTemplateTemplateParmPack();
3936 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3937 NameLoc);
3938 }
3939 }
3940
3941 llvm_unreachable("bad template name kind!");
John McCall80ad16f2009-11-24 18:42:40 +00003942}
3943
Jay Foad4ba2a172011-01-12 09:06:06 +00003944TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCall14606042011-06-30 08:33:18 +00003945 switch (Name.getKind()) {
3946 case TemplateName::QualifiedTemplate:
3947 case TemplateName::Template: {
3948 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003949 if (TemplateTemplateParmDecl *TTP
John McCall14606042011-06-30 08:33:18 +00003950 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003951 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3952
3953 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00003954 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003955 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003956
John McCall14606042011-06-30 08:33:18 +00003957 case TemplateName::OverloadedTemplate:
3958 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump1eb44332009-09-09 15:08:12 +00003959
John McCall14606042011-06-30 08:33:18 +00003960 case TemplateName::DependentTemplate: {
3961 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3962 assert(DTN && "Non-dependent template names must refer to template decls.");
3963 return DTN->CanonicalTemplateName;
3964 }
3965
3966 case TemplateName::SubstTemplateTemplateParm: {
3967 SubstTemplateTemplateParmStorage *subst
3968 = Name.getAsSubstTemplateTemplateParm();
3969 return getCanonicalTemplateName(subst->getReplacement());
3970 }
3971
3972 case TemplateName::SubstTemplateTemplateParmPack: {
3973 SubstTemplateTemplateParmPackStorage *subst
3974 = Name.getAsSubstTemplateTemplateParmPack();
3975 TemplateTemplateParmDecl *canonParameter
3976 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3977 TemplateArgument canonArgPack
3978 = getCanonicalTemplateArgument(subst->getArgumentPack());
3979 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3980 }
3981 }
3982
3983 llvm_unreachable("bad template name!");
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003984}
3985
Douglas Gregordb0d4b72009-11-11 23:06:43 +00003986bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3987 X = getCanonicalTemplateName(X);
3988 Y = getCanonicalTemplateName(Y);
3989 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3990}
3991
Mike Stump1eb44332009-09-09 15:08:12 +00003992TemplateArgument
Jay Foad4ba2a172011-01-12 09:06:06 +00003993ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregor1275ae02009-07-28 23:00:59 +00003994 switch (Arg.getKind()) {
3995 case TemplateArgument::Null:
3996 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003997
Douglas Gregor1275ae02009-07-28 23:00:59 +00003998 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00003999 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00004000
Douglas Gregord2008e22012-04-06 22:40:38 +00004001 case TemplateArgument::Declaration: {
Eli Friedmand7a6b162012-09-26 02:36:12 +00004002 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
4003 return TemplateArgument(D, Arg.isDeclForReferenceParam());
Douglas Gregord2008e22012-04-06 22:40:38 +00004004 }
Mike Stump1eb44332009-09-09 15:08:12 +00004005
Eli Friedmand7a6b162012-09-26 02:36:12 +00004006 case TemplateArgument::NullPtr:
4007 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4008 /*isNullPtr*/true);
4009
Douglas Gregor788cd062009-11-11 01:00:40 +00004010 case TemplateArgument::Template:
4011 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregora7fc9012011-01-05 18:58:31 +00004012
4013 case TemplateArgument::TemplateExpansion:
4014 return TemplateArgument(getCanonicalTemplateName(
4015 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregor2be29f42011-01-14 23:41:42 +00004016 Arg.getNumTemplateExpansions());
Douglas Gregora7fc9012011-01-05 18:58:31 +00004017
Douglas Gregor1275ae02009-07-28 23:00:59 +00004018 case TemplateArgument::Integral:
Benjamin Kramer85524372012-06-07 15:09:51 +00004019 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00004020
Douglas Gregor1275ae02009-07-28 23:00:59 +00004021 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00004022 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00004023
Douglas Gregor1275ae02009-07-28 23:00:59 +00004024 case TemplateArgument::Pack: {
Douglas Gregor87dd6972010-12-20 16:52:59 +00004025 if (Arg.pack_size() == 0)
4026 return Arg;
4027
Douglas Gregor910f8002010-11-07 23:05:16 +00004028 TemplateArgument *CanonArgs
4029 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregor1275ae02009-07-28 23:00:59 +00004030 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004031 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00004032 AEnd = Arg.pack_end();
4033 A != AEnd; (void)++A, ++Idx)
4034 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00004035
Douglas Gregor910f8002010-11-07 23:05:16 +00004036 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregor1275ae02009-07-28 23:00:59 +00004037 }
4038 }
4039
4040 // Silence GCC warning
David Blaikieb219cfc2011-09-23 05:06:16 +00004041 llvm_unreachable("Unhandled template argument kind");
Douglas Gregor1275ae02009-07-28 23:00:59 +00004042}
4043
Douglas Gregord57959a2009-03-27 23:10:48 +00004044NestedNameSpecifier *
Jay Foad4ba2a172011-01-12 09:06:06 +00004045ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump1eb44332009-09-09 15:08:12 +00004046 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00004047 return 0;
4048
4049 switch (NNS->getKind()) {
4050 case NestedNameSpecifier::Identifier:
4051 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00004052 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00004053 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4054 NNS->getAsIdentifier());
4055
4056 case NestedNameSpecifier::Namespace:
4057 // A namespace is canonical; build a nested-name-specifier with
4058 // this namespace and no prefix.
Douglas Gregor14aba762011-02-24 02:36:08 +00004059 return NestedNameSpecifier::Create(*this, 0,
4060 NNS->getAsNamespace()->getOriginalNamespace());
4061
4062 case NestedNameSpecifier::NamespaceAlias:
4063 // A namespace is canonical; build a nested-name-specifier with
4064 // this namespace and no prefix.
4065 return NestedNameSpecifier::Create(*this, 0,
4066 NNS->getAsNamespaceAlias()->getNamespace()
4067 ->getOriginalNamespace());
Douglas Gregord57959a2009-03-27 23:10:48 +00004068
4069 case NestedNameSpecifier::TypeSpec:
4070 case NestedNameSpecifier::TypeSpecWithTemplate: {
4071 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor264bf662010-11-04 00:09:33 +00004072
4073 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4074 // break it apart into its prefix and identifier, then reconsititute those
4075 // as the canonical nested-name-specifier. This is required to canonicalize
4076 // a dependent nested-name-specifier involving typedefs of dependent-name
4077 // types, e.g.,
4078 // typedef typename T::type T1;
4079 // typedef typename T1::type T2;
Eli Friedman16412ef2012-03-03 04:09:56 +00004080 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4081 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor264bf662010-11-04 00:09:33 +00004082 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor264bf662010-11-04 00:09:33 +00004083
Eli Friedman16412ef2012-03-03 04:09:56 +00004084 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4085 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4086 // first place?
John McCall3b657512011-01-19 10:06:00 +00004087 return NestedNameSpecifier::Create(*this, 0, false,
4088 const_cast<Type*>(T.getTypePtr()));
Douglas Gregord57959a2009-03-27 23:10:48 +00004089 }
4090
4091 case NestedNameSpecifier::Global:
4092 // The global specifier is canonical and unique.
4093 return NNS;
4094 }
4095
David Blaikie7530c032012-01-17 06:56:22 +00004096 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregord57959a2009-03-27 23:10:48 +00004097}
4098
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004099
Jay Foad4ba2a172011-01-12 09:06:06 +00004100const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004101 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004102 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004103 // Handle the common positive case fast.
4104 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4105 return AT;
4106 }
Mike Stump1eb44332009-09-09 15:08:12 +00004107
John McCall0953e762009-09-24 19:53:00 +00004108 // Handle the common negative case fast.
John McCall3b657512011-01-19 10:06:00 +00004109 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004110 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004111
John McCall0953e762009-09-24 19:53:00 +00004112 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004113 // implements C99 6.7.3p8: "If the specification of an array type includes
4114 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00004115
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004116 // If we get here, we either have type qualifiers on the type, or we have
4117 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00004118 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00004119
John McCall3b657512011-01-19 10:06:00 +00004120 SplitQualType split = T.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00004121 Qualifiers qs = split.Quals;
Mike Stump1eb44332009-09-09 15:08:12 +00004122
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004123 // If we have a simple case, just return now.
John McCall200fa532012-02-08 00:46:36 +00004124 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall3b657512011-01-19 10:06:00 +00004125 if (ATy == 0 || qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004126 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00004127
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004128 // Otherwise, we have an array and we have qualifiers on it. Push the
4129 // qualifiers into the array element type and return a new array type.
John McCall3b657512011-01-19 10:06:00 +00004130 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump1eb44332009-09-09 15:08:12 +00004131
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004132 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4133 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4134 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004135 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004136 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4137 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4138 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004139 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00004140
Mike Stump1eb44332009-09-09 15:08:12 +00004141 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00004142 = dyn_cast<DependentSizedArrayType>(ATy))
4143 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00004144 getDependentSizedArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00004145 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00004146 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004147 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004148 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00004149
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004150 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004151 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00004152 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004153 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004154 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004155 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00004156}
4157
Abramo Bagnaraad9689f2012-05-17 12:44:05 +00004158QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner12df2462013-06-24 17:51:48 +00004159 if (T->isArrayType() || T->isFunctionType())
4160 return getDecayedType(T);
4161 return T;
Douglas Gregor79e6bd32011-07-12 04:42:08 +00004162}
4163
Abramo Bagnaraad9689f2012-05-17 12:44:05 +00004164QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor79e6bd32011-07-12 04:42:08 +00004165 T = getVariableArrayDecayedType(T);
4166 T = getAdjustedParameterType(T);
4167 return T.getUnqualifiedType();
4168}
4169
Chris Lattnere6327742008-04-02 05:18:44 +00004170/// getArrayDecayedType - Return the properly qualified result of decaying the
4171/// specified array type to a pointer. This operation is non-trivial when
4172/// handling typedefs etc. The canonical type of "T" must be an array type,
4173/// this returns a pointer to a properly qualified element of the array.
4174///
4175/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad4ba2a172011-01-12 09:06:06 +00004176QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004177 // Get the element type with 'getAsArrayType' so that we don't lose any
4178 // typedefs in the element type of the array. This also handles propagation
4179 // of type qualifiers from the array type into the element type if present
4180 // (C99 6.7.3p8).
4181 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4182 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00004183
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004184 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00004185
4186 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00004187 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00004188}
4189
John McCall3b657512011-01-19 10:06:00 +00004190QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4191 return getBaseElementType(array->getElementType());
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00004192}
4193
John McCall3b657512011-01-19 10:06:00 +00004194QualType ASTContext::getBaseElementType(QualType type) const {
4195 Qualifiers qs;
4196 while (true) {
4197 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00004198 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall3b657512011-01-19 10:06:00 +00004199 if (!array) break;
Mike Stump1eb44332009-09-09 15:08:12 +00004200
John McCall3b657512011-01-19 10:06:00 +00004201 type = array->getElementType();
John McCall200fa532012-02-08 00:46:36 +00004202 qs.addConsistentQualifiers(split.Quals);
John McCall3b657512011-01-19 10:06:00 +00004203 }
Mike Stump1eb44332009-09-09 15:08:12 +00004204
John McCall3b657512011-01-19 10:06:00 +00004205 return getQualifiedType(type, qs);
Anders Carlsson6183a992008-12-21 03:44:36 +00004206}
4207
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004208/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00004209uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004210ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4211 uint64_t ElementCount = 1;
4212 do {
4213 ElementCount *= CA->getSize().getZExtValue();
Richard Smithd5e83942012-12-06 03:04:50 +00004214 CA = dyn_cast_or_null<ConstantArrayType>(
4215 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004216 } while (CA);
4217 return ElementCount;
4218}
4219
Reid Spencer5f016e22007-07-11 17:01:13 +00004220/// getFloatingRank - Return a relative rank for floating point types.
4221/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00004222static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00004223 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00004224 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00004225
John McCall183700f2009-09-21 23:43:11 +00004226 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4227 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004228 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00004229 case BuiltinType::Half: return HalfRank;
Reid Spencer5f016e22007-07-11 17:01:13 +00004230 case BuiltinType::Float: return FloatRank;
4231 case BuiltinType::Double: return DoubleRank;
4232 case BuiltinType::LongDouble: return LongDoubleRank;
4233 }
4234}
4235
Mike Stump1eb44332009-09-09 15:08:12 +00004236/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4237/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00004238/// 'typeDomain' is a real floating point or complex type.
4239/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00004240QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4241 QualType Domain) const {
4242 FloatingRank EltRank = getFloatingRank(Size);
4243 if (Domain->isComplexType()) {
4244 switch (EltRank) {
David Blaikie561d3ab2012-01-17 02:30:50 +00004245 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Narofff1448a02007-08-27 01:27:54 +00004246 case FloatRank: return FloatComplexTy;
4247 case DoubleRank: return DoubleComplexTy;
4248 case LongDoubleRank: return LongDoubleComplexTy;
4249 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004250 }
Chris Lattner1361b112008-04-06 23:58:54 +00004251
4252 assert(Domain->isRealFloatingType() && "Unknown domain!");
4253 switch (EltRank) {
Joey Gouly19dbb202013-01-23 11:56:20 +00004254 case HalfRank: return HalfTy;
Chris Lattner1361b112008-04-06 23:58:54 +00004255 case FloatRank: return FloatTy;
4256 case DoubleRank: return DoubleTy;
4257 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00004258 }
David Blaikie561d3ab2012-01-17 02:30:50 +00004259 llvm_unreachable("getFloatingRank(): illegal value for rank");
Reid Spencer5f016e22007-07-11 17:01:13 +00004260}
4261
Chris Lattner7cfeb082008-04-06 23:55:33 +00004262/// getFloatingTypeOrder - Compare the rank of the two specified floating
4263/// point types, ignoring the domain of the type (i.e. 'double' ==
4264/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00004265/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00004266int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnera75cea32008-04-06 23:38:49 +00004267 FloatingRank LHSR = getFloatingRank(LHS);
4268 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004269
Chris Lattnera75cea32008-04-06 23:38:49 +00004270 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00004271 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00004272 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00004273 return 1;
4274 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00004275}
4276
Chris Lattnerf52ab252008-04-06 22:59:24 +00004277/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4278/// routine will assert if passed a built-in type that isn't an integer or enum,
4279/// or if it is not canonicalized.
John McCallf4c73712011-01-19 06:33:43 +00004280unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCall467b27b2009-10-22 20:10:53 +00004281 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00004282
Chris Lattnerf52ab252008-04-06 22:59:24 +00004283 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004284 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattner7cfeb082008-04-06 23:55:33 +00004285 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004286 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004287 case BuiltinType::Char_S:
4288 case BuiltinType::Char_U:
4289 case BuiltinType::SChar:
4290 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004291 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004292 case BuiltinType::Short:
4293 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004294 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004295 case BuiltinType::Int:
4296 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004297 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004298 case BuiltinType::Long:
4299 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004300 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004301 case BuiltinType::LongLong:
4302 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004303 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00004304 case BuiltinType::Int128:
4305 case BuiltinType::UInt128:
4306 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00004307 }
4308}
4309
Eli Friedman04e83572009-08-20 04:21:42 +00004310/// \brief Whether this is a promotable bitfield reference according
4311/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4312///
4313/// \returns the type this bit-field will promote to, or NULL if no
4314/// promotion occurs.
Jay Foad4ba2a172011-01-12 09:06:06 +00004315QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregorceafbde2010-05-24 20:13:53 +00004316 if (E->isTypeDependent() || E->isValueDependent())
4317 return QualType();
4318
John McCall993f43f2013-05-06 21:39:12 +00004319 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman04e83572009-08-20 04:21:42 +00004320 if (!Field)
4321 return QualType();
4322
4323 QualType FT = Field->getType();
4324
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004325 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman04e83572009-08-20 04:21:42 +00004326 uint64_t IntSize = getTypeSize(IntTy);
4327 // GCC extension compatibility: if the bit-field size is less than or equal
4328 // to the size of int, it gets promoted no matter what its type is.
4329 // For instance, unsigned long bf : 4 gets promoted to signed int.
4330 if (BitWidth < IntSize)
4331 return IntTy;
4332
4333 if (BitWidth == IntSize)
4334 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4335
4336 // Types bigger than int are not subject to promotions, and therefore act
4337 // like the base type.
4338 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4339 // is ridiculous.
4340 return QualType();
4341}
4342
Eli Friedmana95d7572009-08-19 07:44:53 +00004343/// getPromotedIntegerType - Returns the type that Promotable will
4344/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4345/// integer type.
Jay Foad4ba2a172011-01-12 09:06:06 +00004346QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedmana95d7572009-08-19 07:44:53 +00004347 assert(!Promotable.isNull());
4348 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00004349 if (const EnumType *ET = Promotable->getAs<EnumType>())
4350 return ET->getDecl()->getPromotionType();
Eli Friedman68a2dc42011-10-26 07:22:48 +00004351
4352 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4353 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4354 // (3.9.1) can be converted to a prvalue of the first of the following
4355 // types that can represent all the values of its underlying type:
4356 // int, unsigned int, long int, unsigned long int, long long int, or
4357 // unsigned long long int [...]
4358 // FIXME: Is there some better way to compute this?
4359 if (BT->getKind() == BuiltinType::WChar_S ||
4360 BT->getKind() == BuiltinType::WChar_U ||
4361 BT->getKind() == BuiltinType::Char16 ||
4362 BT->getKind() == BuiltinType::Char32) {
4363 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4364 uint64_t FromSize = getTypeSize(BT);
4365 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4366 LongLongTy, UnsignedLongLongTy };
4367 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4368 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4369 if (FromSize < ToSize ||
4370 (FromSize == ToSize &&
4371 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4372 return PromoteTypes[Idx];
4373 }
4374 llvm_unreachable("char type should fit into long long");
4375 }
4376 }
4377
4378 // At this point, we should have a signed or unsigned integer type.
Eli Friedmana95d7572009-08-19 07:44:53 +00004379 if (Promotable->isSignedIntegerType())
4380 return IntTy;
Eli Friedman5b64e772012-11-15 01:21:59 +00004381 uint64_t PromotableSize = getIntWidth(Promotable);
4382 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedmana95d7572009-08-19 07:44:53 +00004383 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4384 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4385}
4386
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00004387/// \brief Recurses in pointer/array types until it finds an objc retainable
4388/// type and returns its ownership.
4389Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4390 while (!T.isNull()) {
4391 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4392 return T.getObjCLifetime();
4393 if (T->isArrayType())
4394 T = getBaseElementType(T);
4395 else if (const PointerType *PT = T->getAs<PointerType>())
4396 T = PT->getPointeeType();
4397 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis28445f02011-07-01 23:01:46 +00004398 T = RT->getPointeeType();
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00004399 else
4400 break;
4401 }
4402
4403 return Qualifiers::OCL_None;
4404}
4405
Mike Stump1eb44332009-09-09 15:08:12 +00004406/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00004407/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00004408/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00004409int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCallf4c73712011-01-19 06:33:43 +00004410 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4411 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00004412 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004413
Chris Lattnerf52ab252008-04-06 22:59:24 +00004414 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4415 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00004416
Chris Lattner7cfeb082008-04-06 23:55:33 +00004417 unsigned LHSRank = getIntegerRank(LHSC);
4418 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00004419
Chris Lattner7cfeb082008-04-06 23:55:33 +00004420 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4421 if (LHSRank == RHSRank) return 0;
4422 return LHSRank > RHSRank ? 1 : -1;
4423 }
Mike Stump1eb44332009-09-09 15:08:12 +00004424
Chris Lattner7cfeb082008-04-06 23:55:33 +00004425 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4426 if (LHSUnsigned) {
4427 // If the unsigned [LHS] type is larger, return it.
4428 if (LHSRank >= RHSRank)
4429 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004430
Chris Lattner7cfeb082008-04-06 23:55:33 +00004431 // If the signed type can represent all values of the unsigned type, it
4432 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00004433 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00004434 return -1;
4435 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00004436
Chris Lattner7cfeb082008-04-06 23:55:33 +00004437 // If the unsigned [RHS] type is larger, return it.
4438 if (RHSRank >= LHSRank)
4439 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00004440
Chris Lattner7cfeb082008-04-06 23:55:33 +00004441 // If the signed type can represent all values of the unsigned type, it
4442 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00004443 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00004444 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00004445}
Anders Carlsson71993dd2007-08-17 05:31:46 +00004446
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004447static RecordDecl *
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004448CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
4449 DeclContext *DC, IdentifierInfo *Id) {
4450 SourceLocation Loc;
David Blaikie4e4d0842012-03-11 07:00:24 +00004451 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004452 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004453 else
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004454 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004455}
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004456
Mike Stump1eb44332009-09-09 15:08:12 +00004457// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00004458QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson71993dd2007-08-17 05:31:46 +00004459 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00004460 CFConstantStringTypeDecl =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004461 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004462 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00004463 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004464
Anders Carlssonf06273f2007-11-19 00:25:30 +00004465 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00004466
Anders Carlsson71993dd2007-08-17 05:31:46 +00004467 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00004468 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00004469 // int flags;
4470 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00004471 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00004472 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00004473 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00004474 FieldTypes[3] = LongTy;
4475
Anders Carlsson71993dd2007-08-17 05:31:46 +00004476 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00004477 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00004478 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004479 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00004480 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00004481 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00004482 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004483 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004484 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004485 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004486 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00004487 }
4488
Douglas Gregor838db382010-02-11 01:19:42 +00004489 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00004490 }
Mike Stump1eb44332009-09-09 15:08:12 +00004491
Anders Carlsson71993dd2007-08-17 05:31:46 +00004492 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00004493}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004494
Fariborz Jahanianf7992132013-01-04 18:45:40 +00004495QualType ASTContext::getObjCSuperType() const {
4496 if (ObjCSuperType.isNull()) {
4497 RecordDecl *ObjCSuperTypeDecl =
4498 CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get("objc_super"));
4499 TUDecl->addDecl(ObjCSuperTypeDecl);
4500 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4501 }
4502 return ObjCSuperType;
4503}
4504
Douglas Gregor319ac892009-04-23 22:29:11 +00004505void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004506 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00004507 assert(Rec && "Invalid CFConstantStringType");
4508 CFConstantStringTypeDecl = Rec->getDecl();
4509}
4510
Jay Foad4ba2a172011-01-12 09:06:06 +00004511QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpadaaad32009-10-20 02:12:22 +00004512 if (BlockDescriptorType)
4513 return getTagDeclType(BlockDescriptorType);
4514
4515 RecordDecl *T;
4516 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004517 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004518 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00004519 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00004520
4521 QualType FieldTypes[] = {
4522 UnsignedLongTy,
4523 UnsignedLongTy,
4524 };
4525
Craig Topper3aa29df2013-07-15 08:24:27 +00004526 static const char *const FieldNames[] = {
Mike Stumpadaaad32009-10-20 02:12:22 +00004527 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00004528 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00004529 };
4530
4531 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004532 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00004533 SourceLocation(),
4534 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004535 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00004536 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004537 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004538 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004539 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00004540 T->addDecl(Field);
4541 }
4542
Douglas Gregor838db382010-02-11 01:19:42 +00004543 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00004544
4545 BlockDescriptorType = T;
4546
4547 return getTagDeclType(BlockDescriptorType);
4548}
4549
Jay Foad4ba2a172011-01-12 09:06:06 +00004550QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stump083c25e2009-10-22 00:49:09 +00004551 if (BlockDescriptorExtendedType)
4552 return getTagDeclType(BlockDescriptorExtendedType);
4553
4554 RecordDecl *T;
4555 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004556 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004557 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00004558 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00004559
4560 QualType FieldTypes[] = {
4561 UnsignedLongTy,
4562 UnsignedLongTy,
4563 getPointerType(VoidPtrTy),
4564 getPointerType(VoidPtrTy)
4565 };
4566
Craig Topper3aa29df2013-07-15 08:24:27 +00004567 static const char *const FieldNames[] = {
Mike Stump083c25e2009-10-22 00:49:09 +00004568 "reserved",
4569 "Size",
4570 "CopyFuncPtr",
4571 "DestroyFuncPtr"
4572 };
4573
4574 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004575 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stump083c25e2009-10-22 00:49:09 +00004576 SourceLocation(),
4577 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004578 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00004579 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004580 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004581 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004582 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00004583 T->addDecl(Field);
4584 }
4585
Douglas Gregor838db382010-02-11 01:19:42 +00004586 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00004587
4588 BlockDescriptorExtendedType = T;
4589
4590 return getTagDeclType(BlockDescriptorExtendedType);
4591}
4592
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00004593/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4594/// requires copy/dispose. Note that this must match the logic
4595/// in buildByrefHelpers.
4596bool ASTContext::BlockRequiresCopying(QualType Ty,
4597 const VarDecl *D) {
4598 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4599 const Expr *copyExpr = getBlockVarCopyInits(D);
4600 if (!copyExpr && record->hasTrivialDestructor()) return false;
4601
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004602 return true;
Fariborz Jahaniane38be612010-11-17 00:21:28 +00004603 }
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00004604
4605 if (!Ty->isObjCRetainableType()) return false;
4606
4607 Qualifiers qs = Ty.getQualifiers();
4608
4609 // If we have lifetime, that dominates.
4610 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4611 assert(getLangOpts().ObjCAutoRefCount);
4612
4613 switch (lifetime) {
4614 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4615
4616 // These are just bits as far as the runtime is concerned.
4617 case Qualifiers::OCL_ExplicitNone:
4618 case Qualifiers::OCL_Autoreleasing:
4619 return false;
4620
4621 // Tell the runtime that this is ARC __weak, called by the
4622 // byref routines.
4623 case Qualifiers::OCL_Weak:
4624 // ARC __strong __block variables need to be retained.
4625 case Qualifiers::OCL_Strong:
4626 return true;
4627 }
4628 llvm_unreachable("fell out of lifetime switch!");
4629 }
4630 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4631 Ty->isObjCObjectPointerType());
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004632}
4633
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00004634bool ASTContext::getByrefLifetime(QualType Ty,
4635 Qualifiers::ObjCLifetime &LifeTime,
4636 bool &HasByrefExtendedLayout) const {
4637
4638 if (!getLangOpts().ObjC1 ||
4639 getLangOpts().getGC() != LangOptions::NonGC)
4640 return false;
4641
4642 HasByrefExtendedLayout = false;
Fariborz Jahanian34db84f2012-12-11 19:58:01 +00004643 if (Ty->isRecordType()) {
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00004644 HasByrefExtendedLayout = true;
4645 LifeTime = Qualifiers::OCL_None;
4646 }
4647 else if (getLangOpts().ObjCAutoRefCount)
4648 LifeTime = Ty.getObjCLifetime();
4649 // MRR.
4650 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4651 LifeTime = Qualifiers::OCL_ExplicitNone;
4652 else
4653 LifeTime = Qualifiers::OCL_None;
4654 return true;
4655}
4656
Douglas Gregore97179c2011-09-08 01:46:34 +00004657TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4658 if (!ObjCInstanceTypeDecl)
4659 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4660 getTranslationUnitDecl(),
4661 SourceLocation(),
4662 SourceLocation(),
4663 &Idents.get("instancetype"),
4664 getTrivialTypeSourceInfo(getObjCIdType()));
4665 return ObjCInstanceTypeDecl;
4666}
4667
Anders Carlssone8c49532007-10-29 06:33:42 +00004668// This returns true if a type has been typedefed to BOOL:
4669// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00004670static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00004671 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00004672 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4673 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00004674
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004675 return false;
4676}
4677
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004678/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004679/// purpose.
Jay Foad4ba2a172011-01-12 09:06:06 +00004680CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregorf968d832011-05-27 01:19:52 +00004681 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4682 return CharUnits::Zero();
4683
Ken Dyck199c3d62010-01-11 17:06:35 +00004684 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00004685
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004686 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004687 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004688 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004689 // Treat arrays as pointers, since that's how they're passed in.
4690 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004691 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004692 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00004693}
4694
4695static inline
4696std::string charUnitsToString(const CharUnits &CU) {
4697 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004698}
4699
John McCall6b5a61b2011-02-07 10:33:21 +00004700/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00004701/// declaration.
John McCall6b5a61b2011-02-07 10:33:21 +00004702std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4703 std::string S;
4704
David Chisnall5e530af2009-11-17 19:33:30 +00004705 const BlockDecl *Decl = Expr->getBlockDecl();
4706 QualType BlockTy =
4707 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4708 // Encode result type.
Fariborz Jahanian3d145f62012-11-15 19:02:45 +00004709 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian06cffc02012-11-14 23:11:38 +00004710 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None,
4711 BlockTy->getAs<FunctionType>()->getResultType(),
4712 S, true /*Extended*/);
4713 else
4714 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(),
4715 S);
David Chisnall5e530af2009-11-17 19:33:30 +00004716 // Compute size of all parameters.
4717 // Start with computing size of a pointer in number of bytes.
4718 // FIXME: There might(should) be a better way of doing this computation!
4719 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004720 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4721 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00004722 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00004723 E = Decl->param_end(); PI != E; ++PI) {
4724 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004725 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahanian075a5432012-06-30 00:48:59 +00004726 if (sz.isZero())
4727 continue;
Ken Dyck199c3d62010-01-11 17:06:35 +00004728 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00004729 ParmOffset += sz;
4730 }
4731 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00004732 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00004733 // Block pointer and offset.
4734 S += "@?0";
David Chisnall5e530af2009-11-17 19:33:30 +00004735
4736 // Argument types.
4737 ParmOffset = PtrSize;
4738 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4739 Decl->param_end(); PI != E; ++PI) {
4740 ParmVarDecl *PVDecl = *PI;
4741 QualType PType = PVDecl->getOriginalType();
4742 if (const ArrayType *AT =
4743 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4744 // Use array's original type only if it has known number of
4745 // elements.
4746 if (!isa<ConstantArrayType>(AT))
4747 PType = PVDecl->getType();
4748 } else if (PType->isFunctionType())
4749 PType = PVDecl->getType();
Fariborz Jahanian3d145f62012-11-15 19:02:45 +00004750 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian06cffc02012-11-14 23:11:38 +00004751 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4752 S, true /*Extended*/);
4753 else
4754 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00004755 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004756 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00004757 }
John McCall6b5a61b2011-02-07 10:33:21 +00004758
4759 return S;
David Chisnall5e530af2009-11-17 19:33:30 +00004760}
4761
Douglas Gregorf968d832011-05-27 01:19:52 +00004762bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall5389f482010-12-30 14:05:53 +00004763 std::string& S) {
4764 // Encode result type.
4765 getObjCEncodingForType(Decl->getResultType(), S);
4766 CharUnits ParmOffset;
4767 // Compute size of all parameters.
4768 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4769 E = Decl->param_end(); PI != E; ++PI) {
4770 QualType PType = (*PI)->getType();
4771 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004772 if (sz.isZero())
Fariborz Jahanian7e68ba52012-06-29 22:54:56 +00004773 continue;
4774
David Chisnall5389f482010-12-30 14:05:53 +00004775 assert (sz.isPositive() &&
Douglas Gregorf968d832011-05-27 01:19:52 +00004776 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall5389f482010-12-30 14:05:53 +00004777 ParmOffset += sz;
4778 }
4779 S += charUnitsToString(ParmOffset);
4780 ParmOffset = CharUnits::Zero();
4781
4782 // Argument types.
4783 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4784 E = Decl->param_end(); PI != E; ++PI) {
4785 ParmVarDecl *PVDecl = *PI;
4786 QualType PType = PVDecl->getOriginalType();
4787 if (const ArrayType *AT =
4788 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4789 // Use array's original type only if it has known number of
4790 // elements.
4791 if (!isa<ConstantArrayType>(AT))
4792 PType = PVDecl->getType();
4793 } else if (PType->isFunctionType())
4794 PType = PVDecl->getType();
4795 getObjCEncodingForType(PType, S);
4796 S += charUnitsToString(ParmOffset);
4797 ParmOffset += getObjCEncodingTypeSize(PType);
4798 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004799
4800 return false;
David Chisnall5389f482010-12-30 14:05:53 +00004801}
4802
Bob Wilsondc8dab62011-11-30 01:57:58 +00004803/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4804/// method parameter or return type. If Extended, include class names and
4805/// block object types.
4806void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4807 QualType T, std::string& S,
4808 bool Extended) const {
4809 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4810 getObjCEncodingForTypeQualifier(QT, S);
4811 // Encode parameter type.
4812 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4813 true /*OutermostType*/,
4814 false /*EncodingProperty*/,
4815 false /*StructField*/,
4816 Extended /*EncodeBlockParameters*/,
4817 Extended /*EncodeClassNames*/);
4818}
4819
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004820/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004821/// declaration.
Douglas Gregorf968d832011-05-27 01:19:52 +00004822bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilsondc8dab62011-11-30 01:57:58 +00004823 std::string& S,
4824 bool Extended) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004825 // FIXME: This is not very efficient.
Bob Wilsondc8dab62011-11-30 01:57:58 +00004826 // Encode return type.
4827 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4828 Decl->getResultType(), S, Extended);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004829 // Compute size of all parameters.
4830 // Start with computing size of a pointer in number of bytes.
4831 // FIXME: There might(should) be a better way of doing this computation!
4832 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004833 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004834 // The first two arguments (self and _cmd) are pointers; account for
4835 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00004836 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004837 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004838 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00004839 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004840 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004841 if (sz.isZero())
Fariborz Jahanian7e68ba52012-06-29 22:54:56 +00004842 continue;
4843
Ken Dyck199c3d62010-01-11 17:06:35 +00004844 assert (sz.isPositive() &&
4845 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004846 ParmOffset += sz;
4847 }
Ken Dyck199c3d62010-01-11 17:06:35 +00004848 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004849 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00004850 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00004851
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004852 // Argument types.
4853 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004854 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004855 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004856 const ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00004857 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00004858 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00004859 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4860 // Use array's original type only if it has known number of
4861 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00004862 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00004863 PType = PVDecl->getType();
4864 } else if (PType->isFunctionType())
4865 PType = PVDecl->getType();
Bob Wilsondc8dab62011-11-30 01:57:58 +00004866 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4867 PType, S, Extended);
Ken Dyck199c3d62010-01-11 17:06:35 +00004868 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004869 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004870 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004871
4872 return false;
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004873}
4874
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004875/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004876/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004877/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4878/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00004879/// Property attributes are stored as a comma-delimited C string. The simple
4880/// attributes readonly and bycopy are encoded as single characters. The
4881/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4882/// encoded as single characters, followed by an identifier. Property types
4883/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004884/// these attributes are defined by the following enumeration:
4885/// @code
4886/// enum PropertyAttributes {
4887/// kPropertyReadOnly = 'R', // property is read-only.
4888/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4889/// kPropertyByref = '&', // property is a reference to the value last assigned
4890/// kPropertyDynamic = 'D', // property is dynamic
4891/// kPropertyGetter = 'G', // followed by getter selector name
4892/// kPropertySetter = 'S', // followed by setter selector name
4893/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson0d4cb852012-03-22 17:48:02 +00004894/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004895/// kPropertyWeak = 'W' // 'weak' property
4896/// kPropertyStrong = 'P' // property GC'able
4897/// kPropertyNonAtomic = 'N' // property non-atomic
4898/// };
4899/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00004900void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004901 const Decl *Container,
Jay Foad4ba2a172011-01-12 09:06:06 +00004902 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004903 // Collect information from the property implementation decl(s).
4904 bool Dynamic = false;
4905 ObjCPropertyImplDecl *SynthesizePID = 0;
4906
4907 // FIXME: Duplicated code due to poor abstraction.
4908 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00004909 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004910 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4911 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004912 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004913 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00004914 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004915 if (PID->getPropertyDecl() == PD) {
4916 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4917 Dynamic = true;
4918 } else {
4919 SynthesizePID = PID;
4920 }
4921 }
4922 }
4923 } else {
Chris Lattner61710852008-10-05 17:34:18 +00004924 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004925 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004926 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004927 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00004928 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004929 if (PID->getPropertyDecl() == PD) {
4930 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4931 Dynamic = true;
4932 } else {
4933 SynthesizePID = PID;
4934 }
4935 }
Mike Stump1eb44332009-09-09 15:08:12 +00004936 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004937 }
4938 }
4939
4940 // FIXME: This is not very efficient.
4941 S = "T";
4942
4943 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004944 // GCC has some special rules regarding encoding of properties which
4945 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00004946 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004947 true /* outermost type */,
4948 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004949
4950 if (PD->isReadOnly()) {
4951 S += ",R";
Nico Weberd7ceab32013-05-08 23:47:40 +00004952 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
4953 S += ",C";
4954 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
4955 S += ",&";
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004956 } else {
4957 switch (PD->getSetterKind()) {
4958 case ObjCPropertyDecl::Assign: break;
4959 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00004960 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian3a02b442011-08-12 20:47:08 +00004961 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004962 }
4963 }
4964
4965 // It really isn't clear at all what this means, since properties
4966 // are "dynamic by default".
4967 if (Dynamic)
4968 S += ",D";
4969
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004970 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4971 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00004972
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004973 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4974 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004975 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004976 }
4977
4978 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4979 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004980 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004981 }
4982
4983 if (SynthesizePID) {
4984 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4985 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00004986 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004987 }
4988
4989 // FIXME: OBJCGC: weak & strong
4990}
4991
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004992/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00004993/// Another legacy compatibility encoding: 32-bit longs are encoded as
4994/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004995/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4996///
4997void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00004998 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00004999 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad4ba2a172011-01-12 09:06:06 +00005000 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005001 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00005002 else
Jay Foad4ba2a172011-01-12 09:06:06 +00005003 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005004 PointeeTy = IntTy;
5005 }
5006 }
5007}
5008
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00005009void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad4ba2a172011-01-12 09:06:06 +00005010 const FieldDecl *Field) const {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00005011 // We follow the behavior of gcc, expanding structures which are
5012 // directly pointed to, and expanding embedded structures. Note that
5013 // these rules are sufficient to prevent recursive encoding of the
5014 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00005015 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00005016 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00005017}
5018
John McCall3624e9e2012-12-20 02:45:14 +00005019static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5020 BuiltinType::Kind kind) {
5021 switch (kind) {
David Chisnall64fd7e82010-06-04 01:10:52 +00005022 case BuiltinType::Void: return 'v';
5023 case BuiltinType::Bool: return 'B';
5024 case BuiltinType::Char_U:
5025 case BuiltinType::UChar: return 'C';
John McCall3624e9e2012-12-20 02:45:14 +00005026 case BuiltinType::Char16:
David Chisnall64fd7e82010-06-04 01:10:52 +00005027 case BuiltinType::UShort: return 'S';
John McCall3624e9e2012-12-20 02:45:14 +00005028 case BuiltinType::Char32:
David Chisnall64fd7e82010-06-04 01:10:52 +00005029 case BuiltinType::UInt: return 'I';
5030 case BuiltinType::ULong:
John McCall3624e9e2012-12-20 02:45:14 +00005031 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnall64fd7e82010-06-04 01:10:52 +00005032 case BuiltinType::UInt128: return 'T';
5033 case BuiltinType::ULongLong: return 'Q';
5034 case BuiltinType::Char_S:
5035 case BuiltinType::SChar: return 'c';
5036 case BuiltinType::Short: return 's';
Chris Lattner3f59c972010-12-25 23:25:43 +00005037 case BuiltinType::WChar_S:
5038 case BuiltinType::WChar_U:
David Chisnall64fd7e82010-06-04 01:10:52 +00005039 case BuiltinType::Int: return 'i';
5040 case BuiltinType::Long:
John McCall3624e9e2012-12-20 02:45:14 +00005041 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnall64fd7e82010-06-04 01:10:52 +00005042 case BuiltinType::LongLong: return 'q';
5043 case BuiltinType::Int128: return 't';
5044 case BuiltinType::Float: return 'f';
5045 case BuiltinType::Double: return 'd';
Daniel Dunbar3a0be842010-10-11 21:13:48 +00005046 case BuiltinType::LongDouble: return 'D';
John McCall3624e9e2012-12-20 02:45:14 +00005047 case BuiltinType::NullPtr: return '*'; // like char*
5048
5049 case BuiltinType::Half:
5050 // FIXME: potentially need @encodes for these!
5051 return ' ';
5052
5053 case BuiltinType::ObjCId:
5054 case BuiltinType::ObjCClass:
5055 case BuiltinType::ObjCSel:
5056 llvm_unreachable("@encoding ObjC primitive type");
5057
5058 // OpenCL and placeholder types don't need @encodings.
5059 case BuiltinType::OCLImage1d:
5060 case BuiltinType::OCLImage1dArray:
5061 case BuiltinType::OCLImage1dBuffer:
5062 case BuiltinType::OCLImage2d:
5063 case BuiltinType::OCLImage2dArray:
5064 case BuiltinType::OCLImage3d:
Guy Benyeie6b9d802013-01-20 12:31:11 +00005065 case BuiltinType::OCLEvent:
Guy Benyei21f18c42013-02-07 10:55:47 +00005066 case BuiltinType::OCLSampler:
John McCall3624e9e2012-12-20 02:45:14 +00005067 case BuiltinType::Dependent:
5068#define BUILTIN_TYPE(KIND, ID)
5069#define PLACEHOLDER_TYPE(KIND, ID) \
5070 case BuiltinType::KIND:
5071#include "clang/AST/BuiltinTypes.def"
5072 llvm_unreachable("invalid builtin type for @encode");
David Chisnall64fd7e82010-06-04 01:10:52 +00005073 }
David Blaikie719e53f2013-01-09 17:48:41 +00005074 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnall64fd7e82010-06-04 01:10:52 +00005075}
5076
Douglas Gregor5471bc82011-09-08 17:18:35 +00005077static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5078 EnumDecl *Enum = ET->getDecl();
5079
5080 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5081 if (!Enum->isFixed())
5082 return 'i';
5083
5084 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall3624e9e2012-12-20 02:45:14 +00005085 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5086 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor5471bc82011-09-08 17:18:35 +00005087}
5088
Jay Foad4ba2a172011-01-12 09:06:06 +00005089static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00005090 QualType T, const FieldDecl *FD) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005091 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00005092 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00005093 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5094 // The GNU runtime requires more information; bitfields are encoded as b,
5095 // then the offset (in bits) of the first element, then the type of the
5096 // bitfield, then the size in bits. For example, in this structure:
5097 //
5098 // struct
5099 // {
5100 // int integer;
5101 // int flags:2;
5102 // };
5103 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5104 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5105 // information is not especially sensible, but we're stuck with it for
5106 // compatibility with GCC, although providing it breaks anything that
5107 // actually uses runtime introspection and wants to work on both runtimes...
John McCall260611a2012-06-20 06:18:46 +00005108 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnall64fd7e82010-06-04 01:10:52 +00005109 const RecordDecl *RD = FD->getParent();
5110 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedman82905742011-07-07 01:54:01 +00005111 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor5471bc82011-09-08 17:18:35 +00005112 if (const EnumType *ET = T->getAs<EnumType>())
5113 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall3624e9e2012-12-20 02:45:14 +00005114 else {
5115 const BuiltinType *BT = T->castAs<BuiltinType>();
5116 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5117 }
David Chisnall64fd7e82010-06-04 01:10:52 +00005118 }
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005119 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00005120}
5121
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00005122// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00005123void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5124 bool ExpandPointedToStructures,
5125 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00005126 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00005127 bool OutermostType,
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005128 bool EncodingProperty,
Bob Wilsondc8dab62011-11-30 01:57:58 +00005129 bool StructField,
5130 bool EncodeBlockParameters,
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005131 bool EncodeClassNames,
5132 bool EncodePointerToObjCTypedef) const {
John McCall3624e9e2012-12-20 02:45:14 +00005133 CanQualType CT = getCanonicalType(T);
5134 switch (CT->getTypeClass()) {
5135 case Type::Builtin:
5136 case Type::Enum:
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005137 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00005138 return EncodeBitField(this, S, T, FD);
John McCall3624e9e2012-12-20 02:45:14 +00005139 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5140 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5141 else
5142 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005143 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005144
John McCall3624e9e2012-12-20 02:45:14 +00005145 case Type::Complex: {
5146 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlssonc612f7b2009-04-09 21:55:45 +00005147 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00005148 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00005149 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005150 return;
5151 }
John McCall3624e9e2012-12-20 02:45:14 +00005152
5153 case Type::Atomic: {
5154 const AtomicType *AT = T->castAs<AtomicType>();
5155 S += 'A';
5156 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, 0,
5157 false, false);
5158 return;
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00005159 }
John McCall3624e9e2012-12-20 02:45:14 +00005160
5161 // encoding for pointer or reference types.
5162 case Type::Pointer:
5163 case Type::LValueReference:
5164 case Type::RValueReference: {
5165 QualType PointeeTy;
5166 if (isa<PointerType>(CT)) {
5167 const PointerType *PT = T->castAs<PointerType>();
5168 if (PT->isObjCSelType()) {
5169 S += ':';
5170 return;
5171 }
5172 PointeeTy = PT->getPointeeType();
5173 } else {
5174 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5175 }
5176
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005177 bool isReadOnly = false;
5178 // For historical/compatibility reasons, the read-only qualifier of the
5179 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5180 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00005181 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00005182 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005183 if (OutermostType && T.isConstQualified()) {
5184 isReadOnly = true;
5185 S += 'r';
5186 }
Mike Stump9fdbab32009-07-31 02:02:20 +00005187 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005188 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00005189 while (P->getAs<PointerType>())
5190 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005191 if (P.isConstQualified()) {
5192 isReadOnly = true;
5193 S += 'r';
5194 }
5195 }
5196 if (isReadOnly) {
5197 // Another legacy compatibility encoding. Some ObjC qualifier and type
5198 // combinations need to be rearranged.
5199 // Rewrite "in const" from "nr" to "rn"
Chris Lattner5f9e2722011-07-23 10:55:15 +00005200 if (StringRef(S).endswith("nr"))
Benjamin Kramer02379412010-04-27 17:12:11 +00005201 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005202 }
Mike Stump1eb44332009-09-09 15:08:12 +00005203
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005204 if (PointeeTy->isCharType()) {
5205 // char pointer types should be encoded as '*' unless it is a
5206 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00005207 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005208 S += '*';
5209 return;
5210 }
Ted Kremenek6217b802009-07-29 21:53:49 +00005211 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00005212 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5213 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5214 S += '#';
5215 return;
5216 }
5217 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5218 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5219 S += '@';
5220 return;
5221 }
5222 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005223 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005224 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005225 getLegacyIntegralTypeEncoding(PointeeTy);
5226
Mike Stump1eb44332009-09-09 15:08:12 +00005227 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005228 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005229 return;
5230 }
John McCall3624e9e2012-12-20 02:45:14 +00005231
5232 case Type::ConstantArray:
5233 case Type::IncompleteArray:
5234 case Type::VariableArray: {
5235 const ArrayType *AT = cast<ArrayType>(CT);
5236
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005237 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlsson559a8332009-02-22 01:38:57 +00005238 // Incomplete arrays are encoded as a pointer to the array element.
5239 S += '^';
5240
Mike Stump1eb44332009-09-09 15:08:12 +00005241 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00005242 false, ExpandStructures, FD);
5243 } else {
5244 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00005245
Fariborz Jahanian48eff6c2013-06-04 16:04:37 +00005246 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5247 S += llvm::utostr(CAT->getSize().getZExtValue());
5248 else {
Anders Carlsson559a8332009-02-22 01:38:57 +00005249 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005250 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5251 "Unknown array type!");
Anders Carlsson559a8332009-02-22 01:38:57 +00005252 S += '0';
5253 }
Mike Stump1eb44332009-09-09 15:08:12 +00005254
5255 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00005256 false, ExpandStructures, FD);
5257 S += ']';
5258 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005259 return;
5260 }
Mike Stump1eb44332009-09-09 15:08:12 +00005261
John McCall3624e9e2012-12-20 02:45:14 +00005262 case Type::FunctionNoProto:
5263 case Type::FunctionProto:
Anders Carlssonc0a87b72007-10-30 00:06:20 +00005264 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005265 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005266
John McCall3624e9e2012-12-20 02:45:14 +00005267 case Type::Record: {
5268 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005269 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00005270 // Anonymous structures print as '?'
5271 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5272 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00005273 if (ClassTemplateSpecializationDecl *Spec
5274 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5275 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer5eada842013-02-22 15:46:01 +00005276 llvm::raw_string_ostream OS(S);
5277 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor910f8002010-11-07 23:05:16 +00005278 TemplateArgs.data(),
5279 TemplateArgs.size(),
Douglas Gregor30c42402011-09-27 22:38:19 +00005280 (*this).getPrintingPolicy());
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00005281 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00005282 } else {
5283 S += '?';
5284 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00005285 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00005286 S += '=';
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005287 if (!RDecl->isUnion()) {
5288 getObjCEncodingForStructureImpl(RDecl, S, FD);
5289 } else {
5290 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5291 FieldEnd = RDecl->field_end();
5292 Field != FieldEnd; ++Field) {
5293 if (FD) {
5294 S += '"';
5295 S += Field->getNameAsString();
5296 S += '"';
5297 }
Mike Stump1eb44332009-09-09 15:08:12 +00005298
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005299 // Special case bit-fields.
5300 if (Field->isBitField()) {
5301 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie581deb32012-06-06 20:45:41 +00005302 *Field);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005303 } else {
5304 QualType qt = Field->getType();
5305 getLegacyIntegralTypeEncoding(qt);
5306 getObjCEncodingForTypeImpl(qt, S, false, true,
5307 FD, /*OutermostType*/false,
5308 /*EncodingProperty*/false,
5309 /*StructField*/true);
5310 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005311 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00005312 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00005313 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005314 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005315 return;
5316 }
Mike Stump1eb44332009-09-09 15:08:12 +00005317
John McCall3624e9e2012-12-20 02:45:14 +00005318 case Type::BlockPointer: {
5319 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff21a98b12009-02-02 18:24:29 +00005320 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilsondc8dab62011-11-30 01:57:58 +00005321 if (EncodeBlockParameters) {
John McCall3624e9e2012-12-20 02:45:14 +00005322 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilsondc8dab62011-11-30 01:57:58 +00005323
5324 S += '<';
5325 // Block return type
5326 getObjCEncodingForTypeImpl(FT->getResultType(), S,
5327 ExpandPointedToStructures, ExpandStructures,
5328 FD,
5329 false /* OutermostType */,
5330 EncodingProperty,
5331 false /* StructField */,
5332 EncodeBlockParameters,
5333 EncodeClassNames);
5334 // Block self
5335 S += "@?";
5336 // Block parameters
5337 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
5338 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
5339 E = FPT->arg_type_end(); I && (I != E); ++I) {
5340 getObjCEncodingForTypeImpl(*I, S,
5341 ExpandPointedToStructures,
5342 ExpandStructures,
5343 FD,
5344 false /* OutermostType */,
5345 EncodingProperty,
5346 false /* StructField */,
5347 EncodeBlockParameters,
5348 EncodeClassNames);
5349 }
5350 }
5351 S += '>';
5352 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005353 return;
5354 }
Mike Stump1eb44332009-09-09 15:08:12 +00005355
John McCall3624e9e2012-12-20 02:45:14 +00005356 case Type::ObjCObject:
5357 case Type::ObjCInterface: {
5358 // Ignore protocol qualifiers when mangling at this level.
5359 T = T->castAs<ObjCObjectType>()->getBaseType();
John McCallc12c5bb2010-05-15 11:32:37 +00005360
John McCall3624e9e2012-12-20 02:45:14 +00005361 // The assumption seems to be that this assert will succeed
5362 // because nested levels will have filtered out 'id' and 'Class'.
5363 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005364 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00005365 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005366 S += '{';
5367 const IdentifierInfo *II = OI->getIdentifier();
5368 S += II->getName();
5369 S += '=';
Jordy Rosedb8264e2011-07-22 02:08:32 +00005370 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00005371 DeepCollectObjCIvars(OI, true, Ivars);
5372 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00005373 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00005374 if (Field->isBitField())
5375 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005376 else
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005377 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5378 false, false, false, false, false,
5379 EncodePointerToObjCTypedef);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005380 }
5381 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005382 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005383 }
Mike Stump1eb44332009-09-09 15:08:12 +00005384
John McCall3624e9e2012-12-20 02:45:14 +00005385 case Type::ObjCObjectPointer: {
5386 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff14108da2009-07-10 23:34:53 +00005387 if (OPT->isObjCIdType()) {
5388 S += '@';
5389 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005390 }
Mike Stump1eb44332009-09-09 15:08:12 +00005391
Steve Naroff27d20a22009-10-28 22:03:49 +00005392 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5393 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5394 // Since this is a binary compatibility issue, need to consult with runtime
5395 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00005396 S += '#';
5397 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005398 }
Mike Stump1eb44332009-09-09 15:08:12 +00005399
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005400 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005401 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00005402 ExpandPointedToStructures,
5403 ExpandStructures, FD);
Bob Wilsondc8dab62011-11-30 01:57:58 +00005404 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff14108da2009-07-10 23:34:53 +00005405 // Note that we do extended encoding of protocol qualifer list
5406 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00005407 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005408 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5409 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00005410 S += '<';
5411 S += (*I)->getNameAsString();
5412 S += '>';
5413 }
5414 S += '"';
5415 }
5416 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005417 }
Mike Stump1eb44332009-09-09 15:08:12 +00005418
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005419 QualType PointeeTy = OPT->getPointeeType();
5420 if (!EncodingProperty &&
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005421 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5422 !EncodePointerToObjCTypedef) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005423 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00005424 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005425 // {...};
5426 S += '^';
Fariborz Jahanian361a3292013-07-12 16:19:11 +00005427 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc1310462013-07-12 16:41:56 +00005428 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian361a3292013-07-12 16:19:11 +00005429 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5430 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5431 DeepCollectObjCIvars(OI, true, Ivars);
5432 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5433 if (cast<FieldDecl>(Ivars[i]) == FD) {
5434 S += '{';
5435 S += OI->getIdentifier()->getName();
5436 S += '}';
5437 return;
5438 }
5439 }
5440 }
Mike Stump1eb44332009-09-09 15:08:12 +00005441 getObjCEncodingForTypeImpl(PointeeTy, S,
5442 false, ExpandPointedToStructures,
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005443 NULL,
5444 false, false, false, false, false,
5445 /*EncodePointerToObjCTypedef*/true);
Steve Naroff14108da2009-07-10 23:34:53 +00005446 return;
5447 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005448
5449 S += '@';
Bob Wilsondc8dab62011-11-30 01:57:58 +00005450 if (OPT->getInterfaceDecl() &&
5451 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005452 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00005453 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005454 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5455 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005456 S += '<';
5457 S += (*I)->getNameAsString();
5458 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00005459 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005460 S += '"';
5461 }
5462 return;
5463 }
Mike Stump1eb44332009-09-09 15:08:12 +00005464
John McCall532ec7b2010-05-17 23:56:34 +00005465 // gcc just blithely ignores member pointers.
John McCall3624e9e2012-12-20 02:45:14 +00005466 // FIXME: we shoul do better than that. 'M' is available.
5467 case Type::MemberPointer:
John McCall532ec7b2010-05-17 23:56:34 +00005468 return;
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005469
John McCall3624e9e2012-12-20 02:45:14 +00005470 case Type::Vector:
5471 case Type::ExtVector:
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005472 // This matches gcc's encoding, even though technically it is
5473 // insufficient.
5474 // FIXME. We should do a better job than gcc.
5475 return;
John McCall3624e9e2012-12-20 02:45:14 +00005476
Richard Smithdc7a4f52013-04-30 13:56:41 +00005477 case Type::Auto:
5478 // We could see an undeduced auto type here during error recovery.
5479 // Just ignore it.
5480 return;
5481
John McCall3624e9e2012-12-20 02:45:14 +00005482#define ABSTRACT_TYPE(KIND, BASE)
5483#define TYPE(KIND, BASE)
5484#define DEPENDENT_TYPE(KIND, BASE) \
5485 case Type::KIND:
5486#define NON_CANONICAL_TYPE(KIND, BASE) \
5487 case Type::KIND:
5488#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5489 case Type::KIND:
5490#include "clang/AST/TypeNodes.def"
5491 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005492 }
John McCall3624e9e2012-12-20 02:45:14 +00005493 llvm_unreachable("bad type kind!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005494}
5495
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005496void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5497 std::string &S,
5498 const FieldDecl *FD,
5499 bool includeVBases) const {
5500 assert(RDecl && "Expected non-null RecordDecl");
5501 assert(!RDecl->isUnion() && "Should not be called for unions");
5502 if (!RDecl->getDefinition())
5503 return;
5504
5505 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5506 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5507 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5508
5509 if (CXXRec) {
5510 for (CXXRecordDecl::base_class_iterator
5511 BI = CXXRec->bases_begin(),
5512 BE = CXXRec->bases_end(); BI != BE; ++BI) {
5513 if (!BI->isVirtual()) {
5514 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005515 if (base->isEmpty())
5516 continue;
Benjamin Kramerd4f51982012-07-04 18:45:14 +00005517 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005518 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5519 std::make_pair(offs, base));
5520 }
5521 }
5522 }
5523
5524 unsigned i = 0;
5525 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5526 FieldEnd = RDecl->field_end();
5527 Field != FieldEnd; ++Field, ++i) {
5528 uint64_t offs = layout.getFieldOffset(i);
5529 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie581deb32012-06-06 20:45:41 +00005530 std::make_pair(offs, *Field));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005531 }
5532
5533 if (CXXRec && includeVBases) {
5534 for (CXXRecordDecl::base_class_iterator
5535 BI = CXXRec->vbases_begin(),
5536 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
5537 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005538 if (base->isEmpty())
5539 continue;
Benjamin Kramerd4f51982012-07-04 18:45:14 +00005540 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Argyrios Kyrtzidis19aa8602011-09-26 18:14:24 +00005541 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
5542 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5543 std::make_pair(offs, base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005544 }
5545 }
5546
5547 CharUnits size;
5548 if (CXXRec) {
5549 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5550 } else {
5551 size = layout.getSize();
5552 }
5553
5554 uint64_t CurOffs = 0;
5555 std::multimap<uint64_t, NamedDecl *>::iterator
5556 CurLayObj = FieldOrBaseOffsets.begin();
5557
Douglas Gregor58db7a52012-04-27 22:30:01 +00005558 if (CXXRec && CXXRec->isDynamicClass() &&
5559 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005560 if (FD) {
5561 S += "\"_vptr$";
5562 std::string recname = CXXRec->getNameAsString();
5563 if (recname.empty()) recname = "?";
5564 S += recname;
5565 S += '"';
5566 }
5567 S += "^^?";
5568 CurOffs += getTypeSize(VoidPtrTy);
5569 }
5570
5571 if (!RDecl->hasFlexibleArrayMember()) {
5572 // Mark the end of the structure.
5573 uint64_t offs = toBits(size);
5574 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5575 std::make_pair(offs, (NamedDecl*)0));
5576 }
5577
5578 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5579 assert(CurOffs <= CurLayObj->first);
5580
5581 if (CurOffs < CurLayObj->first) {
5582 uint64_t padding = CurLayObj->first - CurOffs;
5583 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5584 // packing/alignment of members is different that normal, in which case
5585 // the encoding will be out-of-sync with the real layout.
5586 // If the runtime switches to just consider the size of types without
5587 // taking into account alignment, we could make padding explicit in the
5588 // encoding (e.g. using arrays of chars). The encoding strings would be
5589 // longer then though.
5590 CurOffs += padding;
5591 }
5592
5593 NamedDecl *dcl = CurLayObj->second;
5594 if (dcl == 0)
5595 break; // reached end of structure.
5596
5597 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5598 // We expand the bases without their virtual bases since those are going
5599 // in the initial structure. Note that this differs from gcc which
5600 // expands virtual bases each time one is encountered in the hierarchy,
5601 // making the encoding type bigger than it really is.
5602 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005603 assert(!base->isEmpty());
5604 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005605 } else {
5606 FieldDecl *field = cast<FieldDecl>(dcl);
5607 if (FD) {
5608 S += '"';
5609 S += field->getNameAsString();
5610 S += '"';
5611 }
5612
5613 if (field->isBitField()) {
5614 EncodeBitField(this, S, field->getType(), field);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005615 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005616 } else {
5617 QualType qt = field->getType();
5618 getLegacyIntegralTypeEncoding(qt);
5619 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5620 /*OutermostType*/false,
5621 /*EncodingProperty*/false,
5622 /*StructField*/true);
5623 CurOffs += getTypeSize(field->getType());
5624 }
5625 }
5626 }
5627}
5628
Mike Stump1eb44332009-09-09 15:08:12 +00005629void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00005630 std::string& S) const {
5631 if (QT & Decl::OBJC_TQ_In)
5632 S += 'n';
5633 if (QT & Decl::OBJC_TQ_Inout)
5634 S += 'N';
5635 if (QT & Decl::OBJC_TQ_Out)
5636 S += 'o';
5637 if (QT & Decl::OBJC_TQ_Bycopy)
5638 S += 'O';
5639 if (QT & Decl::OBJC_TQ_Byref)
5640 S += 'R';
5641 if (QT & Decl::OBJC_TQ_Oneway)
5642 S += 'V';
5643}
5644
Douglas Gregor4dfd02a2011-08-12 05:46:01 +00005645TypedefDecl *ASTContext::getObjCIdDecl() const {
5646 if (!ObjCIdDecl) {
5647 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5648 T = getObjCObjectPointerType(T);
5649 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
5650 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5651 getTranslationUnitDecl(),
5652 SourceLocation(), SourceLocation(),
5653 &Idents.get("id"), IdInfo);
5654 }
5655
5656 return ObjCIdDecl;
Steve Naroff7e219e42007-10-15 14:41:52 +00005657}
5658
Douglas Gregor7a27ea52011-08-12 06:17:30 +00005659TypedefDecl *ASTContext::getObjCSelDecl() const {
5660 if (!ObjCSelDecl) {
5661 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5662 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5663 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5664 getTranslationUnitDecl(),
5665 SourceLocation(), SourceLocation(),
5666 &Idents.get("SEL"), SelInfo);
5667 }
5668 return ObjCSelDecl;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00005669}
5670
Douglas Gregor79d67262011-08-12 05:59:41 +00005671TypedefDecl *ASTContext::getObjCClassDecl() const {
5672 if (!ObjCClassDecl) {
5673 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5674 T = getObjCObjectPointerType(T);
5675 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5676 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5677 getTranslationUnitDecl(),
5678 SourceLocation(), SourceLocation(),
5679 &Idents.get("Class"), ClassInfo);
5680 }
5681
5682 return ObjCClassDecl;
Anders Carlsson8baaca52007-10-31 02:53:19 +00005683}
5684
Douglas Gregora6ea10e2012-01-17 18:09:05 +00005685ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5686 if (!ObjCProtocolClassDecl) {
5687 ObjCProtocolClassDecl
5688 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5689 SourceLocation(),
5690 &Idents.get("Protocol"),
5691 /*PrevDecl=*/0,
5692 SourceLocation(), true);
5693 }
5694
5695 return ObjCProtocolClassDecl;
5696}
5697
Meador Ingec5613b22012-06-16 03:34:49 +00005698//===----------------------------------------------------------------------===//
5699// __builtin_va_list Construction Functions
5700//===----------------------------------------------------------------------===//
5701
5702static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5703 // typedef char* __builtin_va_list;
5704 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5705 TypeSourceInfo *TInfo
5706 = Context->getTrivialTypeSourceInfo(CharPtrType);
5707
5708 TypedefDecl *VaListTypeDecl
5709 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5710 Context->getTranslationUnitDecl(),
5711 SourceLocation(), SourceLocation(),
5712 &Context->Idents.get("__builtin_va_list"),
5713 TInfo);
5714 return VaListTypeDecl;
5715}
5716
5717static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5718 // typedef void* __builtin_va_list;
5719 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5720 TypeSourceInfo *TInfo
5721 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5722
5723 TypedefDecl *VaListTypeDecl
5724 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5725 Context->getTranslationUnitDecl(),
5726 SourceLocation(), SourceLocation(),
5727 &Context->Idents.get("__builtin_va_list"),
5728 TInfo);
5729 return VaListTypeDecl;
5730}
5731
Tim Northoverc264e162013-01-31 12:13:10 +00005732static TypedefDecl *
5733CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
5734 RecordDecl *VaListTagDecl;
5735 if (Context->getLangOpts().CPlusPlus) {
5736 // namespace std { struct __va_list {
5737 NamespaceDecl *NS;
5738 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5739 Context->getTranslationUnitDecl(),
5740 /*Inline*/false, SourceLocation(),
5741 SourceLocation(), &Context->Idents.get("std"),
5742 /*PrevDecl*/0);
5743
5744 VaListTagDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5745 Context->getTranslationUnitDecl(),
5746 SourceLocation(), SourceLocation(),
5747 &Context->Idents.get("__va_list"));
5748 VaListTagDecl->setDeclContext(NS);
5749 } else {
5750 // struct __va_list
5751 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5752 Context->getTranslationUnitDecl(),
5753 &Context->Idents.get("__va_list"));
5754 }
5755
5756 VaListTagDecl->startDefinition();
5757
5758 const size_t NumFields = 5;
5759 QualType FieldTypes[NumFields];
5760 const char *FieldNames[NumFields];
5761
5762 // void *__stack;
5763 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
5764 FieldNames[0] = "__stack";
5765
5766 // void *__gr_top;
5767 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
5768 FieldNames[1] = "__gr_top";
5769
5770 // void *__vr_top;
5771 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5772 FieldNames[2] = "__vr_top";
5773
5774 // int __gr_offs;
5775 FieldTypes[3] = Context->IntTy;
5776 FieldNames[3] = "__gr_offs";
5777
5778 // int __vr_offs;
5779 FieldTypes[4] = Context->IntTy;
5780 FieldNames[4] = "__vr_offs";
5781
5782 // Create fields
5783 for (unsigned i = 0; i < NumFields; ++i) {
5784 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5785 VaListTagDecl,
5786 SourceLocation(),
5787 SourceLocation(),
5788 &Context->Idents.get(FieldNames[i]),
5789 FieldTypes[i], /*TInfo=*/0,
5790 /*BitWidth=*/0,
5791 /*Mutable=*/false,
5792 ICIS_NoInit);
5793 Field->setAccess(AS_public);
5794 VaListTagDecl->addDecl(Field);
5795 }
5796 VaListTagDecl->completeDefinition();
5797 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5798 Context->VaListTagTy = VaListTagType;
5799
5800 // } __builtin_va_list;
5801 TypedefDecl *VaListTypedefDecl
5802 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5803 Context->getTranslationUnitDecl(),
5804 SourceLocation(), SourceLocation(),
5805 &Context->Idents.get("__builtin_va_list"),
5806 Context->getTrivialTypeSourceInfo(VaListTagType));
5807
5808 return VaListTypedefDecl;
5809}
5810
Meador Ingec5613b22012-06-16 03:34:49 +00005811static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5812 // typedef struct __va_list_tag {
5813 RecordDecl *VaListTagDecl;
5814
5815 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5816 Context->getTranslationUnitDecl(),
5817 &Context->Idents.get("__va_list_tag"));
5818 VaListTagDecl->startDefinition();
5819
5820 const size_t NumFields = 5;
5821 QualType FieldTypes[NumFields];
5822 const char *FieldNames[NumFields];
5823
5824 // unsigned char gpr;
5825 FieldTypes[0] = Context->UnsignedCharTy;
5826 FieldNames[0] = "gpr";
5827
5828 // unsigned char fpr;
5829 FieldTypes[1] = Context->UnsignedCharTy;
5830 FieldNames[1] = "fpr";
5831
5832 // unsigned short reserved;
5833 FieldTypes[2] = Context->UnsignedShortTy;
5834 FieldNames[2] = "reserved";
5835
5836 // void* overflow_arg_area;
5837 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5838 FieldNames[3] = "overflow_arg_area";
5839
5840 // void* reg_save_area;
5841 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5842 FieldNames[4] = "reg_save_area";
5843
5844 // Create fields
5845 for (unsigned i = 0; i < NumFields; ++i) {
5846 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5847 SourceLocation(),
5848 SourceLocation(),
5849 &Context->Idents.get(FieldNames[i]),
5850 FieldTypes[i], /*TInfo=*/0,
5851 /*BitWidth=*/0,
5852 /*Mutable=*/false,
5853 ICIS_NoInit);
5854 Field->setAccess(AS_public);
5855 VaListTagDecl->addDecl(Field);
5856 }
5857 VaListTagDecl->completeDefinition();
5858 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingefb40e3f2012-07-01 15:57:25 +00005859 Context->VaListTagTy = VaListTagType;
Meador Ingec5613b22012-06-16 03:34:49 +00005860
5861 // } __va_list_tag;
5862 TypedefDecl *VaListTagTypedefDecl
5863 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5864 Context->getTranslationUnitDecl(),
5865 SourceLocation(), SourceLocation(),
5866 &Context->Idents.get("__va_list_tag"),
5867 Context->getTrivialTypeSourceInfo(VaListTagType));
5868 QualType VaListTagTypedefType =
5869 Context->getTypedefType(VaListTagTypedefDecl);
5870
5871 // typedef __va_list_tag __builtin_va_list[1];
5872 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5873 QualType VaListTagArrayType
5874 = Context->getConstantArrayType(VaListTagTypedefType,
5875 Size, ArrayType::Normal, 0);
5876 TypeSourceInfo *TInfo
5877 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5878 TypedefDecl *VaListTypedefDecl
5879 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5880 Context->getTranslationUnitDecl(),
5881 SourceLocation(), SourceLocation(),
5882 &Context->Idents.get("__builtin_va_list"),
5883 TInfo);
5884
5885 return VaListTypedefDecl;
5886}
5887
5888static TypedefDecl *
5889CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5890 // typedef struct __va_list_tag {
5891 RecordDecl *VaListTagDecl;
5892 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5893 Context->getTranslationUnitDecl(),
5894 &Context->Idents.get("__va_list_tag"));
5895 VaListTagDecl->startDefinition();
5896
5897 const size_t NumFields = 4;
5898 QualType FieldTypes[NumFields];
5899 const char *FieldNames[NumFields];
5900
5901 // unsigned gp_offset;
5902 FieldTypes[0] = Context->UnsignedIntTy;
5903 FieldNames[0] = "gp_offset";
5904
5905 // unsigned fp_offset;
5906 FieldTypes[1] = Context->UnsignedIntTy;
5907 FieldNames[1] = "fp_offset";
5908
5909 // void* overflow_arg_area;
5910 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5911 FieldNames[2] = "overflow_arg_area";
5912
5913 // void* reg_save_area;
5914 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5915 FieldNames[3] = "reg_save_area";
5916
5917 // Create fields
5918 for (unsigned i = 0; i < NumFields; ++i) {
5919 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5920 VaListTagDecl,
5921 SourceLocation(),
5922 SourceLocation(),
5923 &Context->Idents.get(FieldNames[i]),
5924 FieldTypes[i], /*TInfo=*/0,
5925 /*BitWidth=*/0,
5926 /*Mutable=*/false,
5927 ICIS_NoInit);
5928 Field->setAccess(AS_public);
5929 VaListTagDecl->addDecl(Field);
5930 }
5931 VaListTagDecl->completeDefinition();
5932 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingefb40e3f2012-07-01 15:57:25 +00005933 Context->VaListTagTy = VaListTagType;
Meador Ingec5613b22012-06-16 03:34:49 +00005934
5935 // } __va_list_tag;
5936 TypedefDecl *VaListTagTypedefDecl
5937 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5938 Context->getTranslationUnitDecl(),
5939 SourceLocation(), SourceLocation(),
5940 &Context->Idents.get("__va_list_tag"),
5941 Context->getTrivialTypeSourceInfo(VaListTagType));
5942 QualType VaListTagTypedefType =
5943 Context->getTypedefType(VaListTagTypedefDecl);
5944
5945 // typedef __va_list_tag __builtin_va_list[1];
5946 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5947 QualType VaListTagArrayType
5948 = Context->getConstantArrayType(VaListTagTypedefType,
5949 Size, ArrayType::Normal,0);
5950 TypeSourceInfo *TInfo
5951 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5952 TypedefDecl *VaListTypedefDecl
5953 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5954 Context->getTranslationUnitDecl(),
5955 SourceLocation(), SourceLocation(),
5956 &Context->Idents.get("__builtin_va_list"),
5957 TInfo);
5958
5959 return VaListTypedefDecl;
5960}
5961
5962static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5963 // typedef int __builtin_va_list[4];
5964 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5965 QualType IntArrayType
5966 = Context->getConstantArrayType(Context->IntTy,
5967 Size, ArrayType::Normal, 0);
5968 TypedefDecl *VaListTypedefDecl
5969 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5970 Context->getTranslationUnitDecl(),
5971 SourceLocation(), SourceLocation(),
5972 &Context->Idents.get("__builtin_va_list"),
5973 Context->getTrivialTypeSourceInfo(IntArrayType));
5974
5975 return VaListTypedefDecl;
5976}
5977
Logan Chieneae5a8202012-10-10 06:56:20 +00005978static TypedefDecl *
5979CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
5980 RecordDecl *VaListDecl;
5981 if (Context->getLangOpts().CPlusPlus) {
5982 // namespace std { struct __va_list {
5983 NamespaceDecl *NS;
5984 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5985 Context->getTranslationUnitDecl(),
5986 /*Inline*/false, SourceLocation(),
5987 SourceLocation(), &Context->Idents.get("std"),
5988 /*PrevDecl*/0);
5989
5990 VaListDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5991 Context->getTranslationUnitDecl(),
5992 SourceLocation(), SourceLocation(),
5993 &Context->Idents.get("__va_list"));
5994
5995 VaListDecl->setDeclContext(NS);
5996
5997 } else {
5998 // struct __va_list {
5999 VaListDecl = CreateRecordDecl(*Context, TTK_Struct,
6000 Context->getTranslationUnitDecl(),
6001 &Context->Idents.get("__va_list"));
6002 }
6003
6004 VaListDecl->startDefinition();
6005
6006 // void * __ap;
6007 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6008 VaListDecl,
6009 SourceLocation(),
6010 SourceLocation(),
6011 &Context->Idents.get("__ap"),
6012 Context->getPointerType(Context->VoidTy),
6013 /*TInfo=*/0,
6014 /*BitWidth=*/0,
6015 /*Mutable=*/false,
6016 ICIS_NoInit);
6017 Field->setAccess(AS_public);
6018 VaListDecl->addDecl(Field);
6019
6020 // };
6021 VaListDecl->completeDefinition();
6022
6023 // typedef struct __va_list __builtin_va_list;
6024 TypeSourceInfo *TInfo
6025 = Context->getTrivialTypeSourceInfo(Context->getRecordType(VaListDecl));
6026
6027 TypedefDecl *VaListTypeDecl
6028 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6029 Context->getTranslationUnitDecl(),
6030 SourceLocation(), SourceLocation(),
6031 &Context->Idents.get("__builtin_va_list"),
6032 TInfo);
6033
6034 return VaListTypeDecl;
6035}
6036
Ulrich Weigandb8409212013-05-06 16:26:41 +00006037static TypedefDecl *
6038CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
6039 // typedef struct __va_list_tag {
6040 RecordDecl *VaListTagDecl;
6041 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
6042 Context->getTranslationUnitDecl(),
6043 &Context->Idents.get("__va_list_tag"));
6044 VaListTagDecl->startDefinition();
6045
6046 const size_t NumFields = 4;
6047 QualType FieldTypes[NumFields];
6048 const char *FieldNames[NumFields];
6049
6050 // long __gpr;
6051 FieldTypes[0] = Context->LongTy;
6052 FieldNames[0] = "__gpr";
6053
6054 // long __fpr;
6055 FieldTypes[1] = Context->LongTy;
6056 FieldNames[1] = "__fpr";
6057
6058 // void *__overflow_arg_area;
6059 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6060 FieldNames[2] = "__overflow_arg_area";
6061
6062 // void *__reg_save_area;
6063 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6064 FieldNames[3] = "__reg_save_area";
6065
6066 // Create fields
6067 for (unsigned i = 0; i < NumFields; ++i) {
6068 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6069 VaListTagDecl,
6070 SourceLocation(),
6071 SourceLocation(),
6072 &Context->Idents.get(FieldNames[i]),
6073 FieldTypes[i], /*TInfo=*/0,
6074 /*BitWidth=*/0,
6075 /*Mutable=*/false,
6076 ICIS_NoInit);
6077 Field->setAccess(AS_public);
6078 VaListTagDecl->addDecl(Field);
6079 }
6080 VaListTagDecl->completeDefinition();
6081 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6082 Context->VaListTagTy = VaListTagType;
6083
6084 // } __va_list_tag;
6085 TypedefDecl *VaListTagTypedefDecl
6086 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6087 Context->getTranslationUnitDecl(),
6088 SourceLocation(), SourceLocation(),
6089 &Context->Idents.get("__va_list_tag"),
6090 Context->getTrivialTypeSourceInfo(VaListTagType));
6091 QualType VaListTagTypedefType =
6092 Context->getTypedefType(VaListTagTypedefDecl);
6093
6094 // typedef __va_list_tag __builtin_va_list[1];
6095 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6096 QualType VaListTagArrayType
6097 = Context->getConstantArrayType(VaListTagTypedefType,
6098 Size, ArrayType::Normal,0);
6099 TypeSourceInfo *TInfo
6100 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
6101 TypedefDecl *VaListTypedefDecl
6102 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6103 Context->getTranslationUnitDecl(),
6104 SourceLocation(), SourceLocation(),
6105 &Context->Idents.get("__builtin_va_list"),
6106 TInfo);
6107
6108 return VaListTypedefDecl;
6109}
6110
Meador Ingec5613b22012-06-16 03:34:49 +00006111static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6112 TargetInfo::BuiltinVaListKind Kind) {
6113 switch (Kind) {
6114 case TargetInfo::CharPtrBuiltinVaList:
6115 return CreateCharPtrBuiltinVaListDecl(Context);
6116 case TargetInfo::VoidPtrBuiltinVaList:
6117 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northoverc264e162013-01-31 12:13:10 +00006118 case TargetInfo::AArch64ABIBuiltinVaList:
6119 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Ingec5613b22012-06-16 03:34:49 +00006120 case TargetInfo::PowerABIBuiltinVaList:
6121 return CreatePowerABIBuiltinVaListDecl(Context);
6122 case TargetInfo::X86_64ABIBuiltinVaList:
6123 return CreateX86_64ABIBuiltinVaListDecl(Context);
6124 case TargetInfo::PNaClABIBuiltinVaList:
6125 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chieneae5a8202012-10-10 06:56:20 +00006126 case TargetInfo::AAPCSABIBuiltinVaList:
6127 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigandb8409212013-05-06 16:26:41 +00006128 case TargetInfo::SystemZBuiltinVaList:
6129 return CreateSystemZBuiltinVaListDecl(Context);
Meador Ingec5613b22012-06-16 03:34:49 +00006130 }
6131
6132 llvm_unreachable("Unhandled __builtin_va_list type kind");
6133}
6134
6135TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
6136 if (!BuiltinVaListDecl)
6137 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
6138
6139 return BuiltinVaListDecl;
6140}
6141
Meador Ingefb40e3f2012-07-01 15:57:25 +00006142QualType ASTContext::getVaListTagType() const {
6143 // Force the creation of VaListTagTy by building the __builtin_va_list
6144 // declaration.
6145 if (VaListTagTy.isNull())
6146 (void) getBuiltinVaListDecl();
6147
6148 return VaListTagTy;
6149}
6150
Ted Kremeneka526c5c2008-01-07 19:49:32 +00006151void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00006152 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00006153 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00006154
Ted Kremeneka526c5c2008-01-07 19:49:32 +00006155 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00006156}
6157
John McCall0bd6feb2009-12-02 08:04:21 +00006158/// \brief Retrieve the template name that corresponds to a non-empty
6159/// lookup.
Jay Foad4ba2a172011-01-12 09:06:06 +00006160TemplateName
6161ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6162 UnresolvedSetIterator End) const {
John McCall0bd6feb2009-12-02 08:04:21 +00006163 unsigned size = End - Begin;
6164 assert(size > 1 && "set is not overloaded!");
6165
6166 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6167 size * sizeof(FunctionTemplateDecl*));
6168 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6169
6170 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00006171 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00006172 NamedDecl *D = *I;
6173 assert(isa<FunctionTemplateDecl>(D) ||
6174 (isa<UsingShadowDecl>(D) &&
6175 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6176 *Storage++ = D;
6177 }
6178
6179 return TemplateName(OT);
6180}
6181
Douglas Gregor7532dc62009-03-30 22:58:21 +00006182/// \brief Retrieve the template name that represents a qualified
6183/// template name such as \c std::vector.
Jay Foad4ba2a172011-01-12 09:06:06 +00006184TemplateName
6185ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6186 bool TemplateKeyword,
6187 TemplateDecl *Template) const {
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00006188 assert(NNS && "Missing nested-name-specifier in qualified template name");
6189
Douglas Gregor789b1f62010-02-04 18:10:26 +00006190 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00006191 llvm::FoldingSetNodeID ID;
6192 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6193
6194 void *InsertPos = 0;
6195 QualifiedTemplateName *QTN =
6196 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6197 if (!QTN) {
Richard Smith2f47cab2012-08-16 01:19:31 +00006198 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6199 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregor7532dc62009-03-30 22:58:21 +00006200 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6201 }
6202
6203 return TemplateName(QTN);
6204}
6205
6206/// \brief Retrieve the template name that represents a dependent
6207/// template name such as \c MetaFun::template apply.
Jay Foad4ba2a172011-01-12 09:06:06 +00006208TemplateName
6209ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6210 const IdentifierInfo *Name) const {
Mike Stump1eb44332009-09-09 15:08:12 +00006211 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00006212 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00006213
6214 llvm::FoldingSetNodeID ID;
6215 DependentTemplateName::Profile(ID, NNS, Name);
6216
6217 void *InsertPos = 0;
6218 DependentTemplateName *QTN =
6219 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6220
6221 if (QTN)
6222 return TemplateName(QTN);
6223
6224 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6225 if (CanonNNS == NNS) {
Richard Smith2f47cab2012-08-16 01:19:31 +00006226 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6227 DependentTemplateName(NNS, Name);
Douglas Gregor7532dc62009-03-30 22:58:21 +00006228 } else {
6229 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smith2f47cab2012-08-16 01:19:31 +00006230 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6231 DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00006232 DependentTemplateName *CheckQTN =
6233 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6234 assert(!CheckQTN && "Dependent type name canonicalization broken");
6235 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00006236 }
6237
6238 DependentTemplateNames.InsertNode(QTN, InsertPos);
6239 return TemplateName(QTN);
6240}
6241
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006242/// \brief Retrieve the template name that represents a dependent
6243/// template name such as \c MetaFun::template operator+.
6244TemplateName
6245ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00006246 OverloadedOperatorKind Operator) const {
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006247 assert((!NNS || NNS->isDependent()) &&
6248 "Nested name specifier must be dependent");
6249
6250 llvm::FoldingSetNodeID ID;
6251 DependentTemplateName::Profile(ID, NNS, Operator);
6252
6253 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00006254 DependentTemplateName *QTN
6255 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006256
6257 if (QTN)
6258 return TemplateName(QTN);
6259
6260 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6261 if (CanonNNS == NNS) {
Richard Smith2f47cab2012-08-16 01:19:31 +00006262 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6263 DependentTemplateName(NNS, Operator);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006264 } else {
6265 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smith2f47cab2012-08-16 01:19:31 +00006266 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6267 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00006268
6269 DependentTemplateName *CheckQTN
6270 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6271 assert(!CheckQTN && "Dependent template name canonicalization broken");
6272 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006273 }
6274
6275 DependentTemplateNames.InsertNode(QTN, InsertPos);
6276 return TemplateName(QTN);
6277}
6278
Douglas Gregor1aee05d2011-01-15 06:45:20 +00006279TemplateName
John McCall14606042011-06-30 08:33:18 +00006280ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6281 TemplateName replacement) const {
6282 llvm::FoldingSetNodeID ID;
6283 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
6284
6285 void *insertPos = 0;
6286 SubstTemplateTemplateParmStorage *subst
6287 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6288
6289 if (!subst) {
6290 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6291 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6292 }
6293
6294 return TemplateName(subst);
6295}
6296
6297TemplateName
Douglas Gregor1aee05d2011-01-15 06:45:20 +00006298ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6299 const TemplateArgument &ArgPack) const {
6300 ASTContext &Self = const_cast<ASTContext &>(*this);
6301 llvm::FoldingSetNodeID ID;
6302 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
6303
6304 void *InsertPos = 0;
6305 SubstTemplateTemplateParmPackStorage *Subst
6306 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6307
6308 if (!Subst) {
John McCall14606042011-06-30 08:33:18 +00006309 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor1aee05d2011-01-15 06:45:20 +00006310 ArgPack.pack_size(),
6311 ArgPack.pack_begin());
6312 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6313 }
6314
6315 return TemplateName(Subst);
6316}
6317
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006318/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00006319/// TargetInfo, produce the corresponding type. The unsigned @p Type
6320/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00006321CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006322 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00006323 case TargetInfo::NoInt: return CanQualType();
Stepan Dyatkovskiy7b7bef12013-09-05 11:23:21 +00006324 case TargetInfo::SignedChar: return SignedCharTy;
6325 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006326 case TargetInfo::SignedShort: return ShortTy;
6327 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6328 case TargetInfo::SignedInt: return IntTy;
6329 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6330 case TargetInfo::SignedLong: return LongTy;
6331 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6332 case TargetInfo::SignedLongLong: return LongLongTy;
6333 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6334 }
6335
David Blaikieb219cfc2011-09-23 05:06:16 +00006336 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006337}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00006338
6339//===----------------------------------------------------------------------===//
6340// Type Predicates.
6341//===----------------------------------------------------------------------===//
6342
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00006343/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6344/// garbage collection attribute.
6345///
John McCallae278a32011-01-12 00:34:59 +00006346Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikie4e4d0842012-03-11 07:00:24 +00006347 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCallae278a32011-01-12 00:34:59 +00006348 return Qualifiers::GCNone;
6349
David Blaikie4e4d0842012-03-11 07:00:24 +00006350 assert(getLangOpts().ObjC1);
John McCallae278a32011-01-12 00:34:59 +00006351 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6352
6353 // Default behaviour under objective-C's gc is for ObjC pointers
6354 // (or pointers to them) be treated as though they were declared
6355 // as __strong.
6356 if (GCAttrs == Qualifiers::GCNone) {
6357 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6358 return Qualifiers::Strong;
6359 else if (Ty->isPointerType())
6360 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6361 } else {
6362 // It's not valid to set GC attributes on anything that isn't a
6363 // pointer.
6364#ifndef NDEBUG
6365 QualType CT = Ty->getCanonicalTypeInternal();
6366 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6367 CT = AT->getElementType();
6368 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6369#endif
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00006370 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00006371 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00006372}
6373
Chris Lattner6ac46a42008-04-07 06:51:04 +00006374//===----------------------------------------------------------------------===//
6375// Type Compatibility Testing
6376//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00006377
Mike Stump1eb44332009-09-09 15:08:12 +00006378/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00006379/// compatible.
6380static bool areCompatVectorTypes(const VectorType *LHS,
6381 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00006382 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00006383 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00006384 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00006385}
6386
Douglas Gregor255210e2010-08-06 10:14:59 +00006387bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6388 QualType SecondVec) {
6389 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6390 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6391
6392 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6393 return true;
6394
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00006395 // Treat Neon vector types and most AltiVec vector types as if they are the
6396 // equivalent GCC vector types.
Douglas Gregor255210e2010-08-06 10:14:59 +00006397 const VectorType *First = FirstVec->getAs<VectorType>();
6398 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00006399 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor255210e2010-08-06 10:14:59 +00006400 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00006401 First->getVectorKind() != VectorType::AltiVecPixel &&
6402 First->getVectorKind() != VectorType::AltiVecBool &&
6403 Second->getVectorKind() != VectorType::AltiVecPixel &&
6404 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor255210e2010-08-06 10:14:59 +00006405 return true;
6406
6407 return false;
6408}
6409
Steve Naroff4084c302009-07-23 01:01:38 +00006410//===----------------------------------------------------------------------===//
6411// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6412//===----------------------------------------------------------------------===//
6413
6414/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6415/// inheritance hierarchy of 'rProto'.
Jay Foad4ba2a172011-01-12 09:06:06 +00006416bool
6417ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6418 ObjCProtocolDecl *rProto) const {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00006419 if (declaresSameEntity(lProto, rProto))
Steve Naroff4084c302009-07-23 01:01:38 +00006420 return true;
6421 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
6422 E = rProto->protocol_end(); PI != E; ++PI)
6423 if (ProtocolCompatibleWithProtocol(lProto, *PI))
6424 return true;
6425 return false;
6426}
6427
Dmitri Gribenko4c3b8a32012-08-28 02:49:14 +00006428/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6429/// Class<pr1, ...>.
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00006430bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6431 QualType rhs) {
6432 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6433 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6434 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6435
6436 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6437 E = lhsQID->qual_end(); I != E; ++I) {
6438 bool match = false;
6439 ObjCProtocolDecl *lhsProto = *I;
6440 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6441 E = rhsOPT->qual_end(); J != E; ++J) {
6442 ObjCProtocolDecl *rhsProto = *J;
6443 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6444 match = true;
6445 break;
6446 }
6447 }
6448 if (!match)
6449 return false;
6450 }
6451 return true;
6452}
6453
Steve Naroff4084c302009-07-23 01:01:38 +00006454/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6455/// ObjCQualifiedIDType.
6456bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6457 bool compare) {
6458 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00006459 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00006460 lhs->isObjCIdType() || lhs->isObjCClassType())
6461 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00006462 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00006463 rhs->isObjCIdType() || rhs->isObjCClassType())
6464 return true;
6465
6466 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00006467 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00006468
Steve Naroff4084c302009-07-23 01:01:38 +00006469 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006470
Steve Naroff4084c302009-07-23 01:01:38 +00006471 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006472 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00006473 // make sure we check the class hierarchy.
6474 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6475 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6476 E = lhsQID->qual_end(); I != E; ++I) {
6477 // when comparing an id<P> on lhs with a static type on rhs,
6478 // see if static class implements all of id's protocols, directly or
6479 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00006480 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00006481 return false;
6482 }
6483 }
6484 // If there are no qualifiers and no interface, we have an 'id'.
6485 return true;
6486 }
Mike Stump1eb44332009-09-09 15:08:12 +00006487 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00006488 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6489 E = lhsQID->qual_end(); I != E; ++I) {
6490 ObjCProtocolDecl *lhsProto = *I;
6491 bool match = false;
6492
6493 // when comparing an id<P> on lhs with a static type on rhs,
6494 // see if static class implements all of id's protocols, directly or
6495 // through its super class and categories.
6496 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6497 E = rhsOPT->qual_end(); J != E; ++J) {
6498 ObjCProtocolDecl *rhsProto = *J;
6499 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6500 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6501 match = true;
6502 break;
6503 }
6504 }
Mike Stump1eb44332009-09-09 15:08:12 +00006505 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00006506 // make sure we check the class hierarchy.
6507 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6508 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6509 E = lhsQID->qual_end(); I != E; ++I) {
6510 // when comparing an id<P> on lhs with a static type on rhs,
6511 // see if static class implements all of id's protocols, directly or
6512 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00006513 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00006514 match = true;
6515 break;
6516 }
6517 }
6518 }
6519 if (!match)
6520 return false;
6521 }
Mike Stump1eb44332009-09-09 15:08:12 +00006522
Steve Naroff4084c302009-07-23 01:01:38 +00006523 return true;
6524 }
Mike Stump1eb44332009-09-09 15:08:12 +00006525
Steve Naroff4084c302009-07-23 01:01:38 +00006526 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6527 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6528
Mike Stump1eb44332009-09-09 15:08:12 +00006529 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00006530 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006531 // If both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00006532 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
6533 E = lhsOPT->qual_end(); I != E; ++I) {
6534 ObjCProtocolDecl *lhsProto = *I;
6535 bool match = false;
6536
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006537 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff4084c302009-07-23 01:01:38 +00006538 // see if static class implements all of id's protocols, directly or
6539 // through its super class and categories.
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006540 // First, lhs protocols in the qualifier list must be found, direct
6541 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff4084c302009-07-23 01:01:38 +00006542 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6543 E = rhsQID->qual_end(); J != E; ++J) {
6544 ObjCProtocolDecl *rhsProto = *J;
6545 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6546 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6547 match = true;
6548 break;
6549 }
6550 }
6551 if (!match)
6552 return false;
6553 }
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006554
6555 // Static class's protocols, or its super class or category protocols
6556 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6557 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6558 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6559 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6560 // This is rather dubious but matches gcc's behavior. If lhs has
6561 // no type qualifier and its class has no static protocol(s)
6562 // assume that it is mismatch.
6563 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6564 return false;
6565 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6566 LHSInheritedProtocols.begin(),
6567 E = LHSInheritedProtocols.end(); I != E; ++I) {
6568 bool match = false;
6569 ObjCProtocolDecl *lhsProto = (*I);
6570 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6571 E = rhsQID->qual_end(); J != E; ++J) {
6572 ObjCProtocolDecl *rhsProto = *J;
6573 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6574 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6575 match = true;
6576 break;
6577 }
6578 }
6579 if (!match)
6580 return false;
6581 }
6582 }
Steve Naroff4084c302009-07-23 01:01:38 +00006583 return true;
6584 }
6585 return false;
6586}
6587
Eli Friedman3d815e72008-08-22 00:56:42 +00006588/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00006589/// compatible for assignment from RHS to LHS. This handles validation of any
6590/// protocol qualifiers on the LHS or RHS.
6591///
Steve Naroff14108da2009-07-10 23:34:53 +00006592bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6593 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00006594 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6595 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6596
Steve Naroffde2e22d2009-07-15 18:40:39 +00006597 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00006598 if (LHS->isObjCUnqualifiedIdOrClass() ||
6599 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00006600 return true;
6601
John McCallc12c5bb2010-05-15 11:32:37 +00006602 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00006603 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6604 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00006605 false);
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00006606
6607 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6608 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6609 QualType(RHSOPT,0));
6610
John McCallc12c5bb2010-05-15 11:32:37 +00006611 // If we have 2 user-defined types, fall into that path.
6612 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00006613 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00006614
Steve Naroff4084c302009-07-23 01:01:38 +00006615 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00006616}
6617
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006618/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00006619/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006620/// arguments in block literals. When passed as arguments, passing 'A*' where
6621/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6622/// not OK. For the return type, the opposite is not OK.
6623bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6624 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006625 const ObjCObjectPointerType *RHSOPT,
6626 bool BlockReturnType) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00006627 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006628 return true;
6629
6630 if (LHSOPT->isObjCBuiltinType()) {
6631 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6632 }
6633
Fariborz Jahaniana9834482010-04-06 17:23:39 +00006634 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006635 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6636 QualType(RHSOPT,0),
6637 false);
6638
6639 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6640 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6641 if (LHS && RHS) { // We have 2 user-defined types.
6642 if (LHS != RHS) {
6643 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006644 return BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006645 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006646 return !BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006647 }
6648 else
6649 return true;
6650 }
6651 return false;
6652}
6653
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006654/// getIntersectionOfProtocols - This routine finds the intersection of set
6655/// of protocols inherited from two distinct objective-c pointer objects.
6656/// It is used to build composite qualifier list of the composite type of
6657/// the conditional expression involving two objective-c pointer objects.
6658static
6659void getIntersectionOfProtocols(ASTContext &Context,
6660 const ObjCObjectPointerType *LHSOPT,
6661 const ObjCObjectPointerType *RHSOPT,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006662 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006663
John McCallc12c5bb2010-05-15 11:32:37 +00006664 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6665 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6666 assert(LHS->getInterface() && "LHS must have an interface base");
6667 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006668
6669 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6670 unsigned LHSNumProtocols = LHS->getNumProtocols();
6671 if (LHSNumProtocols > 0)
6672 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6673 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006674 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006675 Context.CollectInheritedProtocols(LHS->getInterface(),
6676 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006677 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6678 LHSInheritedProtocols.end());
6679 }
6680
6681 unsigned RHSNumProtocols = RHS->getNumProtocols();
6682 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00006683 ObjCProtocolDecl **RHSProtocols =
6684 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006685 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6686 if (InheritedProtocolSet.count(RHSProtocols[i]))
6687 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier30601782011-08-17 23:08:45 +00006688 } else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006689 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006690 Context.CollectInheritedProtocols(RHS->getInterface(),
6691 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006692 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6693 RHSInheritedProtocols.begin(),
6694 E = RHSInheritedProtocols.end(); I != E; ++I)
6695 if (InheritedProtocolSet.count((*I)))
6696 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006697 }
6698}
6699
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006700/// areCommonBaseCompatible - Returns common base class of the two classes if
6701/// one found. Note that this is O'2 algorithm. But it will be called as the
6702/// last type comparison in a ?-exp of ObjC pointer types before a
6703/// warning is issued. So, its invokation is extremely rare.
6704QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00006705 const ObjCObjectPointerType *Lptr,
6706 const ObjCObjectPointerType *Rptr) {
6707 const ObjCObjectType *LHS = Lptr->getObjectType();
6708 const ObjCObjectType *RHS = Rptr->getObjectType();
6709 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6710 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor60ef3082011-12-15 00:29:59 +00006711 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006712 return QualType();
6713
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00006714 do {
John McCallc12c5bb2010-05-15 11:32:37 +00006715 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006716 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006717 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006718 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6719
6720 QualType Result = QualType(LHS, 0);
6721 if (!Protocols.empty())
6722 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6723 Result = getObjCObjectPointerType(Result);
6724 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006725 }
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00006726 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006727
6728 return QualType();
6729}
6730
John McCallc12c5bb2010-05-15 11:32:37 +00006731bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6732 const ObjCObjectType *RHS) {
6733 assert(LHS->getInterface() && "LHS is not an interface type");
6734 assert(RHS->getInterface() && "RHS is not an interface type");
6735
Chris Lattner6ac46a42008-04-07 06:51:04 +00006736 // Verify that the base decls are compatible: the RHS must be a subclass of
6737 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00006738 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00006739 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006740
Chris Lattner6ac46a42008-04-07 06:51:04 +00006741 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6742 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00006743 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00006744 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00006745
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006746 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6747 // more detailed analysis is required.
6748 if (RHS->getNumProtocols() == 0) {
6749 // OK, if LHS is a superclass of RHS *and*
6750 // this superclass is assignment compatible with LHS.
6751 // false otherwise.
Fariborz Jahanian627788c2011-04-12 16:34:14 +00006752 bool IsSuperClass =
6753 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6754 if (IsSuperClass) {
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006755 // OK if conversion of LHS to SuperClass results in narrowing of types
6756 // ; i.e., SuperClass may implement at least one of the protocols
6757 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6758 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6759 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian627788c2011-04-12 16:34:14 +00006760 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006761 // If super class has no protocols, it is not a match.
6762 if (SuperClassInheritedProtocols.empty())
6763 return false;
6764
6765 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6766 LHSPE = LHS->qual_end();
6767 LHSPI != LHSPE; LHSPI++) {
6768 bool SuperImplementsProtocol = false;
6769 ObjCProtocolDecl *LHSProto = (*LHSPI);
6770
6771 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6772 SuperClassInheritedProtocols.begin(),
6773 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6774 ObjCProtocolDecl *SuperClassProto = (*I);
6775 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6776 SuperImplementsProtocol = true;
6777 break;
6778 }
6779 }
6780 if (!SuperImplementsProtocol)
6781 return false;
6782 }
6783 return true;
6784 }
6785 return false;
6786 }
Mike Stump1eb44332009-09-09 15:08:12 +00006787
John McCallc12c5bb2010-05-15 11:32:37 +00006788 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6789 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006790 LHSPI != LHSPE; LHSPI++) {
6791 bool RHSImplementsProtocol = false;
6792
6793 // If the RHS doesn't implement the protocol on the left, the types
6794 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00006795 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6796 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00006797 RHSPI != RHSPE; RHSPI++) {
6798 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006799 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00006800 break;
6801 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006802 }
6803 // FIXME: For better diagnostics, consider passing back the protocol name.
6804 if (!RHSImplementsProtocol)
6805 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00006806 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006807 // The RHS implements all protocols listed on the LHS.
6808 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00006809}
6810
Steve Naroff389bf462009-02-12 17:52:19 +00006811bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6812 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00006813 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6814 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00006815
Steve Naroff14108da2009-07-10 23:34:53 +00006816 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00006817 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00006818
6819 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6820 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00006821}
6822
Douglas Gregor569c3162010-08-07 11:51:51 +00006823bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6824 return canAssignObjCInterfaces(
6825 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6826 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6827}
6828
Mike Stump1eb44332009-09-09 15:08:12 +00006829/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00006830/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00006831/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00006832/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor447234d2010-07-29 15:18:02 +00006833bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6834 bool CompareUnqualified) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006835 if (getLangOpts().CPlusPlus)
Douglas Gregor0e709ab2010-02-03 21:02:30 +00006836 return hasSameType(LHS, RHS);
6837
Douglas Gregor447234d2010-07-29 15:18:02 +00006838 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman3d815e72008-08-22 00:56:42 +00006839}
6840
Fariborz Jahanianc286f382011-07-12 22:05:16 +00006841bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanian82378392011-07-12 23:20:13 +00006842 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc286f382011-07-12 22:05:16 +00006843}
6844
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006845bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6846 return !mergeTypes(LHS, RHS, true).isNull();
6847}
6848
Peter Collingbourne48466752010-10-24 18:30:18 +00006849/// mergeTransparentUnionType - if T is a transparent union type and a member
6850/// of T is compatible with SubType, return the merged type, else return
6851/// QualType()
6852QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6853 bool OfBlockPointer,
6854 bool Unqualified) {
6855 if (const RecordType *UT = T->getAsUnionType()) {
6856 RecordDecl *UD = UT->getDecl();
6857 if (UD->hasAttr<TransparentUnionAttr>()) {
6858 for (RecordDecl::field_iterator it = UD->field_begin(),
6859 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbournef91d7572010-12-02 21:00:06 +00006860 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00006861 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6862 if (!MT.isNull())
6863 return MT;
6864 }
6865 }
6866 }
6867
6868 return QualType();
6869}
6870
6871/// mergeFunctionArgumentTypes - merge two types which appear as function
6872/// argument types
6873QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
6874 bool OfBlockPointer,
6875 bool Unqualified) {
6876 // GNU extension: two types are compatible if they appear as a function
6877 // argument, one of the types is a transparent union type and the other
6878 // type is compatible with a union member
6879 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6880 Unqualified);
6881 if (!lmerge.isNull())
6882 return lmerge;
6883
6884 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6885 Unqualified);
6886 if (!rmerge.isNull())
6887 return rmerge;
6888
6889 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6890}
6891
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006892QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor447234d2010-07-29 15:18:02 +00006893 bool OfBlockPointer,
6894 bool Unqualified) {
John McCall183700f2009-09-21 23:43:11 +00006895 const FunctionType *lbase = lhs->getAs<FunctionType>();
6896 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00006897 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6898 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00006899 bool allLTypes = true;
6900 bool allRTypes = true;
6901
6902 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006903 QualType retType;
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00006904 if (OfBlockPointer) {
6905 QualType RHS = rbase->getResultType();
6906 QualType LHS = lbase->getResultType();
6907 bool UnqualifiedResult = Unqualified;
6908 if (!UnqualifiedResult)
6909 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006910 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00006911 }
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006912 else
John McCall8cc246c2010-12-15 01:06:38 +00006913 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6914 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006915 if (retType.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006916
6917 if (Unqualified)
6918 retType = retType.getUnqualifiedType();
6919
6920 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6921 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6922 if (Unqualified) {
6923 LRetType = LRetType.getUnqualifiedType();
6924 RRetType = RRetType.getUnqualifiedType();
6925 }
6926
6927 if (getCanonicalType(retType) != LRetType)
Chris Lattner61710852008-10-05 17:34:18 +00006928 allLTypes = false;
Douglas Gregor447234d2010-07-29 15:18:02 +00006929 if (getCanonicalType(retType) != RRetType)
Chris Lattner61710852008-10-05 17:34:18 +00006930 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00006931
Daniel Dunbar6a15c852010-04-28 16:20:58 +00006932 // FIXME: double check this
6933 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6934 // rbase->getRegParmAttr() != 0 &&
6935 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00006936 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6937 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8cc246c2010-12-15 01:06:38 +00006938
Douglas Gregorab8bbf42010-01-18 17:14:39 +00006939 // Compatible functions must have compatible calling conventions
Reid Kleckneref072032013-08-27 23:08:25 +00006940 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Douglas Gregorab8bbf42010-01-18 17:14:39 +00006941 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00006942
John McCall8cc246c2010-12-15 01:06:38 +00006943 // Regparm is part of the calling convention.
Eli Friedmana49218e2011-04-09 08:18:08 +00006944 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6945 return QualType();
John McCall8cc246c2010-12-15 01:06:38 +00006946 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6947 return QualType();
6948
John McCallf85e1932011-06-15 23:02:42 +00006949 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6950 return QualType();
6951
John McCall8cc246c2010-12-15 01:06:38 +00006952 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6953 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8cc246c2010-12-15 01:06:38 +00006954
Rafael Espindola8b8a09e2012-11-29 16:09:03 +00006955 if (lbaseInfo.getNoReturn() != NoReturn)
6956 allLTypes = false;
6957 if (rbaseInfo.getNoReturn() != NoReturn)
6958 allRTypes = false;
6959
John McCallf85e1932011-06-15 23:02:42 +00006960 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00006961
Eli Friedman3d815e72008-08-22 00:56:42 +00006962 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00006963 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6964 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00006965 unsigned lproto_nargs = lproto->getNumArgs();
6966 unsigned rproto_nargs = rproto->getNumArgs();
6967
6968 // Compatible functions must have the same number of arguments
6969 if (lproto_nargs != rproto_nargs)
6970 return QualType();
6971
6972 // Variadic and non-variadic functions aren't compatible
6973 if (lproto->isVariadic() != rproto->isVariadic())
6974 return QualType();
6975
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00006976 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6977 return QualType();
6978
Fariborz Jahanian78213e42011-09-28 21:52:05 +00006979 if (LangOpts.ObjCAutoRefCount &&
6980 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6981 return QualType();
6982
Eli Friedman3d815e72008-08-22 00:56:42 +00006983 // Check argument compatibility
Chris Lattner5f9e2722011-07-23 10:55:15 +00006984 SmallVector<QualType, 10> types;
Eli Friedman3d815e72008-08-22 00:56:42 +00006985 for (unsigned i = 0; i < lproto_nargs; i++) {
6986 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
6987 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00006988 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
6989 OfBlockPointer,
6990 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006991 if (argtype.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006992
6993 if (Unqualified)
6994 argtype = argtype.getUnqualifiedType();
6995
Eli Friedman3d815e72008-08-22 00:56:42 +00006996 types.push_back(argtype);
Douglas Gregor447234d2010-07-29 15:18:02 +00006997 if (Unqualified) {
6998 largtype = largtype.getUnqualifiedType();
6999 rargtype = rargtype.getUnqualifiedType();
7000 }
7001
Chris Lattner61710852008-10-05 17:34:18 +00007002 if (getCanonicalType(argtype) != getCanonicalType(largtype))
7003 allLTypes = false;
7004 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
7005 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00007006 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00007007
Eli Friedman3d815e72008-08-22 00:56:42 +00007008 if (allLTypes) return lhs;
7009 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00007010
7011 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7012 EPI.ExtInfo = einfo;
Jordan Rosebea522f2013-03-08 21:51:21 +00007013 return getFunctionType(retType, types, EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00007014 }
7015
7016 if (lproto) allRTypes = false;
7017 if (rproto) allLTypes = false;
7018
Douglas Gregor72564e72009-02-26 23:50:07 +00007019 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00007020 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00007021 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00007022 if (proto->isVariadic()) return QualType();
7023 // Check that the types are compatible with the types that
7024 // would result from default argument promotions (C99 6.7.5.3p15).
7025 // The only types actually affected are promotable integer
7026 // types and floats, which would be passed as a different
7027 // type depending on whether the prototype is visible.
7028 unsigned proto_nargs = proto->getNumArgs();
7029 for (unsigned i = 0; i < proto_nargs; ++i) {
7030 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00007031
Eli Friedmanc586d5d2012-08-30 00:44:15 +00007032 // Look at the converted type of enum types, since that is the type used
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00007033 // to pass enum values.
Eli Friedmanc586d5d2012-08-30 00:44:15 +00007034 if (const EnumType *Enum = argTy->getAs<EnumType>()) {
7035 argTy = Enum->getDecl()->getIntegerType();
7036 if (argTy.isNull())
7037 return QualType();
7038 }
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00007039
Eli Friedman3d815e72008-08-22 00:56:42 +00007040 if (argTy->isPromotableIntegerType() ||
7041 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
7042 return QualType();
7043 }
7044
7045 if (allLTypes) return lhs;
7046 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00007047
7048 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7049 EPI.ExtInfo = einfo;
Reid Kleckner0567a792013-06-10 20:51:09 +00007050 return getFunctionType(retType, proto->getArgTypes(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00007051 }
7052
7053 if (allLTypes) return lhs;
7054 if (allRTypes) return rhs;
John McCall8cc246c2010-12-15 01:06:38 +00007055 return getFunctionNoProtoType(retType, einfo);
Eli Friedman3d815e72008-08-22 00:56:42 +00007056}
7057
John McCallb9da7132013-03-21 00:10:07 +00007058/// Given that we have an enum type and a non-enum type, try to merge them.
7059static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7060 QualType other, bool isBlockReturnType) {
7061 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7062 // a signed integer type, or an unsigned integer type.
7063 // Compatibility is based on the underlying type, not the promotion
7064 // type.
7065 QualType underlyingType = ET->getDecl()->getIntegerType();
7066 if (underlyingType.isNull()) return QualType();
7067 if (Context.hasSameType(underlyingType, other))
7068 return other;
7069
7070 // In block return types, we're more permissive and accept any
7071 // integral type of the same size.
7072 if (isBlockReturnType && other->isIntegerType() &&
7073 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7074 return other;
7075
7076 return QualType();
7077}
7078
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00007079QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor447234d2010-07-29 15:18:02 +00007080 bool OfBlockPointer,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00007081 bool Unqualified, bool BlockReturnType) {
Bill Wendling43d69752007-12-03 07:33:35 +00007082 // C++ [expr]: If an expression initially has the type "reference to T", the
7083 // type is adjusted to "T" prior to any further analysis, the expression
7084 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00007085 // expression is an lvalue unless the reference is an rvalue reference and
7086 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00007087 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7088 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor447234d2010-07-29 15:18:02 +00007089
7090 if (Unqualified) {
7091 LHS = LHS.getUnqualifiedType();
7092 RHS = RHS.getUnqualifiedType();
7093 }
Douglas Gregor0e709ab2010-02-03 21:02:30 +00007094
Eli Friedman3d815e72008-08-22 00:56:42 +00007095 QualType LHSCan = getCanonicalType(LHS),
7096 RHSCan = getCanonicalType(RHS);
7097
7098 // If two types are identical, they are compatible.
7099 if (LHSCan == RHSCan)
7100 return LHS;
7101
John McCall0953e762009-09-24 19:53:00 +00007102 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00007103 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7104 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00007105 if (LQuals != RQuals) {
7106 // If any of these qualifiers are different, we have a type
7107 // mismatch.
7108 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCallf85e1932011-06-15 23:02:42 +00007109 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7110 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall0953e762009-09-24 19:53:00 +00007111 return QualType();
7112
7113 // Exactly one GC qualifier difference is allowed: __strong is
7114 // okay if the other type has no GC qualifier but is an Objective
7115 // C object pointer (i.e. implicitly strong by default). We fix
7116 // this by pretending that the unqualified type was actually
7117 // qualified __strong.
7118 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7119 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7120 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7121
7122 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7123 return QualType();
7124
7125 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7126 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7127 }
7128 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7129 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7130 }
Eli Friedman3d815e72008-08-22 00:56:42 +00007131 return QualType();
John McCall0953e762009-09-24 19:53:00 +00007132 }
7133
7134 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00007135
Eli Friedman852d63b2009-06-01 01:22:52 +00007136 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7137 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00007138
Chris Lattner1adb8832008-01-14 05:45:46 +00007139 // We want to consider the two function types to be the same for these
7140 // comparisons, just force one to the other.
7141 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7142 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00007143
7144 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00007145 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7146 LHSClass = Type::ConstantArray;
7147 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7148 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00007149
John McCallc12c5bb2010-05-15 11:32:37 +00007150 // ObjCInterfaces are just specialized ObjCObjects.
7151 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7152 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7153
Nate Begeman213541a2008-04-18 23:10:10 +00007154 // Canonicalize ExtVector -> Vector.
7155 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7156 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00007157
Chris Lattnera36a61f2008-04-07 05:43:21 +00007158 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00007159 if (LHSClass != RHSClass) {
John McCallb9da7132013-03-21 00:10:07 +00007160 // Note that we only have special rules for turning block enum
7161 // returns into block int returns, not vice-versa.
John McCall183700f2009-09-21 23:43:11 +00007162 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCallb9da7132013-03-21 00:10:07 +00007163 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmanbab96962008-02-12 08:46:17 +00007164 }
John McCall183700f2009-09-21 23:43:11 +00007165 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCallb9da7132013-03-21 00:10:07 +00007166 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmanbab96962008-02-12 08:46:17 +00007167 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00007168 // allow block pointer type to match an 'id' type.
Fariborz Jahanian41963632012-01-26 17:08:50 +00007169 if (OfBlockPointer && !BlockReturnType) {
7170 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7171 return LHS;
7172 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7173 return RHS;
7174 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00007175
Eli Friedman3d815e72008-08-22 00:56:42 +00007176 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00007177 }
Eli Friedman3d815e72008-08-22 00:56:42 +00007178
Steve Naroff4a746782008-01-09 22:43:08 +00007179 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00007180 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00007181#define TYPE(Class, Base)
7182#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00007183#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00007184#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7185#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7186#include "clang/AST/TypeNodes.def"
David Blaikieb219cfc2011-09-23 05:06:16 +00007187 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregor72564e72009-02-26 23:50:07 +00007188
Richard Smithdc7a4f52013-04-30 13:56:41 +00007189 case Type::Auto:
Sebastian Redl7c80bd62009-03-16 23:22:08 +00007190 case Type::LValueReference:
7191 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00007192 case Type::MemberPointer:
David Blaikieb219cfc2011-09-23 05:06:16 +00007193 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregor72564e72009-02-26 23:50:07 +00007194
John McCallc12c5bb2010-05-15 11:32:37 +00007195 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00007196 case Type::IncompleteArray:
7197 case Type::VariableArray:
7198 case Type::FunctionProto:
7199 case Type::ExtVector:
David Blaikieb219cfc2011-09-23 05:06:16 +00007200 llvm_unreachable("Types are eliminated above");
Douglas Gregor72564e72009-02-26 23:50:07 +00007201
Chris Lattner1adb8832008-01-14 05:45:46 +00007202 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00007203 {
7204 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00007205 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7206 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00007207 if (Unqualified) {
7208 LHSPointee = LHSPointee.getUnqualifiedType();
7209 RHSPointee = RHSPointee.getUnqualifiedType();
7210 }
7211 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7212 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00007213 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00007214 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00007215 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00007216 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00007217 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00007218 return getPointerType(ResultType);
7219 }
Steve Naroffc0febd52008-12-10 17:49:55 +00007220 case Type::BlockPointer:
7221 {
7222 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00007223 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7224 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00007225 if (Unqualified) {
7226 LHSPointee = LHSPointee.getUnqualifiedType();
7227 RHSPointee = RHSPointee.getUnqualifiedType();
7228 }
7229 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7230 Unqualified);
Steve Naroffc0febd52008-12-10 17:49:55 +00007231 if (ResultType.isNull()) return QualType();
7232 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7233 return LHS;
7234 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7235 return RHS;
7236 return getBlockPointerType(ResultType);
7237 }
Eli Friedmanb001de72011-10-06 23:00:33 +00007238 case Type::Atomic:
7239 {
7240 // Merge two pointer types, while trying to preserve typedef info
7241 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7242 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7243 if (Unqualified) {
7244 LHSValue = LHSValue.getUnqualifiedType();
7245 RHSValue = RHSValue.getUnqualifiedType();
7246 }
7247 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7248 Unqualified);
7249 if (ResultType.isNull()) return QualType();
7250 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7251 return LHS;
7252 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7253 return RHS;
7254 return getAtomicType(ResultType);
7255 }
Chris Lattner1adb8832008-01-14 05:45:46 +00007256 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00007257 {
7258 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7259 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7260 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7261 return QualType();
7262
7263 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7264 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor447234d2010-07-29 15:18:02 +00007265 if (Unqualified) {
7266 LHSElem = LHSElem.getUnqualifiedType();
7267 RHSElem = RHSElem.getUnqualifiedType();
7268 }
7269
7270 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00007271 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00007272 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7273 return LHS;
7274 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7275 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00007276 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7277 ArrayType::ArraySizeModifier(), 0);
7278 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7279 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00007280 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7281 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00007282 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7283 return LHS;
7284 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7285 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00007286 if (LVAT) {
7287 // FIXME: This isn't correct! But tricky to implement because
7288 // the array's size has to be the size of LHS, but the type
7289 // has to be different.
7290 return LHS;
7291 }
7292 if (RVAT) {
7293 // FIXME: This isn't correct! But tricky to implement because
7294 // the array's size has to be the size of RHS, but the type
7295 // has to be different.
7296 return RHS;
7297 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00007298 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7299 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00007300 return getIncompleteArrayType(ResultType,
7301 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00007302 }
Chris Lattner1adb8832008-01-14 05:45:46 +00007303 case Type::FunctionNoProto:
Douglas Gregor447234d2010-07-29 15:18:02 +00007304 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregor72564e72009-02-26 23:50:07 +00007305 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00007306 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00007307 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00007308 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00007309 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00007310 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00007311 case Type::Complex:
7312 // Distinct complex types are incompatible.
7313 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00007314 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00007315 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00007316 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7317 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00007318 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00007319 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00007320 case Type::ObjCObject: {
7321 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00007322 // FIXME: This should be type compatibility, e.g. whether
7323 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00007324 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7325 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7326 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00007327 return LHS;
7328
Eli Friedman3d815e72008-08-22 00:56:42 +00007329 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00007330 }
Steve Naroff14108da2009-07-10 23:34:53 +00007331 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00007332 if (OfBlockPointer) {
7333 if (canAssignObjCInterfacesInBlockPointer(
7334 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00007335 RHS->getAs<ObjCObjectPointerType>(),
7336 BlockReturnType))
David Blaikie7530c032012-01-17 06:56:22 +00007337 return LHS;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00007338 return QualType();
7339 }
John McCall183700f2009-09-21 23:43:11 +00007340 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7341 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00007342 return LHS;
7343
Steve Naroffbc76dd02008-12-10 22:14:21 +00007344 return QualType();
David Blaikie7530c032012-01-17 06:56:22 +00007345 }
Steve Naroffec0550f2007-10-15 20:41:53 +00007346 }
Douglas Gregor72564e72009-02-26 23:50:07 +00007347
David Blaikie7530c032012-01-17 06:56:22 +00007348 llvm_unreachable("Invalid Type::Class!");
Steve Naroffec0550f2007-10-15 20:41:53 +00007349}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00007350
Fariborz Jahanian78213e42011-09-28 21:52:05 +00007351bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7352 const FunctionProtoType *FromFunctionType,
7353 const FunctionProtoType *ToFunctionType) {
7354 if (FromFunctionType->hasAnyConsumedArgs() !=
7355 ToFunctionType->hasAnyConsumedArgs())
7356 return false;
7357 FunctionProtoType::ExtProtoInfo FromEPI =
7358 FromFunctionType->getExtProtoInfo();
7359 FunctionProtoType::ExtProtoInfo ToEPI =
7360 ToFunctionType->getExtProtoInfo();
7361 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
7362 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
7363 ArgIdx != NumArgs; ++ArgIdx) {
7364 if (FromEPI.ConsumedArguments[ArgIdx] !=
7365 ToEPI.ConsumedArguments[ArgIdx])
7366 return false;
7367 }
7368 return true;
7369}
7370
Fariborz Jahanian2390a722010-05-19 21:37:30 +00007371/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7372/// 'RHS' attributes and returns the merged version; including for function
7373/// return types.
7374QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7375 QualType LHSCan = getCanonicalType(LHS),
7376 RHSCan = getCanonicalType(RHS);
7377 // If two types are identical, they are compatible.
7378 if (LHSCan == RHSCan)
7379 return LHS;
7380 if (RHSCan->isFunctionType()) {
7381 if (!LHSCan->isFunctionType())
7382 return QualType();
7383 QualType OldReturnType =
7384 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
7385 QualType NewReturnType =
7386 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
7387 QualType ResReturnType =
7388 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7389 if (ResReturnType.isNull())
7390 return QualType();
7391 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7392 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7393 // In either case, use OldReturnType to build the new function type.
7394 const FunctionType *F = LHS->getAs<FunctionType>();
7395 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalle23cf432010-12-14 08:05:40 +00007396 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7397 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner0567a792013-06-10 20:51:09 +00007398 QualType ResultType =
7399 getFunctionType(OldReturnType, FPT->getArgTypes(), EPI);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00007400 return ResultType;
7401 }
7402 }
7403 return QualType();
7404 }
7405
7406 // If the qualifiers are different, the types can still be merged.
7407 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7408 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7409 if (LQuals != RQuals) {
7410 // If any of these qualifiers are different, we have a type mismatch.
7411 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7412 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7413 return QualType();
7414
7415 // Exactly one GC qualifier difference is allowed: __strong is
7416 // okay if the other type has no GC qualifier but is an Objective
7417 // C object pointer (i.e. implicitly strong by default). We fix
7418 // this by pretending that the unqualified type was actually
7419 // qualified __strong.
7420 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7421 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7422 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7423
7424 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7425 return QualType();
7426
7427 if (GC_L == Qualifiers::Strong)
7428 return LHS;
7429 if (GC_R == Qualifiers::Strong)
7430 return RHS;
7431 return QualType();
7432 }
7433
7434 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7435 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7436 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7437 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7438 if (ResQT == LHSBaseQT)
7439 return LHS;
7440 if (ResQT == RHSBaseQT)
7441 return RHS;
7442 }
7443 return QualType();
7444}
7445
Chris Lattner5426bf62008-04-07 07:01:58 +00007446//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00007447// Integer Predicates
7448//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00007449
Jay Foad4ba2a172011-01-12 09:06:06 +00007450unsigned ASTContext::getIntWidth(QualType T) const {
John McCallf4c73712011-01-19 06:33:43 +00007451 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00007452 T = ET->getDecl()->getIntegerType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00007453 if (T->isBooleanType())
7454 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00007455 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00007456 return (unsigned)getTypeSize(T);
7457}
7458
Abramo Bagnara762f1592012-09-09 10:21:24 +00007459QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregorf6094622010-07-23 15:58:24 +00007460 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00007461
7462 // Turn <4 x signed int> -> <4 x unsigned int>
7463 if (const VectorType *VTy = T->getAs<VectorType>())
7464 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsone86d78c2010-11-10 21:56:12 +00007465 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattner6a2b9262009-10-17 20:33:28 +00007466
7467 // For enums, we return the unsigned version of the base type.
7468 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00007469 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00007470
7471 const BuiltinType *BTy = T->getAs<BuiltinType>();
7472 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00007473 switch (BTy->getKind()) {
7474 case BuiltinType::Char_S:
7475 case BuiltinType::SChar:
7476 return UnsignedCharTy;
7477 case BuiltinType::Short:
7478 return UnsignedShortTy;
7479 case BuiltinType::Int:
7480 return UnsignedIntTy;
7481 case BuiltinType::Long:
7482 return UnsignedLongTy;
7483 case BuiltinType::LongLong:
7484 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00007485 case BuiltinType::Int128:
7486 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00007487 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00007488 llvm_unreachable("Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00007489 }
7490}
7491
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00007492ASTMutationListener::~ASTMutationListener() { }
7493
Richard Smith9dadfab2013-05-11 05:45:24 +00007494void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7495 QualType ReturnType) {}
Chris Lattner86df27b2009-06-14 00:45:47 +00007496
7497//===----------------------------------------------------------------------===//
7498// Builtin Type Computation
7499//===----------------------------------------------------------------------===//
7500
7501/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattner33daae62010-10-01 22:42:38 +00007502/// pointer over the consumed characters. This returns the resultant type. If
7503/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7504/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7505/// a vector of "i*".
Chris Lattner14e0e742010-10-01 22:53:11 +00007506///
7507/// RequiresICE is filled in on return to indicate whether the value is required
7508/// to be an Integer Constant Expression.
Jay Foad4ba2a172011-01-12 09:06:06 +00007509static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00007510 ASTContext::GetBuiltinTypeError &Error,
Chris Lattner14e0e742010-10-01 22:53:11 +00007511 bool &RequiresICE,
Chris Lattner33daae62010-10-01 22:42:38 +00007512 bool AllowTypeModifiers) {
Chris Lattner86df27b2009-06-14 00:45:47 +00007513 // Modifiers.
7514 int HowLong = 0;
7515 bool Signed = false, Unsigned = false;
Chris Lattner14e0e742010-10-01 22:53:11 +00007516 RequiresICE = false;
Chris Lattner393bd8e2010-10-01 07:13:18 +00007517
Chris Lattner33daae62010-10-01 22:42:38 +00007518 // Read the prefixed modifiers first.
Chris Lattner86df27b2009-06-14 00:45:47 +00007519 bool Done = false;
7520 while (!Done) {
7521 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00007522 default: Done = true; --Str; break;
Chris Lattner393bd8e2010-10-01 07:13:18 +00007523 case 'I':
Chris Lattner14e0e742010-10-01 22:53:11 +00007524 RequiresICE = true;
Chris Lattner393bd8e2010-10-01 07:13:18 +00007525 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007526 case 'S':
7527 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7528 assert(!Signed && "Can't use 'S' modifier multiple times!");
7529 Signed = true;
7530 break;
7531 case 'U':
7532 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7533 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7534 Unsigned = true;
7535 break;
7536 case 'L':
7537 assert(HowLong <= 2 && "Can't have LLLL modifier");
7538 ++HowLong;
7539 break;
7540 }
7541 }
7542
7543 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00007544
Chris Lattner86df27b2009-06-14 00:45:47 +00007545 // Read the base type.
7546 switch (*Str++) {
David Blaikieb219cfc2011-09-23 05:06:16 +00007547 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattner86df27b2009-06-14 00:45:47 +00007548 case 'v':
7549 assert(HowLong == 0 && !Signed && !Unsigned &&
7550 "Bad modifiers used with 'v'!");
7551 Type = Context.VoidTy;
7552 break;
Jack Carter146522e2013-08-15 15:16:57 +00007553 case 'h':
7554 assert(HowLong == 0 && !Signed && !Unsigned &&
7555 "Bad modifiers used with 'f'!");
7556 Type = Context.HalfTy;
7557 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007558 case 'f':
7559 assert(HowLong == 0 && !Signed && !Unsigned &&
7560 "Bad modifiers used with 'f'!");
7561 Type = Context.FloatTy;
7562 break;
7563 case 'd':
7564 assert(HowLong < 2 && !Signed && !Unsigned &&
7565 "Bad modifiers used with 'd'!");
7566 if (HowLong)
7567 Type = Context.LongDoubleTy;
7568 else
7569 Type = Context.DoubleTy;
7570 break;
7571 case 's':
7572 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7573 if (Unsigned)
7574 Type = Context.UnsignedShortTy;
7575 else
7576 Type = Context.ShortTy;
7577 break;
7578 case 'i':
7579 if (HowLong == 3)
7580 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7581 else if (HowLong == 2)
7582 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7583 else if (HowLong == 1)
7584 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7585 else
7586 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7587 break;
7588 case 'c':
7589 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7590 if (Signed)
7591 Type = Context.SignedCharTy;
7592 else if (Unsigned)
7593 Type = Context.UnsignedCharTy;
7594 else
7595 Type = Context.CharTy;
7596 break;
7597 case 'b': // boolean
7598 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7599 Type = Context.BoolTy;
7600 break;
7601 case 'z': // size_t.
7602 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7603 Type = Context.getSizeType();
7604 break;
7605 case 'F':
7606 Type = Context.getCFConstantStringType();
7607 break;
Fariborz Jahanianba8bda02010-11-09 21:38:20 +00007608 case 'G':
7609 Type = Context.getObjCIdType();
7610 break;
7611 case 'H':
7612 Type = Context.getObjCSelType();
7613 break;
Fariborz Jahanianf7992132013-01-04 18:45:40 +00007614 case 'M':
7615 Type = Context.getObjCSuperType();
7616 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007617 case 'a':
7618 Type = Context.getBuiltinVaListType();
7619 assert(!Type.isNull() && "builtin va list type not initialized!");
7620 break;
7621 case 'A':
7622 // This is a "reference" to a va_list; however, what exactly
7623 // this means depends on how va_list is defined. There are two
7624 // different kinds of va_list: ones passed by value, and ones
7625 // passed by reference. An example of a by-value va_list is
7626 // x86, where va_list is a char*. An example of by-ref va_list
7627 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7628 // we want this argument to be a char*&; for x86-64, we want
7629 // it to be a __va_list_tag*.
7630 Type = Context.getBuiltinVaListType();
7631 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattner14e0e742010-10-01 22:53:11 +00007632 if (Type->isArrayType())
Chris Lattner86df27b2009-06-14 00:45:47 +00007633 Type = Context.getArrayDecayedType(Type);
Chris Lattner14e0e742010-10-01 22:53:11 +00007634 else
Chris Lattner86df27b2009-06-14 00:45:47 +00007635 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00007636 break;
7637 case 'V': {
7638 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00007639 unsigned NumElements = strtoul(Str, &End, 10);
7640 assert(End != Str && "Missing vector size");
Chris Lattner86df27b2009-06-14 00:45:47 +00007641 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00007642
Chris Lattner14e0e742010-10-01 22:53:11 +00007643 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7644 RequiresICE, false);
7645 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattner33daae62010-10-01 22:42:38 +00007646
7647 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner788b0fd2010-06-23 06:00:24 +00007648 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00007649 VectorType::GenericVector);
Chris Lattner86df27b2009-06-14 00:45:47 +00007650 break;
7651 }
Douglas Gregorb4bc99b2012-06-07 18:08:25 +00007652 case 'E': {
7653 char *End;
7654
7655 unsigned NumElements = strtoul(Str, &End, 10);
7656 assert(End != Str && "Missing vector size");
7657
7658 Str = End;
7659
7660 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7661 false);
7662 Type = Context.getExtVectorType(ElementType, NumElements);
7663 break;
7664 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00007665 case 'X': {
Chris Lattner14e0e742010-10-01 22:53:11 +00007666 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7667 false);
7668 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregord3a23b22009-09-28 21:45:01 +00007669 Type = Context.getComplexType(ElementType);
7670 break;
Fariborz Jahaniancc075e42011-08-23 23:33:09 +00007671 }
7672 case 'Y' : {
7673 Type = Context.getPointerDiffType();
7674 break;
7675 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00007676 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00007677 Type = Context.getFILEType();
7678 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00007679 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00007680 return QualType();
7681 }
Mike Stumpfd612db2009-07-28 23:47:15 +00007682 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00007683 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00007684 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00007685 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00007686 else
7687 Type = Context.getjmp_bufType();
7688
Mike Stumpfd612db2009-07-28 23:47:15 +00007689 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00007690 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00007691 return QualType();
7692 }
7693 break;
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +00007694 case 'K':
7695 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7696 Type = Context.getucontext_tType();
7697
7698 if (Type.isNull()) {
7699 Error = ASTContext::GE_Missing_ucontext;
7700 return QualType();
7701 }
7702 break;
Eli Friedman6902e412012-11-27 02:58:24 +00007703 case 'p':
7704 Type = Context.getProcessIDType();
7705 break;
Mike Stump782fa302009-07-28 02:25:19 +00007706 }
Mike Stump1eb44332009-09-09 15:08:12 +00007707
Chris Lattner33daae62010-10-01 22:42:38 +00007708 // If there are modifiers and if we're allowed to parse them, go for it.
7709 Done = !AllowTypeModifiers;
Chris Lattner86df27b2009-06-14 00:45:47 +00007710 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00007711 switch (char c = *Str++) {
Chris Lattner33daae62010-10-01 22:42:38 +00007712 default: Done = true; --Str; break;
7713 case '*':
7714 case '&': {
7715 // Both pointers and references can have their pointee types
7716 // qualified with an address space.
7717 char *End;
7718 unsigned AddrSpace = strtoul(Str, &End, 10);
7719 if (End != Str && AddrSpace != 0) {
7720 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7721 Str = End;
7722 }
7723 if (c == '*')
7724 Type = Context.getPointerType(Type);
7725 else
7726 Type = Context.getLValueReferenceType(Type);
7727 break;
7728 }
7729 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7730 case 'C':
7731 Type = Type.withConst();
7732 break;
7733 case 'D':
7734 Type = Context.getVolatileType(Type);
7735 break;
Ted Kremenek18932a02012-01-20 21:40:12 +00007736 case 'R':
7737 Type = Type.withRestrict();
7738 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007739 }
7740 }
Chris Lattner393bd8e2010-10-01 07:13:18 +00007741
Chris Lattner14e0e742010-10-01 22:53:11 +00007742 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner393bd8e2010-10-01 07:13:18 +00007743 "Integer constant 'I' type must be an integer");
Mike Stump1eb44332009-09-09 15:08:12 +00007744
Chris Lattner86df27b2009-06-14 00:45:47 +00007745 return Type;
7746}
7747
7748/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattner33daae62010-10-01 22:42:38 +00007749QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattner14e0e742010-10-01 22:53:11 +00007750 GetBuiltinTypeError &Error,
Jay Foad4ba2a172011-01-12 09:06:06 +00007751 unsigned *IntegerConstantArgs) const {
Chris Lattner33daae62010-10-01 22:42:38 +00007752 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump1eb44332009-09-09 15:08:12 +00007753
Chris Lattner5f9e2722011-07-23 10:55:15 +00007754 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00007755
Chris Lattner14e0e742010-10-01 22:53:11 +00007756 bool RequiresICE = false;
Chris Lattner86df27b2009-06-14 00:45:47 +00007757 Error = GE_None;
Chris Lattner14e0e742010-10-01 22:53:11 +00007758 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7759 RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00007760 if (Error != GE_None)
7761 return QualType();
Chris Lattner14e0e742010-10-01 22:53:11 +00007762
7763 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7764
Chris Lattner86df27b2009-06-14 00:45:47 +00007765 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattner14e0e742010-10-01 22:53:11 +00007766 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00007767 if (Error != GE_None)
7768 return QualType();
7769
Chris Lattner14e0e742010-10-01 22:53:11 +00007770 // If this argument is required to be an IntegerConstantExpression and the
7771 // caller cares, fill in the bitmask we return.
7772 if (RequiresICE && IntegerConstantArgs)
7773 *IntegerConstantArgs |= 1 << ArgTypes.size();
7774
Chris Lattner86df27b2009-06-14 00:45:47 +00007775 // Do array -> pointer decay. The builtin should use the decayed type.
7776 if (Ty->isArrayType())
7777 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00007778
Chris Lattner86df27b2009-06-14 00:45:47 +00007779 ArgTypes.push_back(Ty);
7780 }
7781
7782 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7783 "'.' should only occur at end of builtin type list!");
7784
Reid Kleckneref072032013-08-27 23:08:25 +00007785 FunctionType::ExtInfo EI(CC_C);
John McCall00ccbef2010-12-21 00:44:39 +00007786 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7787
7788 bool Variadic = (TypeStr[0] == '.');
7789
7790 // We really shouldn't be making a no-proto type here, especially in C++.
7791 if (ArgTypes.empty() && Variadic)
7792 return getFunctionNoProtoType(ResType, EI);
Douglas Gregorce056bc2010-02-21 22:15:06 +00007793
John McCalle23cf432010-12-14 08:05:40 +00007794 FunctionProtoType::ExtProtoInfo EPI;
John McCall00ccbef2010-12-21 00:44:39 +00007795 EPI.ExtInfo = EI;
7796 EPI.Variadic = Variadic;
John McCalle23cf432010-12-14 08:05:40 +00007797
Jordan Rosebea522f2013-03-08 21:51:21 +00007798 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattner86df27b2009-06-14 00:45:47 +00007799}
Eli Friedmana95d7572009-08-19 07:44:53 +00007800
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007801GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007802 if (!FD->isExternallyVisible())
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007803 return GVA_Internal;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007804
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007805 GVALinkage External = GVA_StrongExternal;
7806 switch (FD->getTemplateSpecializationKind()) {
7807 case TSK_Undeclared:
7808 case TSK_ExplicitSpecialization:
7809 External = GVA_StrongExternal;
7810 break;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007811
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007812 case TSK_ExplicitInstantiationDefinition:
7813 return GVA_ExplicitTemplateInstantiation;
7814
7815 case TSK_ExplicitInstantiationDeclaration:
7816 case TSK_ImplicitInstantiation:
7817 External = GVA_TemplateInstantiation;
7818 break;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007819 }
7820
7821 if (!FD->isInlined())
7822 return External;
David Majnemer13163702013-08-01 17:26:42 +00007823
7824 if ((!getLangOpts().CPlusPlus && !getLangOpts().MicrosoftMode) ||
7825 FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007826 // GNU or C99 inline semantics. Determine whether this symbol should be
7827 // externally visible.
7828 if (FD->isInlineDefinitionExternallyVisible())
7829 return External;
7830
7831 // C99 inline semantics, where the symbol is not externally visible.
7832 return GVA_C99Inline;
7833 }
7834
7835 // C++0x [temp.explicit]p9:
7836 // [ Note: The intent is that an inline function that is the subject of
7837 // an explicit instantiation declaration will still be implicitly
7838 // instantiated when used so that the body can be considered for
7839 // inlining, but that no out-of-line copy of the inline function would be
7840 // generated in the translation unit. -- end note ]
7841 if (FD->getTemplateSpecializationKind()
7842 == TSK_ExplicitInstantiationDeclaration)
7843 return GVA_C99Inline;
7844
7845 return GVA_CXXInline;
7846}
7847
7848GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007849 if (!VD->isExternallyVisible())
7850 return GVA_Internal;
7851
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007852 // If this is a static data member, compute the kind of template
7853 // specialization. Otherwise, this variable is not part of a
7854 // template.
7855 TemplateSpecializationKind TSK = TSK_Undeclared;
7856 if (VD->isStaticDataMember())
7857 TSK = VD->getTemplateSpecializationKind();
7858
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007859 switch (TSK) {
7860 case TSK_Undeclared:
7861 case TSK_ExplicitSpecialization:
7862 return GVA_StrongExternal;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007863
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007864 case TSK_ExplicitInstantiationDeclaration:
7865 llvm_unreachable("Variable should not be instantiated");
7866 // Fall through to treat this like any other instantiation.
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007867
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007868 case TSK_ExplicitInstantiationDefinition:
7869 return GVA_ExplicitTemplateInstantiation;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007870
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007871 case TSK_ImplicitInstantiation:
7872 return GVA_TemplateInstantiation;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007873 }
Rafael Espindola77b50252013-05-13 14:05:53 +00007874
7875 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007876}
7877
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +00007878bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007879 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7880 if (!VD->isFileVarDecl())
7881 return false;
Richard Smithf396ad92013-04-01 20:22:16 +00007882 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7883 // We never need to emit an uninstantiated function template.
7884 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
7885 return false;
7886 } else
7887 return false;
7888
7889 // If this is a member of a class template, we do not need to emit it.
7890 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007891 return false;
7892
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00007893 // Weak references don't produce any output by themselves.
7894 if (D->hasAttr<WeakRefAttr>())
7895 return false;
7896
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007897 // Aliases and used decls are required.
7898 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7899 return true;
7900
7901 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7902 // Forward declarations aren't required.
Sean Hunt10620eb2011-05-06 20:44:56 +00007903 if (!FD->doesThisDeclarationHaveABody())
Nick Lewyckydce67a72011-07-18 05:26:13 +00007904 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007905
7906 // Constructors and destructors are required.
7907 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7908 return true;
7909
John McCalld5617ee2013-01-25 22:31:03 +00007910 // The key function for a class is required. This rule only comes
7911 // into play when inline functions can be key functions, though.
7912 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7913 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7914 const CXXRecordDecl *RD = MD->getParent();
7915 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7916 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
7917 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7918 return true;
7919 }
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007920 }
7921 }
7922
7923 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7924
7925 // static, static inline, always_inline, and extern inline functions can
7926 // always be deferred. Normal inline functions can be deferred in C99/C++.
7927 // Implicit template instantiations can also be deferred in C++.
7928 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev3a5aca82012-02-02 06:06:34 +00007929 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007930 return false;
7931 return true;
7932 }
Douglas Gregor94da1582011-09-10 00:22:34 +00007933
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007934 const VarDecl *VD = cast<VarDecl>(D);
7935 assert(VD->isFileVarDecl() && "Expected file scoped var");
7936
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00007937 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7938 return false;
7939
Richard Smith5f9a7e32012-11-12 21:38:00 +00007940 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007941 GVALinkage L = GetGVALinkageForVariable(VD);
Richard Smith5f9a7e32012-11-12 21:38:00 +00007942 if (L != GVA_Internal && L != GVA_TemplateInstantiation)
7943 return true;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007944
Richard Smith5f9a7e32012-11-12 21:38:00 +00007945 // Variables that have destruction with side-effects are required.
7946 if (VD->getType().isDestructedType())
7947 return true;
7948
7949 // Variables that have initialization with side-effects are required.
7950 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
7951 return true;
7952
7953 return false;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007954}
Charles Davis071cc7d2010-08-16 03:33:14 +00007955
Reid Kleckneref072032013-08-27 23:08:25 +00007956CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
7957 bool IsCXXMethod) const {
Charles Davisee743f92010-11-09 18:04:24 +00007958 // Pass through to the C++ ABI object
Reid Kleckneref072032013-08-27 23:08:25 +00007959 if (IsCXXMethod)
7960 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007961
Reid Kleckneref072032013-08-27 23:08:25 +00007962 return (LangOpts.MRTD && !IsVariadic) ? CC_X86StdCall : CC_C;
Charles Davisee743f92010-11-09 18:04:24 +00007963}
7964
Jay Foad4ba2a172011-01-12 09:06:06 +00007965bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlssondae0cb52010-11-25 01:51:53 +00007966 // Pass through to the C++ ABI object
7967 return ABI->isNearlyEmpty(RD);
7968}
7969
Peter Collingbourne14110472011-01-13 18:57:25 +00007970MangleContext *ASTContext::createMangleContext() {
John McCallb8b2c9d2013-01-25 22:30:49 +00007971 switch (Target->getCXXABI().getKind()) {
Tim Northoverc264e162013-01-31 12:13:10 +00007972 case TargetCXXABI::GenericAArch64:
John McCallb8b2c9d2013-01-25 22:30:49 +00007973 case TargetCXXABI::GenericItanium:
7974 case TargetCXXABI::GenericARM:
7975 case TargetCXXABI::iOS:
Peter Collingbourne14110472011-01-13 18:57:25 +00007976 return createItaniumMangleContext(*this, getDiagnostics());
John McCallb8b2c9d2013-01-25 22:30:49 +00007977 case TargetCXXABI::Microsoft:
Peter Collingbourne14110472011-01-13 18:57:25 +00007978 return createMicrosoftMangleContext(*this, getDiagnostics());
7979 }
David Blaikieb219cfc2011-09-23 05:06:16 +00007980 llvm_unreachable("Unsupported ABI");
Peter Collingbourne14110472011-01-13 18:57:25 +00007981}
7982
Charles Davis071cc7d2010-08-16 03:33:14 +00007983CXXABI::~CXXABI() {}
Ted Kremenekba29bd22011-04-28 04:53:38 +00007984
7985size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufoef4579c2013-08-06 01:03:05 +00007986 return ASTRecordLayouts.getMemorySize() +
7987 llvm::capacity_in_bytes(ObjCLayouts) +
7988 llvm::capacity_in_bytes(KeyFunctions) +
7989 llvm::capacity_in_bytes(ObjCImpls) +
7990 llvm::capacity_in_bytes(BlockVarCopyInits) +
7991 llvm::capacity_in_bytes(DeclAttrs) +
7992 llvm::capacity_in_bytes(TemplateOrInstantiation) +
7993 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
7994 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
7995 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
7996 llvm::capacity_in_bytes(OverriddenMethods) +
7997 llvm::capacity_in_bytes(Types) +
7998 llvm::capacity_in_bytes(VariableArrayTypes) +
7999 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekba29bd22011-04-28 04:53:38 +00008000}
Ted Kremenekd211cb72011-10-06 05:00:56 +00008001
Stepan Dyatkovskiy7b7bef12013-09-05 11:23:21 +00008002/// getIntTypeForBitwidth -
8003/// sets integer QualTy according to specified details:
8004/// bitwidth, signed/unsigned.
8005/// Returns empty type if there is no appropriate target types.
8006QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
8007 unsigned Signed) const {
8008 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
8009 CanQualType QualTy = getFromTargetType(Ty);
8010 if (!QualTy && DestWidth == 128)
8011 return Signed ? Int128Ty : UnsignedInt128Ty;
8012 return QualTy;
8013}
8014
8015/// getRealTypeForBitwidth -
8016/// sets floating point QualTy according to specified bitwidth.
8017/// Returns empty type if there is no appropriate target types.
8018QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
8019 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
8020 switch (Ty) {
8021 case TargetInfo::Float:
8022 return FloatTy;
8023 case TargetInfo::Double:
8024 return DoubleTy;
8025 case TargetInfo::LongDouble:
8026 return LongDoubleTy;
8027 case TargetInfo::NoFloat:
8028 return QualType();
8029 }
8030
8031 llvm_unreachable("Unhandled TargetInfo::RealType value");
8032}
8033
Eli Friedman5e867c82013-07-10 00:30:46 +00008034void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
8035 if (Number > 1)
8036 MangleNumbers[ND] = Number;
David Blaikie66cff722012-11-14 01:52:05 +00008037}
8038
Eli Friedman5e867c82013-07-10 00:30:46 +00008039unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
8040 llvm::DenseMap<const NamedDecl *, unsigned>::const_iterator I =
8041 MangleNumbers.find(ND);
8042 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie66cff722012-11-14 01:52:05 +00008043}
8044
Eli Friedman5e867c82013-07-10 00:30:46 +00008045MangleNumberingContext &
8046ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Kleckner942f9fe2013-09-10 20:14:30 +00008047 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
8048 MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
8049 if (!MCtx)
8050 MCtx = createMangleNumberingContext();
8051 return *MCtx;
8052}
8053
8054MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
8055 return ABI->createMangleNumberingContext();
Douglas Gregor9e8c92a2012-02-20 19:44:39 +00008056}
8057
Ted Kremenekd211cb72011-10-06 05:00:56 +00008058void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8059 ParamIndices[D] = index;
8060}
8061
8062unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8063 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8064 assert(I != ParamIndices.end() &&
8065 "ParmIndices lacks entry set by ParmVarDecl");
8066 return I->second;
8067}
Fariborz Jahanian538bbe52013-05-28 17:37:39 +00008068
Richard Smith211c8dd2013-06-05 00:46:14 +00008069APValue *
8070ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8071 bool MayCreate) {
8072 assert(E && E->getStorageDuration() == SD_Static &&
8073 "don't need to cache the computed value for this temporary");
8074 if (MayCreate)
8075 return &MaterializedTemporaryValues[E];
8076
8077 llvm::DenseMap<const MaterializeTemporaryExpr *, APValue>::iterator I =
8078 MaterializedTemporaryValues.find(E);
8079 return I == MaterializedTemporaryValues.end() ? 0 : &I->second;
8080}
8081
Fariborz Jahanian538bbe52013-05-28 17:37:39 +00008082bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8083 const llvm::Triple &T = getTargetInfo().getTriple();
8084 if (!T.isOSDarwin())
8085 return false;
8086
8087 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8088 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8089 uint64_t Size = sizeChars.getQuantity();
8090 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8091 unsigned Align = alignChars.getQuantity();
8092 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8093 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8094}
Reid Klecknercff15122013-06-17 12:56:08 +00008095
8096namespace {
8097
8098 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8099 /// parents as defined by the \c RecursiveASTVisitor.
8100 ///
8101 /// Note that the relationship described here is purely in terms of AST
8102 /// traversal - there are other relationships (for example declaration context)
8103 /// in the AST that are better modeled by special matchers.
8104 ///
8105 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
8106 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
8107
8108 public:
8109 /// \brief Builds and returns the translation unit's parent map.
8110 ///
8111 /// The caller takes ownership of the returned \c ParentMap.
8112 static ASTContext::ParentMap *buildMap(TranslationUnitDecl &TU) {
8113 ParentMapASTVisitor Visitor(new ASTContext::ParentMap);
8114 Visitor.TraverseDecl(&TU);
8115 return Visitor.Parents;
8116 }
8117
8118 private:
8119 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8120
8121 ParentMapASTVisitor(ASTContext::ParentMap *Parents) : Parents(Parents) {
8122 }
8123
8124 bool shouldVisitTemplateInstantiations() const {
8125 return true;
8126 }
8127 bool shouldVisitImplicitCode() const {
8128 return true;
8129 }
8130 // Disables data recursion. We intercept Traverse* methods in the RAV, which
8131 // are not triggered during data recursion.
8132 bool shouldUseDataRecursionFor(clang::Stmt *S) const {
8133 return false;
8134 }
8135
8136 template <typename T>
8137 bool TraverseNode(T *Node, bool(VisitorBase:: *traverse) (T *)) {
8138 if (Node == NULL)
8139 return true;
8140 if (ParentStack.size() > 0)
8141 // FIXME: Currently we add the same parent multiple times, for example
8142 // when we visit all subexpressions of template instantiations; this is
8143 // suboptimal, bug benign: the only way to visit those is with
8144 // hasAncestor / hasParent, and those do not create new matches.
8145 // The plan is to enable DynTypedNode to be storable in a map or hash
8146 // map. The main problem there is to implement hash functions /
8147 // comparison operators for all types that DynTypedNode supports that
8148 // do not have pointer identity.
8149 (*Parents)[Node].push_back(ParentStack.back());
8150 ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node));
8151 bool Result = (this ->* traverse) (Node);
8152 ParentStack.pop_back();
8153 return Result;
8154 }
8155
8156 bool TraverseDecl(Decl *DeclNode) {
8157 return TraverseNode(DeclNode, &VisitorBase::TraverseDecl);
8158 }
8159
8160 bool TraverseStmt(Stmt *StmtNode) {
8161 return TraverseNode(StmtNode, &VisitorBase::TraverseStmt);
8162 }
8163
8164 ASTContext::ParentMap *Parents;
8165 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8166
8167 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8168 };
8169
8170} // end namespace
8171
8172ASTContext::ParentVector
8173ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
8174 assert(Node.getMemoizationData() &&
8175 "Invariant broken: only nodes that support memoization may be "
8176 "used in the parent map.");
8177 if (!AllParents) {
8178 // We always need to run over the whole translation unit, as
8179 // hasAncestor can escape any subtree.
8180 AllParents.reset(
8181 ParentMapASTVisitor::buildMap(*getTranslationUnitDecl()));
8182 }
8183 ParentMap::const_iterator I = AllParents->find(Node.getMemoizationData());
8184 if (I == AllParents->end()) {
8185 return ParentVector();
8186 }
8187 return I->second;
8188}
Fariborz Jahanianad4aaf12013-07-15 21:22:08 +00008189
8190bool
8191ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
8192 const ObjCMethodDecl *MethodImpl) {
8193 // No point trying to match an unavailable/deprecated mothod.
8194 if (MethodDecl->hasAttr<UnavailableAttr>()
8195 || MethodDecl->hasAttr<DeprecatedAttr>())
8196 return false;
8197 if (MethodDecl->getObjCDeclQualifier() !=
8198 MethodImpl->getObjCDeclQualifier())
8199 return false;
8200 if (!hasSameType(MethodDecl->getResultType(),
8201 MethodImpl->getResultType()))
8202 return false;
8203
8204 if (MethodDecl->param_size() != MethodImpl->param_size())
8205 return false;
8206
8207 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
8208 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
8209 EF = MethodDecl->param_end();
8210 IM != EM && IF != EF; ++IM, ++IF) {
8211 const ParmVarDecl *DeclVar = (*IF);
8212 const ParmVarDecl *ImplVar = (*IM);
8213 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
8214 return false;
8215 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
8216 return false;
8217 }
8218 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
8219
8220}