blob: 91059400761f90c45d45b19b0a22a79d4e4653e1 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000015#include "CXXABI.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000016#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/Attr.h"
Ken Dyckbdc601b2009-12-22 14:23:30 +000018#include "clang/AST/CharUnits.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000019#include "clang/AST/Comment.h"
Dmitri Gribenkoaa580812012-08-09 00:03:17 +000020#include "clang/AST/CommentCommandTraits.h"
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +000021#include "clang/AST/DeclCXX.h"
Steve Naroff980e5082007-10-01 19:00:59 +000022#include "clang/AST/DeclObjC.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000023#include "clang/AST/DeclTemplate.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000024#include "clang/AST/Expr.h"
John McCallea1471e2010-05-20 01:18:31 +000025#include "clang/AST/ExprCXX.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000026#include "clang/AST/ExternalASTSource.h"
Peter Collingbourne14110472011-01-13 18:57:25 +000027#include "clang/AST/Mangle.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000028#include "clang/AST/RecordLayout.h"
Reid Klecknercff15122013-06-17 12:56:08 +000029#include "clang/AST/RecursiveASTVisitor.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000030#include "clang/AST/TypeLoc.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000031#include "clang/Basic/Builtins.h"
Chris Lattnera9376d42009-03-28 03:45:20 +000032#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000033#include "clang/Basic/TargetInfo.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000034#include "llvm/ADT/SmallString.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000035#include "llvm/ADT/StringExtras.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000036#include "llvm/Support/Capacity.h"
Nate Begeman6fe7c8a2009-01-18 06:42:49 +000037#include "llvm/Support/MathExtras.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000038#include "llvm/Support/raw_ostream.h"
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +000039#include <map>
Anders Carlsson29445a02009-07-18 21:19:52 +000040
Reid Spencer5f016e22007-07-11 17:01:13 +000041using namespace clang;
42
Douglas Gregor18274032010-07-03 00:47:00 +000043unsigned ASTContext::NumImplicitDefaultConstructors;
44unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregor22584312010-07-02 23:41:54 +000045unsigned ASTContext::NumImplicitCopyConstructors;
46unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Sean Huntffe37fd2011-05-25 20:50:04 +000047unsigned ASTContext::NumImplicitMoveConstructors;
48unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregora376d102010-07-02 21:50:04 +000049unsigned ASTContext::NumImplicitCopyAssignmentOperators;
50unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Huntffe37fd2011-05-25 20:50:04 +000051unsigned ASTContext::NumImplicitMoveAssignmentOperators;
52unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor4923aa22010-07-02 20:37:36 +000053unsigned ASTContext::NumImplicitDestructors;
54unsigned ASTContext::NumImplicitDestructorsDeclared;
55
Reid Spencer5f016e22007-07-11 17:01:13 +000056enum FloatingRank {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +000057 HalfRank, FloatRank, DoubleRank, LongDoubleRank
Reid Spencer5f016e22007-07-11 17:01:13 +000058};
59
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +000060RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +000061 if (!CommentsLoaded && ExternalSource) {
62 ExternalSource->ReadComments();
63 CommentsLoaded = true;
64 }
65
66 assert(D);
67
Dmitri Gribenkoc3fee352012-06-28 16:19:39 +000068 // User can not attach documentation to implicit declarations.
69 if (D->isImplicit())
70 return NULL;
71
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +000072 // User can not attach documentation to implicit instantiations.
73 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
74 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
75 return NULL;
76 }
77
Dmitri Gribenkodce750b2012-08-20 22:36:31 +000078 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
79 if (VD->isStaticDataMember() &&
80 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
81 return NULL;
82 }
83
84 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
85 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
86 return NULL;
87 }
88
Dmitri Gribenkod1e5c0d2013-01-27 21:18:39 +000089 if (const ClassTemplateSpecializationDecl *CTSD =
90 dyn_cast<ClassTemplateSpecializationDecl>(D)) {
91 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
92 if (TSK == TSK_ImplicitInstantiation ||
93 TSK == TSK_Undeclared)
94 return NULL;
95 }
96
Dmitri Gribenkodce750b2012-08-20 22:36:31 +000097 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
98 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
99 return NULL;
100 }
Fariborz Jahanian099ecfb2013-04-17 21:05:20 +0000101 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
102 // When tag declaration (but not definition!) is part of the
103 // decl-specifier-seq of some other declaration, it doesn't get comment
104 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
105 return NULL;
106 }
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000107 // TODO: handle comments for function parameters properly.
108 if (isa<ParmVarDecl>(D))
109 return NULL;
110
Dmitri Gribenko96b09862012-07-31 22:37:06 +0000111 // TODO: we could look up template parameter documentation in the template
112 // documentation.
113 if (isa<TemplateTypeParmDecl>(D) ||
114 isa<NonTypeTemplateParmDecl>(D) ||
115 isa<TemplateTemplateParmDecl>(D))
116 return NULL;
117
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000118 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000119
120 // If there are no comments anywhere, we won't find anything.
121 if (RawComments.empty())
122 return NULL;
123
Dmitri Gribenkoabd56c82012-07-13 01:06:46 +0000124 // Find declaration location.
125 // For Objective-C declarations we generally don't expect to have multiple
126 // declarators, thus use declaration starting location as the "declaration
127 // location".
128 // For all other declarations multiple declarators are used quite frequently,
129 // so we use the location of the identifier as the "declaration location".
130 SourceLocation DeclLoc;
131 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko96b09862012-07-31 22:37:06 +0000132 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +0000133 isa<RedeclarableTemplateDecl>(D) ||
134 isa<ClassTemplateSpecializationDecl>(D))
Dmitri Gribenkoabd56c82012-07-13 01:06:46 +0000135 DeclLoc = D->getLocStart();
136 else
137 DeclLoc = D->getLocation();
138
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000139 // If the declaration doesn't map directly to a location in a file, we
140 // can't find the comment.
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000141 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
142 return NULL;
143
144 // Find the comment that occurs just after this declaration.
Dmitri Gribenkoa444f182012-07-17 22:01:09 +0000145 ArrayRef<RawComment *>::iterator Comment;
146 {
147 // When searching for comments during parsing, the comment we are looking
148 // for is usually among the last two comments we parsed -- check them
149 // first.
Dmitri Gribenko6fd7d302013-04-10 15:35:17 +0000150 RawComment CommentAtDeclLoc(
151 SourceMgr, SourceRange(DeclLoc), false,
152 LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenkoa444f182012-07-17 22:01:09 +0000153 BeforeThanCompare<RawComment> Compare(SourceMgr);
154 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
155 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
156 if (!Found && RawComments.size() >= 2) {
157 MaybeBeforeDecl--;
158 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
159 }
160
161 if (Found) {
162 Comment = MaybeBeforeDecl + 1;
163 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
164 &CommentAtDeclLoc, Compare));
165 } else {
166 // Slow path.
167 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
168 &CommentAtDeclLoc, Compare);
169 }
170 }
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000171
172 // Decompose the location for the declaration and find the beginning of the
173 // file buffer.
174 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
175
176 // First check whether we have a trailing comment.
177 if (Comment != RawComments.end() &&
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000178 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
Dmitri Gribenko9c006762012-07-06 23:27:33 +0000179 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D))) {
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000180 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000181 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000182 // Check that Doxygen trailing comment comes after the declaration, starts
183 // on the same line and in the same file as the declaration.
184 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
185 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
186 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
187 CommentBeginDecomp.second)) {
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000188 return *Comment;
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000189 }
190 }
191
192 // The comment just after the declaration was not a trailing comment.
193 // Let's look at the previous comment.
194 if (Comment == RawComments.begin())
195 return NULL;
196 --Comment;
197
198 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000199 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000200 return NULL;
201
202 // Decompose the end of the comment.
203 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000204 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000205
206 // If the comment and the declaration aren't in the same file, then they
207 // aren't related.
208 if (DeclLocDecomp.first != CommentEndDecomp.first)
209 return NULL;
210
211 // Get the corresponding buffer.
212 bool Invalid = false;
213 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
214 &Invalid).data();
215 if (Invalid)
216 return NULL;
217
218 // Extract text between the comment and declaration.
219 StringRef Text(Buffer + CommentEndDecomp.second,
220 DeclLocDecomp.second - CommentEndDecomp.second);
221
Dmitri Gribenko8bdb58a2012-06-27 23:43:37 +0000222 // There should be no other declarations or preprocessor directives between
223 // comment and declaration.
Dmitri Gribenkoabd56c82012-07-13 01:06:46 +0000224 if (Text.find_first_of(",;{}#@") != StringRef::npos)
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000225 return NULL;
226
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000227 return *Comment;
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000228}
229
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000230namespace {
231/// If we have a 'templated' declaration for a template, adjust 'D' to
232/// refer to the actual template.
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000233/// If we have an implicit instantiation, adjust 'D' to refer to template.
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000234const Decl *adjustDeclToTemplate(const Decl *D) {
Douglas Gregorcd81df22012-08-13 16:37:30 +0000235 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000236 // Is this function declaration part of a function template?
Douglas Gregorcd81df22012-08-13 16:37:30 +0000237 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000238 return FTD;
239
240 // Nothing to do if function is not an implicit instantiation.
241 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
242 return D;
243
244 // Function is an implicit instantiation of a function template?
245 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
246 return FTD;
247
248 // Function is instantiated from a member definition of a class template?
249 if (const FunctionDecl *MemberDecl =
250 FD->getInstantiatedFromMemberFunction())
251 return MemberDecl;
252
253 return D;
Douglas Gregorcd81df22012-08-13 16:37:30 +0000254 }
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000255 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
256 // Static data member is instantiated from a member definition of a class
257 // template?
258 if (VD->isStaticDataMember())
259 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
260 return MemberDecl;
261
262 return D;
263 }
264 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
265 // Is this class declaration part of a class template?
266 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
267 return CTD;
268
269 // Class is an implicit instantiation of a class template or partial
270 // specialization?
271 if (const ClassTemplateSpecializationDecl *CTSD =
272 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
273 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
274 return D;
275 llvm::PointerUnion<ClassTemplateDecl *,
276 ClassTemplatePartialSpecializationDecl *>
277 PU = CTSD->getSpecializedTemplateOrPartial();
278 return PU.is<ClassTemplateDecl*>() ?
279 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
280 static_cast<const Decl*>(
281 PU.get<ClassTemplatePartialSpecializationDecl *>());
282 }
283
284 // Class is instantiated from a member definition of a class template?
285 if (const MemberSpecializationInfo *Info =
286 CRD->getMemberSpecializationInfo())
287 return Info->getInstantiatedFrom();
288
289 return D;
290 }
291 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
292 // Enum is instantiated from a member definition of a class template?
293 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
294 return MemberDecl;
295
296 return D;
297 }
298 // FIXME: Adjust alias templates?
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000299 return D;
300}
301} // unnamed namespace
302
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000303const RawComment *ASTContext::getRawCommentForAnyRedecl(
304 const Decl *D,
305 const Decl **OriginalDecl) const {
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000306 D = adjustDeclToTemplate(D);
Douglas Gregorcd81df22012-08-13 16:37:30 +0000307
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000308 // Check whether we have cached a comment for this declaration already.
309 {
310 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
311 RedeclComments.find(D);
312 if (Pos != RedeclComments.end()) {
313 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000314 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
315 if (OriginalDecl)
316 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000317 return Raw.getRaw();
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000318 }
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000319 }
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000320 }
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000321
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000322 // Search for comments attached to declarations in the redeclaration chain.
323 const RawComment *RC = NULL;
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000324 const Decl *OriginalDeclForRC = NULL;
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000325 for (Decl::redecl_iterator I = D->redecls_begin(),
326 E = D->redecls_end();
327 I != E; ++I) {
328 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
329 RedeclComments.find(*I);
330 if (Pos != RedeclComments.end()) {
331 const RawCommentAndCacheFlags &Raw = Pos->second;
332 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
333 RC = Raw.getRaw();
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000334 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000335 break;
336 }
337 } else {
338 RC = getRawCommentForDeclNoCache(*I);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000339 OriginalDeclForRC = *I;
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000340 RawCommentAndCacheFlags Raw;
341 if (RC) {
342 Raw.setRaw(RC);
343 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
344 } else
345 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000346 Raw.setOriginalDecl(*I);
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000347 RedeclComments[*I] = Raw;
348 if (RC)
349 break;
350 }
351 }
352
Dmitri Gribenko8376f592012-06-28 16:25:36 +0000353 // If we found a comment, it should be a documentation comment.
354 assert(!RC || RC->isDocumentation());
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000355
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000356 if (OriginalDecl)
357 *OriginalDecl = OriginalDeclForRC;
358
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000359 // Update cache for every declaration in the redeclaration chain.
360 RawCommentAndCacheFlags Raw;
361 Raw.setRaw(RC);
362 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000363 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000364
365 for (Decl::redecl_iterator I = D->redecls_begin(),
366 E = D->redecls_end();
367 I != E; ++I) {
368 RawCommentAndCacheFlags &R = RedeclComments[*I];
369 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
370 R = Raw;
371 }
372
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000373 return RC;
374}
375
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000376static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
377 SmallVectorImpl<const NamedDecl *> &Redeclared) {
378 const DeclContext *DC = ObjCMethod->getDeclContext();
379 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
380 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
381 if (!ID)
382 return;
383 // Add redeclared method here.
Douglas Gregord3297242013-01-16 23:00:23 +0000384 for (ObjCInterfaceDecl::known_extensions_iterator
385 Ext = ID->known_extensions_begin(),
386 ExtEnd = ID->known_extensions_end();
387 Ext != ExtEnd; ++Ext) {
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000388 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregord3297242013-01-16 23:00:23 +0000389 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000390 ObjCMethod->isInstanceMethod()))
391 Redeclared.push_back(RedeclaredMethod);
392 }
393 }
394}
395
Fariborz Jahanian749ace62012-10-11 23:52:50 +0000396comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
397 const Decl *D) const {
398 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
399 ThisDeclInfo->CommentDecl = D;
400 ThisDeclInfo->IsFilled = false;
401 ThisDeclInfo->fill();
402 ThisDeclInfo->CommentDecl = FC->getDecl();
403 comments::FullComment *CFC =
404 new (*this) comments::FullComment(FC->getBlocks(),
405 ThisDeclInfo);
406 return CFC;
407
408}
409
Richard Smith0a74a4c2013-05-21 05:24:00 +0000410comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
411 const RawComment *RC = getRawCommentForDeclNoCache(D);
412 return RC ? RC->parse(*this, 0, D) : 0;
413}
414
Dmitri Gribenko19523542012-09-29 11:40:46 +0000415comments::FullComment *ASTContext::getCommentForDecl(
416 const Decl *D,
417 const Preprocessor *PP) const {
Fariborz Jahanianfbff0c42013-05-13 17:27:00 +0000418 if (D->isInvalidDecl())
419 return NULL;
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000420 D = adjustDeclToTemplate(D);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000421
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000422 const Decl *Canonical = D->getCanonicalDecl();
423 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
424 ParsedComments.find(Canonical);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000425
426 if (Pos != ParsedComments.end()) {
Fariborz Jahanian749ace62012-10-11 23:52:50 +0000427 if (Canonical != D) {
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000428 comments::FullComment *FC = Pos->second;
Fariborz Jahanian749ace62012-10-11 23:52:50 +0000429 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000430 return CFC;
431 }
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000432 return Pos->second;
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000433 }
434
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000435 const Decl *OriginalDecl;
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000436
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000437 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000438 if (!RC) {
439 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko1e905da2012-11-03 14:24:57 +0000440 SmallVector<const NamedDecl*, 8> Overridden;
Fariborz Jahanianc328d9c2013-01-12 00:28:34 +0000441 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian23799e32013-01-25 23:08:39 +0000442 if (OMD && OMD->isPropertyAccessor())
443 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
444 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
445 return cloneFullComment(FC, D);
Fariborz Jahanianc328d9c2013-01-12 00:28:34 +0000446 if (OMD)
Dmitri Gribenko1e905da2012-11-03 14:24:57 +0000447 addRedeclaredMethods(OMD, Overridden);
448 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian23799e32013-01-25 23:08:39 +0000449 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
450 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
451 return cloneFullComment(FC, D);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000452 }
Fariborz Jahanian4857fdc2013-05-02 15:44:16 +0000453 else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenkod1e5c0d2013-01-27 21:18:39 +0000454 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian23799e32013-01-25 23:08:39 +0000455 // does not have one of its own.
Fariborz Jahanian41170b52013-01-25 22:48:32 +0000456 QualType QT = TD->getUnderlyingType();
Dmitri Gribenkod1e5c0d2013-01-27 21:18:39 +0000457 if (const TagType *TT = QT->getAs<TagType>())
458 if (const Decl *TD = TT->getDecl())
459 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian23799e32013-01-25 23:08:39 +0000460 return cloneFullComment(FC, D);
Fariborz Jahanian41170b52013-01-25 22:48:32 +0000461 }
Fariborz Jahanian622bb4a2013-04-26 20:55:38 +0000462 else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
463 while (IC->getSuperClass()) {
464 IC = IC->getSuperClass();
465 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
466 return cloneFullComment(FC, D);
467 }
468 }
469 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
470 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
471 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
472 return cloneFullComment(FC, D);
473 }
474 else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
475 if (!(RD = RD->getDefinition()))
476 return NULL;
477 // Check non-virtual bases.
478 for (CXXRecordDecl::base_class_const_iterator I =
479 RD->bases_begin(), E = RD->bases_end(); I != E; ++I) {
Fariborz Jahanian91efca02013-04-26 23:34:36 +0000480 if (I->isVirtual() || (I->getAccessSpecifier() != AS_public))
Fariborz Jahanian622bb4a2013-04-26 20:55:38 +0000481 continue;
482 QualType Ty = I->getType();
483 if (Ty.isNull())
484 continue;
485 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
486 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
487 continue;
488
489 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
490 return cloneFullComment(FC, D);
491 }
492 }
493 // Check virtual bases.
494 for (CXXRecordDecl::base_class_const_iterator I =
495 RD->vbases_begin(), E = RD->vbases_end(); I != E; ++I) {
Fariborz Jahanian91efca02013-04-26 23:34:36 +0000496 if (I->getAccessSpecifier() != AS_public)
497 continue;
Fariborz Jahanian622bb4a2013-04-26 20:55:38 +0000498 QualType Ty = I->getType();
499 if (Ty.isNull())
500 continue;
501 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
502 if (!(VirtualBase= VirtualBase->getDefinition()))
503 continue;
504 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
505 return cloneFullComment(FC, D);
506 }
507 }
508 }
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000509 return NULL;
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000510 }
511
Dmitri Gribenko4b41c652012-08-22 18:12:19 +0000512 // If the RawComment was attached to other redeclaration of this Decl, we
513 // should parse the comment in context of that other Decl. This is important
514 // because comments can contain references to parameter names which can be
515 // different across redeclarations.
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000516 if (D != OriginalDecl)
Dmitri Gribenko19523542012-09-29 11:40:46 +0000517 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000518
Dmitri Gribenko19523542012-09-29 11:40:46 +0000519 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000520 ParsedComments[Canonical] = FC;
521 return FC;
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000522}
523
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000524void
525ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
526 TemplateTemplateParmDecl *Parm) {
527 ID.AddInteger(Parm->getDepth());
528 ID.AddInteger(Parm->getPosition());
Douglas Gregor61c4d282011-01-05 15:48:55 +0000529 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000530
531 TemplateParameterList *Params = Parm->getTemplateParameters();
532 ID.AddInteger(Params->size());
533 for (TemplateParameterList::const_iterator P = Params->begin(),
534 PEnd = Params->end();
535 P != PEnd; ++P) {
536 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
537 ID.AddInteger(0);
538 ID.AddBoolean(TTP->isParameterPack());
539 continue;
540 }
541
542 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
543 ID.AddInteger(1);
Douglas Gregor61c4d282011-01-05 15:48:55 +0000544 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman9e9c4542012-03-07 01:09:33 +0000545 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000546 if (NTTP->isExpandedParameterPack()) {
547 ID.AddBoolean(true);
548 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman9e9c4542012-03-07 01:09:33 +0000549 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
550 QualType T = NTTP->getExpansionType(I);
551 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
552 }
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000553 } else
554 ID.AddBoolean(false);
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000555 continue;
556 }
557
558 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
559 ID.AddInteger(2);
560 Profile(ID, TTP);
561 }
562}
563
564TemplateTemplateParmDecl *
565ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad4ba2a172011-01-12 09:06:06 +0000566 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000567 // Check if we already have a canonical template template parameter.
568 llvm::FoldingSetNodeID ID;
569 CanonicalTemplateTemplateParm::Profile(ID, TTP);
570 void *InsertPos = 0;
571 CanonicalTemplateTemplateParm *Canonical
572 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
573 if (Canonical)
574 return Canonical->getParam();
575
576 // Build a canonical template parameter list.
577 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000578 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000579 CanonParams.reserve(Params->size());
580 for (TemplateParameterList::const_iterator P = Params->begin(),
581 PEnd = Params->end();
582 P != PEnd; ++P) {
583 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
584 CanonParams.push_back(
585 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnara344577e2011-03-06 15:48:19 +0000586 SourceLocation(),
587 SourceLocation(),
588 TTP->getDepth(),
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000589 TTP->getIndex(), 0, false,
590 TTP->isParameterPack()));
591 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000592 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
593 QualType T = getCanonicalType(NTTP->getType());
594 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
595 NonTypeTemplateParmDecl *Param;
596 if (NTTP->isExpandedParameterPack()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000597 SmallVector<QualType, 2> ExpandedTypes;
598 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000599 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
600 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
601 ExpandedTInfos.push_back(
602 getTrivialTypeSourceInfo(ExpandedTypes.back()));
603 }
604
605 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000606 SourceLocation(),
607 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000608 NTTP->getDepth(),
609 NTTP->getPosition(), 0,
610 T,
611 TInfo,
612 ExpandedTypes.data(),
613 ExpandedTypes.size(),
614 ExpandedTInfos.data());
615 } else {
616 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000617 SourceLocation(),
618 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000619 NTTP->getDepth(),
620 NTTP->getPosition(), 0,
621 T,
622 NTTP->isParameterPack(),
623 TInfo);
624 }
625 CanonParams.push_back(Param);
626
627 } else
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000628 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
629 cast<TemplateTemplateParmDecl>(*P)));
630 }
631
632 TemplateTemplateParmDecl *CanonTTP
633 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
634 SourceLocation(), TTP->getDepth(),
Douglas Gregor61c4d282011-01-05 15:48:55 +0000635 TTP->getPosition(),
636 TTP->isParameterPack(),
637 0,
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000638 TemplateParameterList::Create(*this, SourceLocation(),
639 SourceLocation(),
640 CanonParams.data(),
641 CanonParams.size(),
642 SourceLocation()));
643
644 // Get the new insert position for the node we care about.
645 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
646 assert(Canonical == 0 && "Shouldn't be in the map!");
647 (void)Canonical;
648
649 // Create the canonical template template parameter entry.
650 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
651 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
652 return CanonTTP;
653}
654
Charles Davis071cc7d2010-08-16 03:33:14 +0000655CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCallee79a4c2010-08-21 22:46:04 +0000656 if (!LangOpts.CPlusPlus) return 0;
657
John McCallb8b2c9d2013-01-25 22:30:49 +0000658 switch (T.getCXXABI().getKind()) {
659 case TargetCXXABI::GenericARM:
660 case TargetCXXABI::iOS:
John McCallee79a4c2010-08-21 22:46:04 +0000661 return CreateARMCXXABI(*this);
Tim Northoverc264e162013-01-31 12:13:10 +0000662 case TargetCXXABI::GenericAArch64: // Same as Itanium at this level
John McCallb8b2c9d2013-01-25 22:30:49 +0000663 case TargetCXXABI::GenericItanium:
Charles Davis071cc7d2010-08-16 03:33:14 +0000664 return CreateItaniumCXXABI(*this);
John McCallb8b2c9d2013-01-25 22:30:49 +0000665 case TargetCXXABI::Microsoft:
Charles Davis20cf7172010-08-19 02:18:14 +0000666 return CreateMicrosoftCXXABI(*this);
667 }
David Blaikie7530c032012-01-17 06:56:22 +0000668 llvm_unreachable("Invalid CXXABI type!");
Charles Davis071cc7d2010-08-16 03:33:14 +0000669}
670
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000671static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000672 const LangOptions &LOpts) {
673 if (LOpts.FakeAddressSpaceMap) {
674 // The fake address space map must have a distinct entry for each
675 // language-specific address space.
676 static const unsigned FakeAddrSpaceMap[] = {
677 1, // opencl_global
678 2, // opencl_local
Peter Collingbourne4dc34eb2012-05-20 21:08:35 +0000679 3, // opencl_constant
680 4, // cuda_device
681 5, // cuda_constant
682 6 // cuda_shared
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000683 };
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000684 return &FakeAddrSpaceMap;
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000685 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000686 return &T.getAddressSpaceMap();
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000687 }
688}
689
Douglas Gregor3e3cd932011-09-01 20:23:19 +0000690ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000691 const TargetInfo *t,
Daniel Dunbare91593e2008-08-11 04:54:23 +0000692 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000693 Builtin::Context &builtins,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000694 unsigned size_reserve,
695 bool DelayInitialization)
696 : FunctionProtoTypes(this_()),
697 TemplateSpecializationTypes(this_()),
698 DependentTemplateSpecializationTypes(this_()),
699 SubstTemplateTemplateParmPacks(this_()),
700 GlobalNestedNameSpecifier(0),
Nico Webercac18ad2013-06-20 21:44:55 +0000701 Int128Decl(0), UInt128Decl(0), Float128StubDecl(0),
Meador Ingec5613b22012-06-16 03:34:49 +0000702 BuiltinVaListDecl(0),
Douglas Gregora6ea10e2012-01-17 18:09:05 +0000703 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Fariborz Jahanian96171302012-08-30 18:49:41 +0000704 BOOLDecl(0),
Douglas Gregore97179c2011-09-08 01:46:34 +0000705 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000706 FILEDecl(0),
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +0000707 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
708 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
709 cudaConfigureCallDecl(0),
Douglas Gregore6649772011-12-03 00:30:27 +0000710 NullTypeSourceInfo(QualType()),
711 FirstLocalImport(), LastLocalImport(),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000712 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregor30c42402011-09-27 22:38:19 +0000713 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000714 Idents(idents), Selectors(sels),
715 BuiltinInfo(builtins),
716 DeclarationNames(*this),
Douglas Gregor30c42402011-09-27 22:38:19 +0000717 ExternalSource(0), Listener(0),
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000718 Comments(SM), CommentsLoaded(false),
Dmitri Gribenko6ebf0912013-02-22 14:21:27 +0000719 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
Rafael Espindola42b78612013-05-29 19:51:12 +0000720 LastSDM(0, 0)
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000721{
Mike Stump1eb44332009-09-09 15:08:12 +0000722 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +0000723 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000724
725 if (!DelayInitialization) {
726 assert(t && "No target supplied for ASTContext initialization");
727 InitBuiltinTypes(*t);
728 }
Daniel Dunbare91593e2008-08-11 04:54:23 +0000729}
730
Reid Spencer5f016e22007-07-11 17:01:13 +0000731ASTContext::~ASTContext() {
Ted Kremenek3478eb62010-02-11 07:12:28 +0000732 // Release the DenseMaps associated with DeclContext objects.
733 // FIXME: Is this the ideal solution?
734 ReleaseDeclContextMaps();
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000735
Manuel Klimekf0f353b2013-06-03 13:51:33 +0000736 // Call all of the deallocation functions on all of their targets.
737 for (DeallocationMap::const_iterator I = Deallocations.begin(),
738 E = Deallocations.end(); I != E; ++I)
739 for (unsigned J = 0, N = I->second.size(); J != N; ++J)
740 (I->first)((I->second)[J]);
741
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000742 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000743 // because they can contain DenseMaps.
744 for (llvm::DenseMap<const ObjCContainerDecl*,
745 const ASTRecordLayout*>::iterator
746 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
747 // Increment in loop to prevent using deallocated memory.
748 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
749 R->Destroy(*this);
750
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000751 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
752 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
753 // Increment in loop to prevent using deallocated memory.
754 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
755 R->Destroy(*this);
756 }
Douglas Gregor63200642010-08-30 16:49:28 +0000757
758 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
759 AEnd = DeclAttrs.end();
760 A != AEnd; ++A)
761 A->second->~AttrVec();
762}
Douglas Gregorab452ba2009-03-26 23:50:42 +0000763
Douglas Gregor00545312010-05-23 18:26:36 +0000764void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Manuel Klimekf0f353b2013-06-03 13:51:33 +0000765 Deallocations[Callback].push_back(Data);
Douglas Gregor00545312010-05-23 18:26:36 +0000766}
767
Mike Stump1eb44332009-09-09 15:08:12 +0000768void
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000769ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregor2cf26342009-04-09 22:27:44 +0000770 ExternalSource.reset(Source.take());
771}
772
Reid Spencer5f016e22007-07-11 17:01:13 +0000773void ASTContext::PrintStats() const {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000774 llvm::errs() << "\n*** AST Context Stats:\n";
775 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000776
Douglas Gregordbe833d2009-05-26 14:40:08 +0000777 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000778#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000779#define ABSTRACT_TYPE(Name, Parent)
780#include "clang/AST/TypeNodes.def"
781 0 // Extra
782 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000783
Reid Spencer5f016e22007-07-11 17:01:13 +0000784 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
785 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000786 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000787 }
788
Douglas Gregordbe833d2009-05-26 14:40:08 +0000789 unsigned Idx = 0;
790 unsigned TotalBytes = 0;
791#define TYPE(Name, Parent) \
792 if (counts[Idx]) \
Chandler Carruthcd92a652011-07-04 05:32:14 +0000793 llvm::errs() << " " << counts[Idx] << " " << #Name \
794 << " types\n"; \
Douglas Gregordbe833d2009-05-26 14:40:08 +0000795 TotalBytes += counts[Idx] * sizeof(Name##Type); \
796 ++Idx;
797#define ABSTRACT_TYPE(Name, Parent)
798#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000799
Chandler Carruthcd92a652011-07-04 05:32:14 +0000800 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
801
Douglas Gregor4923aa22010-07-02 20:37:36 +0000802 // Implicit special member functions.
Chandler Carruthcd92a652011-07-04 05:32:14 +0000803 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
804 << NumImplicitDefaultConstructors
805 << " implicit default constructors created\n";
806 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
807 << NumImplicitCopyConstructors
808 << " implicit copy constructors created\n";
David Blaikie4e4d0842012-03-11 07:00:24 +0000809 if (getLangOpts().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000810 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
811 << NumImplicitMoveConstructors
812 << " implicit move constructors created\n";
813 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
814 << NumImplicitCopyAssignmentOperators
815 << " implicit copy assignment operators created\n";
David Blaikie4e4d0842012-03-11 07:00:24 +0000816 if (getLangOpts().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000817 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
818 << NumImplicitMoveAssignmentOperators
819 << " implicit move assignment operators created\n";
820 llvm::errs() << NumImplicitDestructorsDeclared << "/"
821 << NumImplicitDestructors
822 << " implicit destructors created\n";
823
Douglas Gregor2cf26342009-04-09 22:27:44 +0000824 if (ExternalSource.get()) {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000825 llvm::errs() << "\n";
Douglas Gregor2cf26342009-04-09 22:27:44 +0000826 ExternalSource->PrintStats();
827 }
Chandler Carruthcd92a652011-07-04 05:32:14 +0000828
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000829 BumpAlloc.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000830}
831
Douglas Gregor772eeae2011-08-12 06:49:56 +0000832TypedefDecl *ASTContext::getInt128Decl() const {
833 if (!Int128Decl) {
834 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
835 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
836 getTranslationUnitDecl(),
837 SourceLocation(),
838 SourceLocation(),
839 &Idents.get("__int128_t"),
840 TInfo);
841 }
842
843 return Int128Decl;
844}
845
846TypedefDecl *ASTContext::getUInt128Decl() const {
847 if (!UInt128Decl) {
848 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
849 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
850 getTranslationUnitDecl(),
851 SourceLocation(),
852 SourceLocation(),
853 &Idents.get("__uint128_t"),
854 TInfo);
855 }
856
857 return UInt128Decl;
858}
Reid Spencer5f016e22007-07-11 17:01:13 +0000859
Nico Webercac18ad2013-06-20 21:44:55 +0000860TypeDecl *ASTContext::getFloat128StubType() const {
Nico Weber3f7c1b12013-06-21 01:29:36 +0000861 assert(LangOpts.CPlusPlus && "should only be called for c++");
Nico Webercac18ad2013-06-20 21:44:55 +0000862 if (!Float128StubDecl) {
Nico Weber9b9bdba2013-06-20 23:30:30 +0000863 Float128StubDecl = CXXRecordDecl::Create(const_cast<ASTContext &>(*this),
864 TTK_Struct,
865 getTranslationUnitDecl(),
866 SourceLocation(),
867 SourceLocation(),
868 &Idents.get("__float128"));
Nico Webercac18ad2013-06-20 21:44:55 +0000869 }
870
871 return Float128StubDecl;
872}
873
John McCalle27ec8a2009-10-23 23:03:21 +0000874void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000875 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000876 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000877 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000878}
879
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000880void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
881 assert((!this->Target || this->Target == &Target) &&
882 "Incorrect target reinitialization");
Reid Spencer5f016e22007-07-11 17:01:13 +0000883 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000884
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000885 this->Target = &Target;
886
887 ABI.reset(createCXXABI(Target));
888 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
889
Reid Spencer5f016e22007-07-11 17:01:13 +0000890 // C99 6.2.5p19.
891 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000892
Reid Spencer5f016e22007-07-11 17:01:13 +0000893 // C99 6.2.5p2.
894 InitBuiltinType(BoolTy, BuiltinType::Bool);
895 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000896 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000897 InitBuiltinType(CharTy, BuiltinType::Char_S);
898 else
899 InitBuiltinType(CharTy, BuiltinType::Char_U);
900 // C99 6.2.5p4.
901 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
902 InitBuiltinType(ShortTy, BuiltinType::Short);
903 InitBuiltinType(IntTy, BuiltinType::Int);
904 InitBuiltinType(LongTy, BuiltinType::Long);
905 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000906
Reid Spencer5f016e22007-07-11 17:01:13 +0000907 // C99 6.2.5p6.
908 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
909 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
910 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
911 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
912 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000913
Reid Spencer5f016e22007-07-11 17:01:13 +0000914 // C99 6.2.5p10.
915 InitBuiltinType(FloatTy, BuiltinType::Float);
916 InitBuiltinType(DoubleTy, BuiltinType::Double);
917 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000918
Chris Lattner2df9ced2009-04-30 02:43:43 +0000919 // GNU extension, 128-bit integers.
920 InitBuiltinType(Int128Ty, BuiltinType::Int128);
921 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
922
Hans Wennborg15f92ba2013-05-10 10:08:40 +0000923 // C++ 3.9.1p5
924 if (TargetInfo::isTypeSigned(Target.getWCharType()))
925 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
926 else // -fshort-wchar makes wchar_t be unsigned.
927 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
928 if (LangOpts.CPlusPlus && LangOpts.WChar)
929 WideCharTy = WCharTy;
930 else {
931 // C99 (or C++ using -fno-wchar).
932 WideCharTy = getFromTargetType(Target.getWCharType());
933 }
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000934
James Molloy392da482012-05-04 10:55:22 +0000935 WIntTy = getFromTargetType(Target.getWIntType());
936
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000937 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
938 InitBuiltinType(Char16Ty, BuiltinType::Char16);
939 else // C99
940 Char16Ty = getFromTargetType(Target.getChar16Type());
941
942 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
943 InitBuiltinType(Char32Ty, BuiltinType::Char32);
944 else // C99
945 Char32Ty = getFromTargetType(Target.getChar32Type());
946
Douglas Gregor898574e2008-12-05 23:32:09 +0000947 // Placeholder type for type-dependent expressions whose type is
948 // completely unknown. No code should ever check a type against
949 // DependentTy and users should never see it; however, it is here to
950 // help diagnose failures to properly check for type-dependent
951 // expressions.
952 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000953
John McCall2a984ca2010-10-12 00:20:44 +0000954 // Placeholder type for functions.
955 InitBuiltinType(OverloadTy, BuiltinType::Overload);
956
John McCall864c0412011-04-26 20:42:42 +0000957 // Placeholder type for bound members.
958 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
959
John McCall3c3b7f92011-10-25 17:37:35 +0000960 // Placeholder type for pseudo-objects.
961 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
962
John McCall1de4d4e2011-04-07 08:22:57 +0000963 // "any" type; useful for debugger-like clients.
964 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
965
John McCall0ddaeb92011-10-17 18:09:15 +0000966 // Placeholder type for unbridged ARC casts.
967 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
968
Eli Friedmana6c66ce2012-08-31 00:14:07 +0000969 // Placeholder type for builtin functions.
970 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
971
Reid Spencer5f016e22007-07-11 17:01:13 +0000972 // C99 6.2.5p11.
973 FloatComplexTy = getComplexType(FloatTy);
974 DoubleComplexTy = getComplexType(DoubleTy);
975 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000976
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000977 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000978 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
979 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000980 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeib13621d2012-12-18 14:38:23 +0000981
982 if (LangOpts.OpenCL) {
983 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
984 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
985 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
986 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
987 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
988 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
Guy Benyeie6b9d802013-01-20 12:31:11 +0000989
Guy Benyei21f18c42013-02-07 10:55:47 +0000990 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyeie6b9d802013-01-20 12:31:11 +0000991 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Guy Benyeib13621d2012-12-18 14:38:23 +0000992 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000993
994 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian93a49942012-04-16 21:03:30 +0000995 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
996 SignedCharTy : BoolTy);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000997
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000998 ObjCConstantStringType = QualType();
Fariborz Jahanianf7992132013-01-04 18:45:40 +0000999
1000 ObjCSuperType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00001001
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001002 // void * type
1003 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001004
1005 // nullptr type (C++0x 2.14.7)
1006 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001007
1008 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1009 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingefb40e3f2012-07-01 15:57:25 +00001010
1011 // Builtin type used to help define __builtin_va_list.
1012 VaListTagTy = QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001013}
1014
David Blaikied6471f72011-09-25 23:23:43 +00001015DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00001016 return SourceMgr.getDiagnostics();
1017}
1018
Douglas Gregor63200642010-08-30 16:49:28 +00001019AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1020 AttrVec *&Result = DeclAttrs[D];
1021 if (!Result) {
1022 void *Mem = Allocate(sizeof(AttrVec));
1023 Result = new (Mem) AttrVec;
1024 }
1025
1026 return *Result;
1027}
1028
1029/// \brief Erase the attributes corresponding to the given declaration.
1030void ASTContext::eraseDeclAttrs(const Decl *D) {
1031 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1032 if (Pos != DeclAttrs.end()) {
1033 Pos->second->~AttrVec();
1034 DeclAttrs.erase(Pos);
1035 }
1036}
1037
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001038MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +00001039ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001040 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +00001041 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +00001042 = InstantiatedFromStaticDataMember.find(Var);
1043 if (Pos == InstantiatedFromStaticDataMember.end())
1044 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001045
Douglas Gregor7caa6822009-07-24 20:34:43 +00001046 return Pos->second;
1047}
1048
Mike Stump1eb44332009-09-09 15:08:12 +00001049void
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001050ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +00001051 TemplateSpecializationKind TSK,
1052 SourceLocation PointOfInstantiation) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001053 assert(Inst->isStaticDataMember() && "Not a static data member");
1054 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1055 assert(!InstantiatedFromStaticDataMember[Inst] &&
1056 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001057 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +00001058 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregor7caa6822009-07-24 20:34:43 +00001059}
1060
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001061FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1062 const FunctionDecl *FD){
1063 assert(FD && "Specialization is 0");
1064 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet0d95f0d2011-08-14 14:28:49 +00001065 = ClassScopeSpecializationPattern.find(FD);
1066 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001067 return 0;
1068
1069 return Pos->second;
1070}
1071
1072void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1073 FunctionDecl *Pattern) {
1074 assert(FD && "Specialization is 0");
1075 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet0d95f0d2011-08-14 14:28:49 +00001076 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001077}
1078
John McCall7ba107a2009-11-18 02:36:19 +00001079NamedDecl *
John McCalled976492009-12-04 22:46:56 +00001080ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +00001081 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +00001082 = InstantiatedFromUsingDecl.find(UUD);
1083 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +00001084 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001085
Anders Carlsson0d8df782009-08-29 19:37:28 +00001086 return Pos->second;
1087}
1088
1089void
John McCalled976492009-12-04 22:46:56 +00001090ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1091 assert((isa<UsingDecl>(Pattern) ||
1092 isa<UnresolvedUsingValueDecl>(Pattern) ||
1093 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1094 "pattern decl is not a using decl");
1095 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1096 InstantiatedFromUsingDecl[Inst] = Pattern;
1097}
1098
1099UsingShadowDecl *
1100ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1101 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1102 = InstantiatedFromUsingShadowDecl.find(Inst);
1103 if (Pos == InstantiatedFromUsingShadowDecl.end())
1104 return 0;
1105
1106 return Pos->second;
1107}
1108
1109void
1110ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1111 UsingShadowDecl *Pattern) {
1112 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1113 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00001114}
1115
Anders Carlssond8b285f2009-09-01 04:26:58 +00001116FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1117 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1118 = InstantiatedFromUnnamedFieldDecl.find(Field);
1119 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1120 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001121
Anders Carlssond8b285f2009-09-01 04:26:58 +00001122 return Pos->second;
1123}
1124
1125void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1126 FieldDecl *Tmpl) {
1127 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1128 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1129 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1130 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +00001131
Anders Carlssond8b285f2009-09-01 04:26:58 +00001132 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1133}
1134
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +00001135bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
1136 const FieldDecl *LastFD) const {
1137 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001138 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +00001139}
1140
Fariborz Jahanian340fa242011-05-02 17:20:56 +00001141bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
1142 const FieldDecl *LastFD) const {
1143 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001144 FD->getBitWidthValue(*this) == 0 &&
1145 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanian340fa242011-05-02 17:20:56 +00001146}
1147
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +00001148bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
1149 const FieldDecl *LastFD) const {
1150 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001151 FD->getBitWidthValue(*this) &&
1152 LastFD->getBitWidthValue(*this));
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +00001153}
1154
Chad Rosierdd7fddb2011-08-04 23:34:15 +00001155bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +00001156 const FieldDecl *LastFD) const {
1157 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001158 LastFD->getBitWidthValue(*this));
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +00001159}
1160
Chad Rosierdd7fddb2011-08-04 23:34:15 +00001161bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +00001162 const FieldDecl *LastFD) const {
1163 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001164 FD->getBitWidthValue(*this));
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +00001165}
1166
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001167ASTContext::overridden_cxx_method_iterator
1168ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1169 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001170 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001171 if (Pos == OverriddenMethods.end())
1172 return 0;
1173
1174 return Pos->second.begin();
1175}
1176
1177ASTContext::overridden_cxx_method_iterator
1178ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1179 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001180 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001181 if (Pos == OverriddenMethods.end())
1182 return 0;
1183
1184 return Pos->second.end();
1185}
1186
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +00001187unsigned
1188ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1189 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001190 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +00001191 if (Pos == OverriddenMethods.end())
1192 return 0;
1193
1194 return Pos->second.size();
1195}
1196
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001197void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1198 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001199 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001200 OverriddenMethods[Method].push_back(Overridden);
1201}
1202
Dmitri Gribenko1e905da2012-11-03 14:24:57 +00001203void ASTContext::getOverriddenMethods(
1204 const NamedDecl *D,
1205 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001206 assert(D);
1207
1208 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis685d1042013-04-17 00:09:03 +00001209 Overridden.append(overridden_methods_begin(CXXMethod),
1210 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001211 return;
1212 }
1213
1214 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1215 if (!Method)
1216 return;
1217
Argyrios Kyrtzidis740ae672012-10-09 18:19:01 +00001218 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1219 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisbc0a2bb2012-10-09 20:08:43 +00001220 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001221}
1222
Douglas Gregore6649772011-12-03 00:30:27 +00001223void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1224 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1225 assert(!Import->isFromASTFile() && "Non-local import declaration");
1226 if (!FirstLocalImport) {
1227 FirstLocalImport = Import;
1228 LastLocalImport = Import;
1229 return;
1230 }
1231
1232 LastLocalImport->NextLocalImport = Import;
1233 LastLocalImport = Import;
1234}
1235
Chris Lattner464175b2007-07-18 17:52:12 +00001236//===----------------------------------------------------------------------===//
1237// Type Sizing and Analysis
1238//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +00001239
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001240/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1241/// scalar floating point type.
1242const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +00001243 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001244 assert(BT && "Not a floating point type!");
1245 switch (BT->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001246 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001247 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001248 case BuiltinType::Float: return Target->getFloatFormat();
1249 case BuiltinType::Double: return Target->getDoubleFormat();
1250 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001251 }
1252}
1253
Ken Dyck8b752f12010-01-27 17:10:57 +00001254/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +00001255/// specified decl. Note that bitfields do not have a valid alignment, so
1256/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +00001257/// If @p RefAsPointee, references are treated like their underlying type
1258/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad4ba2a172011-01-12 09:06:06 +00001259CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001260 unsigned Align = Target->getCharWidth();
Eli Friedmandcdafb62009-02-22 02:56:25 +00001261
John McCall4081a5c2010-10-08 18:24:19 +00001262 bool UseAlignAttrOnly = false;
1263 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1264 Align = AlignFromAttr;
Eli Friedmandcdafb62009-02-22 02:56:25 +00001265
John McCall4081a5c2010-10-08 18:24:19 +00001266 // __attribute__((aligned)) can increase or decrease alignment
1267 // *except* on a struct or struct member, where it only increases
1268 // alignment unless 'packed' is also specified.
1269 //
Peter Collingbourne82d0b0a2011-09-29 18:04:28 +00001270 // It is an error for alignas to decrease alignment, so we can
John McCall4081a5c2010-10-08 18:24:19 +00001271 // ignore that possibility; Sema should diagnose it.
1272 if (isa<FieldDecl>(D)) {
1273 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1274 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1275 } else {
1276 UseAlignAttrOnly = true;
1277 }
1278 }
Fariborz Jahanian78a7d7d2011-05-05 21:19:14 +00001279 else if (isa<FieldDecl>(D))
1280 UseAlignAttrOnly =
1281 D->hasAttr<PackedAttr>() ||
1282 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall4081a5c2010-10-08 18:24:19 +00001283
John McCallba4f5d52011-01-20 07:57:12 +00001284 // If we're using the align attribute only, just ignore everything
1285 // else about the declaration and its type.
John McCall4081a5c2010-10-08 18:24:19 +00001286 if (UseAlignAttrOnly) {
John McCallba4f5d52011-01-20 07:57:12 +00001287 // do nothing
1288
John McCall4081a5c2010-10-08 18:24:19 +00001289 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00001290 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001291 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00001292 if (RefAsPointee)
1293 T = RT->getPointeeType();
1294 else
1295 T = getPointerType(RT->getPointeeType());
1296 }
1297 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall3b657512011-01-19 10:06:00 +00001298 // Adjust alignments of declarations with array type by the
1299 // large-array alignment on the target.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001300 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall3b657512011-01-19 10:06:00 +00001301 const ArrayType *arrayType;
1302 if (MinWidth && (arrayType = getAsArrayType(T))) {
1303 if (isa<VariableArrayType>(arrayType))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001304 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall3b657512011-01-19 10:06:00 +00001305 else if (isa<ConstantArrayType>(arrayType) &&
1306 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001307 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedmandcdafb62009-02-22 02:56:25 +00001308
John McCall3b657512011-01-19 10:06:00 +00001309 // Walk through any array types while we're at it.
1310 T = getBaseElementType(arrayType);
1311 }
Chad Rosier9f1210c2011-07-26 07:03:04 +00001312 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Ulrich Weigand6b203512013-05-06 16:23:57 +00001313 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1314 if (VD->hasGlobalStorage())
1315 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1316 }
Eli Friedmandcdafb62009-02-22 02:56:25 +00001317 }
John McCallba4f5d52011-01-20 07:57:12 +00001318
1319 // Fields can be subject to extra alignment constraints, like if
1320 // the field is packed, the struct is packed, or the struct has a
1321 // a max-field-alignment constraint (#pragma pack). So calculate
1322 // the actual alignment of the field within the struct, and then
1323 // (as we're expected to) constrain that by the alignment of the type.
1324 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
1325 // So calculate the alignment of the field.
1326 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
1327
1328 // Start with the record's overall alignment.
Ken Dyckdac54c12011-02-15 02:32:40 +00001329 unsigned fieldAlign = toBits(layout.getAlignment());
John McCallba4f5d52011-01-20 07:57:12 +00001330
1331 // Use the GCD of that and the offset within the record.
1332 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
1333 if (offset > 0) {
1334 // Alignment is always a power of 2, so the GCD will be a power of 2,
1335 // which means we get to do this crazy thing instead of Euclid's.
1336 uint64_t lowBitOfOffset = offset & (~offset + 1);
1337 if (lowBitOfOffset < fieldAlign)
1338 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
1339 }
1340
1341 Align = std::min(Align, fieldAlign);
Charles Davis05f62472010-02-23 04:52:00 +00001342 }
Chris Lattneraf707ab2009-01-24 21:53:27 +00001343 }
Eli Friedmandcdafb62009-02-22 02:56:25 +00001344
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001345 return toCharUnitsFromBits(Align);
Chris Lattneraf707ab2009-01-24 21:53:27 +00001346}
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001347
John McCall929bbfb2012-08-21 04:10:00 +00001348// getTypeInfoDataSizeInChars - Return the size of a type, in
1349// chars. If the type is a record, its data size is returned. This is
1350// the size of the memcpy that's performed when assigning this type
1351// using a trivial copy/move assignment operator.
1352std::pair<CharUnits, CharUnits>
1353ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1354 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1355
1356 // In C++, objects can sometimes be allocated into the tail padding
1357 // of a base-class subobject. We decide whether that's possible
1358 // during class layout, so here we can just trust the layout results.
1359 if (getLangOpts().CPlusPlus) {
1360 if (const RecordType *RT = T->getAs<RecordType>()) {
1361 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1362 sizeAndAlign.first = layout.getDataSize();
1363 }
1364 }
1365
1366 return sizeAndAlign;
1367}
1368
Richard Trieu910f17e2013-05-14 21:59:17 +00001369/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1370/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1371std::pair<CharUnits, CharUnits>
1372static getConstantArrayInfoInChars(const ASTContext &Context,
1373 const ConstantArrayType *CAT) {
1374 std::pair<CharUnits, CharUnits> EltInfo =
1375 Context.getTypeInfoInChars(CAT->getElementType());
1376 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieu1069b732013-05-14 23:41:50 +00001377 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1378 (uint64_t)(-1)/Size) &&
Richard Trieu910f17e2013-05-14 21:59:17 +00001379 "Overflow in array type char size evaluation");
1380 uint64_t Width = EltInfo.first.getQuantity() * Size;
1381 unsigned Align = EltInfo.second.getQuantity();
1382 Width = llvm::RoundUpToAlignment(Width, Align);
1383 return std::make_pair(CharUnits::fromQuantity(Width),
1384 CharUnits::fromQuantity(Align));
1385}
1386
John McCallea1471e2010-05-20 01:18:31 +00001387std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +00001388ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu910f17e2013-05-14 21:59:17 +00001389 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1390 return getConstantArrayInfoInChars(*this, CAT);
John McCallea1471e2010-05-20 01:18:31 +00001391 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001392 return std::make_pair(toCharUnitsFromBits(Info.first),
1393 toCharUnitsFromBits(Info.second));
John McCallea1471e2010-05-20 01:18:31 +00001394}
1395
1396std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +00001397ASTContext::getTypeInfoInChars(QualType T) const {
John McCallea1471e2010-05-20 01:18:31 +00001398 return getTypeInfoInChars(T.getTypePtr());
1399}
1400
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001401std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1402 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1403 if (it != MemoizedTypeInfo.end())
1404 return it->second;
1405
1406 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1407 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1408 return Info;
1409}
1410
1411/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1412/// method does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +00001413///
1414/// FIXME: Pointers into different addr spaces could have different sizes and
1415/// alignment requirements: getPointerInfo should take an AddrSpace, this
1416/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +00001417std::pair<uint64_t, unsigned>
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001418ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5e301002009-02-27 18:32:39 +00001419 uint64_t Width=0;
1420 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +00001421 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +00001422#define TYPE(Class, Base)
1423#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +00001424#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +00001425#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1426#include "clang/AST/TypeNodes.def"
John McCalld3d49bb2011-06-28 16:49:23 +00001427 llvm_unreachable("Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +00001428
Chris Lattner692233e2007-07-13 22:27:08 +00001429 case Type::FunctionNoProto:
1430 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +00001431 // GCC extension: alignof(function) = 32 bits
1432 Width = 0;
1433 Align = 32;
1434 break;
1435
Douglas Gregor72564e72009-02-26 23:50:07 +00001436 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +00001437 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +00001438 Width = 0;
1439 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1440 break;
1441
Steve Narofffb22d962007-08-30 01:06:46 +00001442 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001443 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001444
Chris Lattner98be4942008-03-05 18:54:05 +00001445 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarafea966a2011-12-13 11:23:52 +00001446 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001447 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1448 "Overflow in array type bit size evaluation");
Abramo Bagnarafea966a2011-12-13 11:23:52 +00001449 Width = EltInfo.first*Size;
Chris Lattner030d8842007-07-19 22:06:24 +00001450 Align = EltInfo.second;
Argyrios Kyrtzidiscd88b412011-04-26 21:05:39 +00001451 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattner030d8842007-07-19 22:06:24 +00001452 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +00001453 }
Nate Begeman213541a2008-04-18 23:10:10 +00001454 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +00001455 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +00001456 const VectorType *VT = cast<VectorType>(T);
1457 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1458 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +00001459 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +00001460 // If the alignment is not a power of 2, round up to the next power of 2.
1461 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +00001462 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +00001463 Align = llvm::NextPowerOf2(Align);
1464 Width = llvm::RoundUpToAlignment(Width, Align);
1465 }
Chad Rosierf9e9af72012-07-13 23:57:43 +00001466 // Adjust the alignment based on the target max.
1467 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1468 if (TargetVectorAlign && TargetVectorAlign < Align)
1469 Align = TargetVectorAlign;
Chris Lattner030d8842007-07-19 22:06:24 +00001470 break;
1471 }
Chris Lattner5d2a6302007-07-18 18:26:58 +00001472
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001473 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +00001474 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001475 default: llvm_unreachable("Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +00001476 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +00001477 // GCC extension: alignof(void) = 8 bits.
1478 Width = 0;
1479 Align = 8;
1480 break;
1481
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001482 case BuiltinType::Bool:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001483 Width = Target->getBoolWidth();
1484 Align = Target->getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001485 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001486 case BuiltinType::Char_S:
1487 case BuiltinType::Char_U:
1488 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001489 case BuiltinType::SChar:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001490 Width = Target->getCharWidth();
1491 Align = Target->getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001492 break;
Chris Lattner3f59c972010-12-25 23:25:43 +00001493 case BuiltinType::WChar_S:
1494 case BuiltinType::WChar_U:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001495 Width = Target->getWCharWidth();
1496 Align = Target->getWCharAlign();
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00001497 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001498 case BuiltinType::Char16:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001499 Width = Target->getChar16Width();
1500 Align = Target->getChar16Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001501 break;
1502 case BuiltinType::Char32:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001503 Width = Target->getChar32Width();
1504 Align = Target->getChar32Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001505 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001506 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001507 case BuiltinType::Short:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001508 Width = Target->getShortWidth();
1509 Align = Target->getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001510 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001511 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001512 case BuiltinType::Int:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001513 Width = Target->getIntWidth();
1514 Align = Target->getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001515 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001516 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001517 case BuiltinType::Long:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001518 Width = Target->getLongWidth();
1519 Align = Target->getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001520 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001521 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001522 case BuiltinType::LongLong:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001523 Width = Target->getLongLongWidth();
1524 Align = Target->getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001525 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +00001526 case BuiltinType::Int128:
1527 case BuiltinType::UInt128:
1528 Width = 128;
1529 Align = 128; // int128_t is 128-bit aligned on all targets.
1530 break;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001531 case BuiltinType::Half:
1532 Width = Target->getHalfWidth();
1533 Align = Target->getHalfAlign();
1534 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001535 case BuiltinType::Float:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001536 Width = Target->getFloatWidth();
1537 Align = Target->getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001538 break;
1539 case BuiltinType::Double:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001540 Width = Target->getDoubleWidth();
1541 Align = Target->getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001542 break;
1543 case BuiltinType::LongDouble:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001544 Width = Target->getLongDoubleWidth();
1545 Align = Target->getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001546 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001547 case BuiltinType::NullPtr:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001548 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1549 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +00001550 break;
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +00001551 case BuiltinType::ObjCId:
1552 case BuiltinType::ObjCClass:
1553 case BuiltinType::ObjCSel:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001554 Width = Target->getPointerWidth(0);
1555 Align = Target->getPointerAlign(0);
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +00001556 break;
Guy Benyei21f18c42013-02-07 10:55:47 +00001557 case BuiltinType::OCLSampler:
1558 // Samplers are modeled as integers.
1559 Width = Target->getIntWidth();
1560 Align = Target->getIntAlign();
1561 break;
Guy Benyeie6b9d802013-01-20 12:31:11 +00001562 case BuiltinType::OCLEvent:
Guy Benyeib13621d2012-12-18 14:38:23 +00001563 case BuiltinType::OCLImage1d:
1564 case BuiltinType::OCLImage1dArray:
1565 case BuiltinType::OCLImage1dBuffer:
1566 case BuiltinType::OCLImage2d:
1567 case BuiltinType::OCLImage2dArray:
1568 case BuiltinType::OCLImage3d:
1569 // Currently these types are pointers to opaque types.
1570 Width = Target->getPointerWidth(0);
1571 Align = Target->getPointerAlign(0);
1572 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001573 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +00001574 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001575 case Type::ObjCObjectPointer:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001576 Width = Target->getPointerWidth(0);
1577 Align = Target->getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001578 break;
Steve Naroff485eeff2008-09-24 15:05:44 +00001579 case Type::BlockPointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001580 unsigned AS = getTargetAddressSpace(
1581 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001582 Width = Target->getPointerWidth(AS);
1583 Align = Target->getPointerAlign(AS);
Steve Naroff485eeff2008-09-24 15:05:44 +00001584 break;
1585 }
Sebastian Redl5d484e82009-11-23 17:18:46 +00001586 case Type::LValueReference:
1587 case Type::RValueReference: {
1588 // alignof and sizeof should never enter this code path here, so we go
1589 // the pointer route.
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001590 unsigned AS = getTargetAddressSpace(
1591 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001592 Width = Target->getPointerWidth(AS);
1593 Align = Target->getPointerAlign(AS);
Sebastian Redl5d484e82009-11-23 17:18:46 +00001594 break;
1595 }
Chris Lattnerf72a4432008-03-08 08:34:58 +00001596 case Type::Pointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001597 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001598 Width = Target->getPointerWidth(AS);
1599 Align = Target->getPointerAlign(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +00001600 break;
1601 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00001602 case Type::MemberPointer: {
Charles Davis071cc7d2010-08-16 03:33:14 +00001603 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Reid Kleckner84e9ab42013-03-28 20:02:56 +00001604 llvm::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson1cca74e2009-05-17 02:06:04 +00001605 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +00001606 }
Chris Lattner5d2a6302007-07-18 18:26:58 +00001607 case Type::Complex: {
1608 // Complex types have the same alignment as their elements, but twice the
1609 // size.
Mike Stump1eb44332009-09-09 15:08:12 +00001610 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +00001611 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001612 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +00001613 Align = EltInfo.second;
1614 break;
1615 }
John McCallc12c5bb2010-05-15 11:32:37 +00001616 case Type::ObjCObject:
1617 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner12df2462013-06-24 17:51:48 +00001618 case Type::Decayed:
1619 return getTypeInfo(cast<DecayedType>(T)->getDecayedType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +00001620 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001621 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +00001622 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001623 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001624 Align = toBits(Layout.getAlignment());
Devang Patel44a3dde2008-06-04 21:54:36 +00001625 break;
1626 }
Douglas Gregor72564e72009-02-26 23:50:07 +00001627 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00001628 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001629 const TagType *TT = cast<TagType>(T);
1630
1631 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor22ce41d2011-04-20 17:29:44 +00001632 Width = 8;
1633 Align = 8;
Chris Lattner8389eab2008-08-09 21:35:13 +00001634 break;
1635 }
Mike Stump1eb44332009-09-09 15:08:12 +00001636
Daniel Dunbar1d751182008-11-08 05:48:37 +00001637 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +00001638 return getTypeInfo(ET->getDecl()->getIntegerType());
1639
Daniel Dunbar1d751182008-11-08 05:48:37 +00001640 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +00001641 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001642 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001643 Align = toBits(Layout.getAlignment());
Chris Lattnerdc0d73e2007-07-23 22:46:22 +00001644 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001645 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001646
Chris Lattner9fcfe922009-10-22 05:17:15 +00001647 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +00001648 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1649 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +00001650
Richard Smith34b41d92011-02-20 03:19:35 +00001651 case Type::Auto: {
1652 const AutoType *A = cast<AutoType>(T);
Richard Smithdc7a4f52013-04-30 13:56:41 +00001653 assert(!A->getDeducedType().isNull() &&
1654 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gaydc856af2011-02-22 20:00:16 +00001655 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith34b41d92011-02-20 03:19:35 +00001656 }
1657
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001658 case Type::Paren:
1659 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1660
Douglas Gregor18857642009-04-30 17:32:17 +00001661 case Type::Typedef: {
Richard Smith162e1c12011-04-15 14:24:37 +00001662 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregordf1367a2010-08-27 00:11:28 +00001663 std::pair<uint64_t, unsigned> Info
1664 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattnerc1de52d2011-02-19 22:55:41 +00001665 // If the typedef has an aligned attribute on it, it overrides any computed
1666 // alignment we have. This violates the GCC documentation (which says that
1667 // attribute(aligned) can only round up) but matches its implementation.
1668 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1669 Align = AttrAlign;
1670 else
1671 Align = Info.second;
Douglas Gregordf1367a2010-08-27 00:11:28 +00001672 Width = Info.first;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001673 break;
Chris Lattner71763312008-04-06 22:05:18 +00001674 }
Douglas Gregor18857642009-04-30 17:32:17 +00001675
1676 case Type::TypeOfExpr:
1677 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1678 .getTypePtr());
1679
1680 case Type::TypeOf:
1681 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1682
Anders Carlsson395b4752009-06-24 19:06:50 +00001683 case Type::Decltype:
1684 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1685 .getTypePtr());
1686
Sean Huntca63c202011-05-24 22:41:36 +00001687 case Type::UnaryTransform:
1688 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1689
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001690 case Type::Elaborated:
1691 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +00001692
John McCall9d156a72011-01-06 01:58:22 +00001693 case Type::Attributed:
1694 return getTypeInfo(
1695 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1696
Richard Smith3e4c6c42011-05-05 21:57:07 +00001697 case Type::TemplateSpecialization: {
Mike Stump1eb44332009-09-09 15:08:12 +00001698 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +00001699 "Cannot request the size of a dependent type");
Richard Smith3e4c6c42011-05-05 21:57:07 +00001700 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1701 // A type alias template specialization may refer to a typedef with the
1702 // aligned attribute on it.
1703 if (TST->isTypeAlias())
1704 return getTypeInfo(TST->getAliasedType().getTypePtr());
1705 else
1706 return getTypeInfo(getCanonicalType(T));
1707 }
1708
Eli Friedmanb001de72011-10-06 23:00:33 +00001709 case Type::Atomic: {
John McCall9eda3ab2013-03-07 21:37:17 +00001710 // Start with the base type information.
Eli Friedman2be46072011-10-14 20:59:01 +00001711 std::pair<uint64_t, unsigned> Info
1712 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1713 Width = Info.first;
1714 Align = Info.second;
John McCall9eda3ab2013-03-07 21:37:17 +00001715
1716 // If the size of the type doesn't exceed the platform's max
1717 // atomic promotion width, make the size and alignment more
1718 // favorable to atomic operations:
1719 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1720 // Round the size up to a power of 2.
1721 if (!llvm::isPowerOf2_64(Width))
1722 Width = llvm::NextPowerOf2(Width);
1723
1724 // Set the alignment equal to the size.
Eli Friedman2be46072011-10-14 20:59:01 +00001725 Align = static_cast<unsigned>(Width);
1726 }
Eli Friedmanb001de72011-10-06 23:00:33 +00001727 }
1728
Douglas Gregor18857642009-04-30 17:32:17 +00001729 }
Mike Stump1eb44332009-09-09 15:08:12 +00001730
Eli Friedman2be46072011-10-14 20:59:01 +00001731 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001732 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +00001733}
1734
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001735/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1736CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1737 return CharUnits::fromQuantity(BitSize / getCharWidth());
1738}
1739
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001740/// toBits - Convert a size in characters to a size in characters.
1741int64_t ASTContext::toBits(CharUnits CharSize) const {
1742 return CharSize.getQuantity() * getCharWidth();
1743}
1744
Ken Dyckbdc601b2009-12-22 14:23:30 +00001745/// getTypeSizeInChars - Return the size of the specified type, in characters.
1746/// This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001747CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu910f17e2013-05-14 21:59:17 +00001748 return getTypeInfoInChars(T).first;
Ken Dyckbdc601b2009-12-22 14:23:30 +00001749}
Jay Foad4ba2a172011-01-12 09:06:06 +00001750CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu910f17e2013-05-14 21:59:17 +00001751 return getTypeInfoInChars(T).first;
Ken Dyckbdc601b2009-12-22 14:23:30 +00001752}
1753
Ken Dyck16e20cc2010-01-26 17:25:18 +00001754/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +00001755/// characters. This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001756CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001757 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001758}
Jay Foad4ba2a172011-01-12 09:06:06 +00001759CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001760 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001761}
1762
Chris Lattner34ebde42009-01-27 18:08:34 +00001763/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1764/// type for the current target in bits. This can be different than the ABI
1765/// alignment in cases where it is beneficial for performance to overalign
1766/// a data type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001767unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattner34ebde42009-01-27 18:08:34 +00001768 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +00001769
1770 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +00001771 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +00001772 T = CT->getElementType().getTypePtr();
1773 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosiercde7a1d2012-03-21 20:20:47 +00001774 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1775 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman1eed6022009-05-25 21:27:19 +00001776 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1777
Chris Lattner34ebde42009-01-27 18:08:34 +00001778 return ABIAlign;
1779}
1780
Ulrich Weigand6b203512013-05-06 16:23:57 +00001781/// getAlignOfGlobalVar - Return the alignment in bits that should be given
1782/// to a global variable of the specified type.
1783unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1784 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1785}
1786
1787/// getAlignOfGlobalVarInChars - Return the alignment in characters that
1788/// should be given to a global variable of the specified type.
1789CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1790 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1791}
1792
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001793/// DeepCollectObjCIvars -
1794/// This routine first collects all declared, but not synthesized, ivars in
1795/// super class and then collects all ivars, including those synthesized for
1796/// current class. This routine is used for implementation of current class
1797/// when all ivars, declared and synthesized are known.
Fariborz Jahanian98200742009-05-12 18:14:29 +00001798///
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001799void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1800 bool leafClass,
Jordy Rosedb8264e2011-07-22 02:08:32 +00001801 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001802 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1803 DeepCollectObjCIvars(SuperClass, false, Ivars);
1804 if (!leafClass) {
1805 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1806 E = OI->ivar_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001807 Ivars.push_back(*I);
Chad Rosier30601782011-08-17 23:08:45 +00001808 } else {
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001809 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosedb8264e2011-07-22 02:08:32 +00001810 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001811 Iv= Iv->getNextIvar())
1812 Ivars.push_back(Iv);
1813 }
Fariborz Jahanian98200742009-05-12 18:14:29 +00001814}
1815
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001816/// CollectInheritedProtocols - Collect all protocols in current class and
1817/// those inherited by it.
1818void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001819 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001820 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001821 // We can use protocol_iterator here instead of
1822 // all_referenced_protocol_iterator since we are walking all categories.
1823 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1824 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001825 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001826 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001827 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001828 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001829 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001830 CollectInheritedProtocols(*P, Protocols);
1831 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001832 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001833
1834 // Categories of this Interface.
Douglas Gregord3297242013-01-16 23:00:23 +00001835 for (ObjCInterfaceDecl::visible_categories_iterator
1836 Cat = OI->visible_categories_begin(),
1837 CatEnd = OI->visible_categories_end();
1838 Cat != CatEnd; ++Cat) {
1839 CollectInheritedProtocols(*Cat, Protocols);
1840 }
1841
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001842 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1843 while (SD) {
1844 CollectInheritedProtocols(SD, Protocols);
1845 SD = SD->getSuperClass();
1846 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001847 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001848 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001849 PE = OC->protocol_end(); P != PE; ++P) {
1850 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001851 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001852 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1853 PE = Proto->protocol_end(); P != PE; ++P)
1854 CollectInheritedProtocols(*P, Protocols);
1855 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001856 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001857 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1858 PE = OP->protocol_end(); P != PE; ++P) {
1859 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001860 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001861 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1862 PE = Proto->protocol_end(); P != PE; ++P)
1863 CollectInheritedProtocols(*P, Protocols);
1864 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001865 }
1866}
1867
Jay Foad4ba2a172011-01-12 09:06:06 +00001868unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001869 unsigned count = 0;
1870 // Count ivars declared in class extension.
Douglas Gregord3297242013-01-16 23:00:23 +00001871 for (ObjCInterfaceDecl::known_extensions_iterator
1872 Ext = OI->known_extensions_begin(),
1873 ExtEnd = OI->known_extensions_end();
1874 Ext != ExtEnd; ++Ext) {
1875 count += Ext->ivar_size();
1876 }
1877
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001878 // Count ivar defined in this class's implementation. This
1879 // includes synthesized ivars.
1880 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001881 count += ImplDecl->ivar_size();
1882
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001883 return count;
1884}
1885
Argyrios Kyrtzidis8deabc12012-02-03 05:58:16 +00001886bool ASTContext::isSentinelNullExpr(const Expr *E) {
1887 if (!E)
1888 return false;
1889
1890 // nullptr_t is always treated as null.
1891 if (E->getType()->isNullPtrType()) return true;
1892
1893 if (E->getType()->isAnyPointerType() &&
1894 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1895 Expr::NPC_ValueDependentIsNull))
1896 return true;
1897
1898 // Unfortunately, __null has type 'int'.
1899 if (isa<GNUNullExpr>(E)) return true;
1900
1901 return false;
1902}
1903
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +00001904/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1905ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1906 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1907 I = ObjCImpls.find(D);
1908 if (I != ObjCImpls.end())
1909 return cast<ObjCImplementationDecl>(I->second);
1910 return 0;
1911}
1912/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1913ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1914 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1915 I = ObjCImpls.find(D);
1916 if (I != ObjCImpls.end())
1917 return cast<ObjCCategoryImplDecl>(I->second);
1918 return 0;
1919}
1920
1921/// \brief Set the implementation of ObjCInterfaceDecl.
1922void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1923 ObjCImplementationDecl *ImplD) {
1924 assert(IFaceD && ImplD && "Passed null params");
1925 ObjCImpls[IFaceD] = ImplD;
1926}
1927/// \brief Set the implementation of ObjCCategoryDecl.
1928void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1929 ObjCCategoryImplDecl *ImplD) {
1930 assert(CatD && ImplD && "Passed null params");
1931 ObjCImpls[CatD] = ImplD;
1932}
1933
Dmitri Gribenkob35cc2d2013-02-03 13:23:21 +00001934const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
1935 const NamedDecl *ND) const {
1936 if (const ObjCInterfaceDecl *ID =
1937 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001938 return ID;
Dmitri Gribenkob35cc2d2013-02-03 13:23:21 +00001939 if (const ObjCCategoryDecl *CD =
1940 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001941 return CD->getClassInterface();
Dmitri Gribenkob35cc2d2013-02-03 13:23:21 +00001942 if (const ObjCImplDecl *IMD =
1943 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001944 return IMD->getClassInterface();
1945
1946 return 0;
1947}
1948
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001949/// \brief Get the copy initialization expression of VarDecl,or NULL if
1950/// none exists.
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001951Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001952 assert(VD && "Passed null params");
1953 assert(VD->hasAttr<BlocksAttr>() &&
1954 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001955 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001956 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001957 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1958}
1959
1960/// \brief Set the copy inialization expression of a block var decl.
1961void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1962 assert(VD && Init && "Passed null params");
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001963 assert(VD->hasAttr<BlocksAttr>() &&
1964 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001965 BlockVarCopyInits[VD] = Init;
1966}
1967
John McCalla93c9342009-12-07 02:54:59 +00001968TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001969 unsigned DataSize) const {
John McCall109de5e2009-10-21 00:23:54 +00001970 if (!DataSize)
1971 DataSize = TypeLoc::getFullDataSizeForType(T);
1972 else
1973 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001974 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001975
John McCalla93c9342009-12-07 02:54:59 +00001976 TypeSourceInfo *TInfo =
1977 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1978 new (TInfo) TypeSourceInfo(T);
1979 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001980}
1981
John McCalla93c9342009-12-07 02:54:59 +00001982TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001983 SourceLocation L) const {
John McCalla93c9342009-12-07 02:54:59 +00001984 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregorc21c7e92011-01-25 19:13:18 +00001985 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCalla4eb74d2009-10-23 21:14:09 +00001986 return DI;
1987}
1988
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001989const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001990ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001991 return getObjCLayout(D, 0);
1992}
1993
1994const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001995ASTContext::getASTObjCImplementationLayout(
1996 const ObjCImplementationDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001997 return getObjCLayout(D->getClassInterface(), D);
1998}
1999
Chris Lattnera7674d82007-07-13 22:13:22 +00002000//===----------------------------------------------------------------------===//
2001// Type creation/memoization methods
2002//===----------------------------------------------------------------------===//
2003
Jay Foad4ba2a172011-01-12 09:06:06 +00002004QualType
John McCall3b657512011-01-19 10:06:00 +00002005ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2006 unsigned fastQuals = quals.getFastQualifiers();
2007 quals.removeFastQualifiers();
John McCall0953e762009-09-24 19:53:00 +00002008
2009 // Check if we've already instantiated this type.
2010 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00002011 ExtQuals::Profile(ID, baseType, quals);
2012 void *insertPos = 0;
2013 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2014 assert(eq->getQualifiers() == quals);
2015 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00002016 }
2017
John McCall3b657512011-01-19 10:06:00 +00002018 // If the base type is not canonical, make the appropriate canonical type.
2019 QualType canon;
2020 if (!baseType->isCanonicalUnqualified()) {
2021 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall200fa532012-02-08 00:46:36 +00002022 canonSplit.Quals.addConsistentQualifiers(quals);
2023 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00002024
2025 // Re-find the insert position.
2026 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2027 }
2028
2029 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2030 ExtQualNodes.InsertNode(eq, insertPos);
2031 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00002032}
2033
Jay Foad4ba2a172011-01-12 09:06:06 +00002034QualType
2035ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002036 QualType CanT = getCanonicalType(T);
2037 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00002038 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +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 address space specified, it cannot get
2046 // another one.
2047 assert(!Quals.hasAddressSpace() &&
2048 "Type cannot be in multiple addr spaces!");
2049 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00002050
John McCall0953e762009-09-24 19:53:00 +00002051 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00002052}
2053
Chris Lattnerb7d25532009-02-18 22:53:11 +00002054QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00002055 Qualifiers::GC GCAttr) const {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00002056 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00002057 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00002058 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00002059
John McCall7f040a92010-12-24 02:08:15 +00002060 if (const PointerType *ptr = T->getAs<PointerType>()) {
2061 QualType Pointee = ptr->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00002062 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00002063 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2064 return getPointerType(ResultType);
2065 }
2066 }
Mike Stump1eb44332009-09-09 15:08:12 +00002067
John McCall0953e762009-09-24 19:53:00 +00002068 // If we are composing extended qualifiers together, merge together
2069 // into one ExtQuals node.
2070 QualifierCollector Quals;
2071 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002072
John McCall0953e762009-09-24 19:53:00 +00002073 // If this type already has an ObjCGC specified, it cannot get
2074 // another one.
2075 assert(!Quals.hasObjCGCAttr() &&
2076 "Type cannot have multiple ObjCGCs!");
2077 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00002078
John McCall0953e762009-09-24 19:53:00 +00002079 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00002080}
Chris Lattnera7674d82007-07-13 22:13:22 +00002081
John McCalle6a365d2010-12-19 02:44:49 +00002082const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2083 FunctionType::ExtInfo Info) {
2084 if (T->getExtInfo() == Info)
2085 return T;
2086
2087 QualType Result;
2088 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
2089 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
2090 } else {
2091 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2092 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2093 EPI.ExtInfo = Info;
Reid Kleckner0567a792013-06-10 20:51:09 +00002094 Result = getFunctionType(FPT->getResultType(), FPT->getArgTypes(), EPI);
John McCalle6a365d2010-12-19 02:44:49 +00002095 }
2096
2097 return cast<FunctionType>(Result.getTypePtr());
2098}
2099
Richard Smith60e141e2013-05-04 07:00:32 +00002100void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2101 QualType ResultType) {
Richard Smith9dadfab2013-05-11 05:45:24 +00002102 FD = FD->getMostRecentDecl();
2103 while (true) {
Richard Smith60e141e2013-05-04 07:00:32 +00002104 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2105 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2106 FD->setType(getFunctionType(ResultType, FPT->getArgTypes(), EPI));
Richard Smith9dadfab2013-05-11 05:45:24 +00002107 if (FunctionDecl *Next = FD->getPreviousDecl())
2108 FD = Next;
2109 else
2110 break;
Richard Smith60e141e2013-05-04 07:00:32 +00002111 }
Richard Smith9dadfab2013-05-11 05:45:24 +00002112 if (ASTMutationListener *L = getASTMutationListener())
2113 L->DeducedReturnType(FD, ResultType);
Richard Smith60e141e2013-05-04 07:00:32 +00002114}
2115
Reid Spencer5f016e22007-07-11 17:01:13 +00002116/// getComplexType - Return the uniqued reference to the type for a complex
2117/// number with the specified element type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002118QualType ASTContext::getComplexType(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 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00002123
Reid Spencer5f016e22007-07-11 17:01:13 +00002124 void *InsertPos = 0;
2125 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2126 return QualType(CT, 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;
John McCall467b27b2009-10-22 20:10:53 +00002131 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002132 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00002133
Reid Spencer5f016e22007-07-11 17:01:13 +00002134 // Get the new insert position for the node we care about.
2135 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002136 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002137 }
John McCall6b304a02009-09-24 23:30:46 +00002138 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00002139 Types.push_back(New);
2140 ComplexTypes.InsertNode(New, InsertPos);
2141 return QualType(New, 0);
2142}
2143
Reid Spencer5f016e22007-07-11 17:01:13 +00002144/// getPointerType - Return the uniqued reference to the type for a pointer to
2145/// the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002146QualType ASTContext::getPointerType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002147 // Unique pointers, to guarantee there is only one pointer of a particular
2148 // structure.
2149 llvm::FoldingSetNodeID ID;
2150 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00002151
Reid Spencer5f016e22007-07-11 17:01:13 +00002152 void *InsertPos = 0;
2153 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2154 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002155
Reid Spencer5f016e22007-07-11 17:01:13 +00002156 // If the pointee type isn't canonical, this won't be a canonical type either,
2157 // so fill in the canonical type field.
2158 QualType Canonical;
Bob Wilsonc90cc932013-03-15 17:12:43 +00002159 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002160 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00002161
Bob Wilsonc90cc932013-03-15 17:12:43 +00002162 // Get the new insert position for the node we care about.
2163 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2164 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2165 }
John McCall6b304a02009-09-24 23:30:46 +00002166 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00002167 Types.push_back(New);
2168 PointerTypes.InsertNode(New, InsertPos);
2169 return QualType(New, 0);
2170}
2171
Reid Kleckner12df2462013-06-24 17:51:48 +00002172QualType ASTContext::getDecayedType(QualType T) const {
2173 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2174
2175 llvm::FoldingSetNodeID ID;
2176 DecayedType::Profile(ID, T);
2177 void *InsertPos = 0;
2178 if (DecayedType *DT = DecayedTypes.FindNodeOrInsertPos(ID, InsertPos))
2179 return QualType(DT, 0);
2180
2181 QualType Decayed;
2182
2183 // C99 6.7.5.3p7:
2184 // A declaration of a parameter as "array of type" shall be
2185 // adjusted to "qualified pointer to type", where the type
2186 // qualifiers (if any) are those specified within the [ and ] of
2187 // the array type derivation.
2188 if (T->isArrayType())
2189 Decayed = getArrayDecayedType(T);
2190
2191 // C99 6.7.5.3p8:
2192 // A declaration of a parameter as "function returning type"
2193 // shall be adjusted to "pointer to function returning type", as
2194 // in 6.3.2.1.
2195 if (T->isFunctionType())
2196 Decayed = getPointerType(T);
2197
2198 QualType Canonical = getCanonicalType(Decayed);
2199
2200 // Get the new insert position for the node we care about.
2201 DecayedType *NewIP = DecayedTypes.FindNodeOrInsertPos(ID, InsertPos);
2202 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2203
2204 DecayedType *New =
2205 new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2206 Types.push_back(New);
2207 DecayedTypes.InsertNode(New, InsertPos);
2208 return QualType(New, 0);
2209}
2210
Mike Stump1eb44332009-09-09 15:08:12 +00002211/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00002212/// a pointer to the specified block.
Jay Foad4ba2a172011-01-12 09:06:06 +00002213QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff296e8d52008-08-28 19:20:44 +00002214 assert(T->isFunctionType() && "block of function types only");
2215 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00002216 // structure.
2217 llvm::FoldingSetNodeID ID;
2218 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00002219
Steve Naroff5618bd42008-08-27 16:04:49 +00002220 void *InsertPos = 0;
2221 if (BlockPointerType *PT =
2222 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2223 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002224
2225 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00002226 // type either so fill in the canonical type field.
2227 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002228 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00002229 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00002230
Steve Naroff5618bd42008-08-27 16:04:49 +00002231 // Get the new insert position for the node we care about.
2232 BlockPointerType *NewIP =
2233 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002234 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00002235 }
John McCall6b304a02009-09-24 23:30:46 +00002236 BlockPointerType *New
2237 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00002238 Types.push_back(New);
2239 BlockPointerTypes.InsertNode(New, InsertPos);
2240 return QualType(New, 0);
2241}
2242
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002243/// getLValueReferenceType - Return the uniqued reference to the type for an
2244/// lvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002245QualType
2246ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor9625e442011-05-21 22:16:50 +00002247 assert(getCanonicalType(T) != OverloadTy &&
2248 "Unresolved overloaded function type");
2249
Reid Spencer5f016e22007-07-11 17:01:13 +00002250 // Unique pointers, to guarantee there is only one pointer of a particular
2251 // structure.
2252 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00002253 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00002254
2255 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002256 if (LValueReferenceType *RT =
2257 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002258 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002259
John McCall54e14c42009-10-22 22:37:11 +00002260 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2261
Reid Spencer5f016e22007-07-11 17:01:13 +00002262 // If the referencee type isn't canonical, this won't be a canonical type
2263 // either, so fill in the canonical type field.
2264 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00002265 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2266 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2267 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002268
Reid Spencer5f016e22007-07-11 17:01:13 +00002269 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002270 LValueReferenceType *NewIP =
2271 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002272 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002273 }
2274
John McCall6b304a02009-09-24 23:30:46 +00002275 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00002276 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2277 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00002278 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002279 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00002280
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002281 return QualType(New, 0);
2282}
2283
2284/// getRValueReferenceType - Return the uniqued reference to the type for an
2285/// rvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002286QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002287 // Unique pointers, to guarantee there is only one pointer of a particular
2288 // structure.
2289 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00002290 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002291
2292 void *InsertPos = 0;
2293 if (RValueReferenceType *RT =
2294 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2295 return QualType(RT, 0);
2296
John McCall54e14c42009-10-22 22:37:11 +00002297 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2298
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002299 // If the referencee type isn't canonical, this won't be a canonical type
2300 // either, so fill in the canonical type field.
2301 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00002302 if (InnerRef || !T.isCanonical()) {
2303 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2304 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002305
2306 // Get the new insert position for the node we care about.
2307 RValueReferenceType *NewIP =
2308 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002309 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002310 }
2311
John McCall6b304a02009-09-24 23:30:46 +00002312 RValueReferenceType *New
2313 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002314 Types.push_back(New);
2315 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002316 return QualType(New, 0);
2317}
2318
Sebastian Redlf30208a2009-01-24 21:16:55 +00002319/// getMemberPointerType - Return the uniqued reference to the type for a
2320/// member pointer to the specified type, in the specified class.
Jay Foad4ba2a172011-01-12 09:06:06 +00002321QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redlf30208a2009-01-24 21:16:55 +00002322 // Unique pointers, to guarantee there is only one pointer of a particular
2323 // structure.
2324 llvm::FoldingSetNodeID ID;
2325 MemberPointerType::Profile(ID, T, Cls);
2326
2327 void *InsertPos = 0;
2328 if (MemberPointerType *PT =
2329 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2330 return QualType(PT, 0);
2331
2332 // If the pointee or class type isn't canonical, this won't be a canonical
2333 // type either, so fill in the canonical type field.
2334 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00002335 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00002336 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2337
2338 // Get the new insert position for the node we care about.
2339 MemberPointerType *NewIP =
2340 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002341 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redlf30208a2009-01-24 21:16:55 +00002342 }
John McCall6b304a02009-09-24 23:30:46 +00002343 MemberPointerType *New
2344 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00002345 Types.push_back(New);
2346 MemberPointerTypes.InsertNode(New, InsertPos);
2347 return QualType(New, 0);
2348}
2349
Mike Stump1eb44332009-09-09 15:08:12 +00002350/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00002351/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002352QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00002353 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00002354 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002355 unsigned IndexTypeQuals) const {
Sebastian Redl923d56d2009-11-05 15:52:31 +00002356 assert((EltTy->isDependentType() ||
2357 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00002358 "Constant array of VLAs is illegal!");
2359
Chris Lattner38aeec72009-05-13 04:12:56 +00002360 // Convert the array size into a canonical width matching the pointer size for
2361 // the target.
2362 llvm::APInt ArySize(ArySizeIn);
Jay Foad9f71a8f2010-12-07 08:25:34 +00002363 ArySize =
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002364 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump1eb44332009-09-09 15:08:12 +00002365
Reid Spencer5f016e22007-07-11 17:01:13 +00002366 llvm::FoldingSetNodeID ID;
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002367 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00002368
Reid Spencer5f016e22007-07-11 17:01:13 +00002369 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002370 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002371 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002372 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002373
John McCall3b657512011-01-19 10:06:00 +00002374 // If the element type isn't canonical or has qualifiers, this won't
2375 // be a canonical type either, so fill in the canonical type field.
2376 QualType Canon;
2377 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2378 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00002379 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002380 ASM, IndexTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00002381 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00002382
Reid Spencer5f016e22007-07-11 17:01:13 +00002383 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00002384 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002385 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002386 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002387 }
Mike Stump1eb44332009-09-09 15:08:12 +00002388
John McCall6b304a02009-09-24 23:30:46 +00002389 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002390 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002391 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002392 Types.push_back(New);
2393 return QualType(New, 0);
2394}
2395
John McCallce889032011-01-18 08:40:38 +00002396/// getVariableArrayDecayedType - Turns the given type, which may be
2397/// variably-modified, into the corresponding type with all the known
2398/// sizes replaced with [*].
2399QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2400 // Vastly most common case.
2401 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002402
John McCallce889032011-01-18 08:40:38 +00002403 QualType result;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002404
John McCallce889032011-01-18 08:40:38 +00002405 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00002406 const Type *ty = split.Ty;
John McCallce889032011-01-18 08:40:38 +00002407 switch (ty->getTypeClass()) {
2408#define TYPE(Class, Base)
2409#define ABSTRACT_TYPE(Class, Base)
2410#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2411#include "clang/AST/TypeNodes.def"
2412 llvm_unreachable("didn't desugar past all non-canonical types?");
2413
2414 // These types should never be variably-modified.
2415 case Type::Builtin:
2416 case Type::Complex:
2417 case Type::Vector:
2418 case Type::ExtVector:
2419 case Type::DependentSizedExtVector:
2420 case Type::ObjCObject:
2421 case Type::ObjCInterface:
2422 case Type::ObjCObjectPointer:
2423 case Type::Record:
2424 case Type::Enum:
2425 case Type::UnresolvedUsing:
2426 case Type::TypeOfExpr:
2427 case Type::TypeOf:
2428 case Type::Decltype:
Sean Huntca63c202011-05-24 22:41:36 +00002429 case Type::UnaryTransform:
John McCallce889032011-01-18 08:40:38 +00002430 case Type::DependentName:
2431 case Type::InjectedClassName:
2432 case Type::TemplateSpecialization:
2433 case Type::DependentTemplateSpecialization:
2434 case Type::TemplateTypeParm:
2435 case Type::SubstTemplateTypeParmPack:
Richard Smith34b41d92011-02-20 03:19:35 +00002436 case Type::Auto:
John McCallce889032011-01-18 08:40:38 +00002437 case Type::PackExpansion:
2438 llvm_unreachable("type should never be variably-modified");
2439
2440 // These types can be variably-modified but should never need to
2441 // further decay.
2442 case Type::FunctionNoProto:
2443 case Type::FunctionProto:
2444 case Type::BlockPointer:
2445 case Type::MemberPointer:
2446 return type;
2447
2448 // These types can be variably-modified. All these modifications
2449 // preserve structure except as noted by comments.
2450 // TODO: if we ever care about optimizing VLAs, there are no-op
2451 // optimizations available here.
2452 case Type::Pointer:
2453 result = getPointerType(getVariableArrayDecayedType(
2454 cast<PointerType>(ty)->getPointeeType()));
2455 break;
2456
2457 case Type::LValueReference: {
2458 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2459 result = getLValueReferenceType(
2460 getVariableArrayDecayedType(lv->getPointeeType()),
2461 lv->isSpelledAsLValue());
2462 break;
2463 }
2464
2465 case Type::RValueReference: {
2466 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2467 result = getRValueReferenceType(
2468 getVariableArrayDecayedType(lv->getPointeeType()));
2469 break;
2470 }
2471
Eli Friedmanb001de72011-10-06 23:00:33 +00002472 case Type::Atomic: {
2473 const AtomicType *at = cast<AtomicType>(ty);
2474 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2475 break;
2476 }
2477
John McCallce889032011-01-18 08:40:38 +00002478 case Type::ConstantArray: {
2479 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2480 result = getConstantArrayType(
2481 getVariableArrayDecayedType(cat->getElementType()),
2482 cat->getSize(),
2483 cat->getSizeModifier(),
2484 cat->getIndexTypeCVRQualifiers());
2485 break;
2486 }
2487
2488 case Type::DependentSizedArray: {
2489 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2490 result = getDependentSizedArrayType(
2491 getVariableArrayDecayedType(dat->getElementType()),
2492 dat->getSizeExpr(),
2493 dat->getSizeModifier(),
2494 dat->getIndexTypeCVRQualifiers(),
2495 dat->getBracketsRange());
2496 break;
2497 }
2498
2499 // Turn incomplete types into [*] types.
2500 case Type::IncompleteArray: {
2501 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2502 result = getVariableArrayType(
2503 getVariableArrayDecayedType(iat->getElementType()),
2504 /*size*/ 0,
2505 ArrayType::Normal,
2506 iat->getIndexTypeCVRQualifiers(),
2507 SourceRange());
2508 break;
2509 }
2510
2511 // Turn VLA types into [*] types.
2512 case Type::VariableArray: {
2513 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2514 result = getVariableArrayType(
2515 getVariableArrayDecayedType(vat->getElementType()),
2516 /*size*/ 0,
2517 ArrayType::Star,
2518 vat->getIndexTypeCVRQualifiers(),
2519 vat->getBracketsRange());
2520 break;
2521 }
2522 }
2523
2524 // Apply the top-level qualifiers from the original.
John McCall200fa532012-02-08 00:46:36 +00002525 return getQualifiedType(result, split.Quals);
John McCallce889032011-01-18 08:40:38 +00002526}
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002527
Steve Naroffbdbf7b02007-08-30 18:14:25 +00002528/// getVariableArrayType - Returns a non-unique reference to the type for a
2529/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002530QualType ASTContext::getVariableArrayType(QualType EltTy,
2531 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00002532 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002533 unsigned IndexTypeQuals,
Jay Foad4ba2a172011-01-12 09:06:06 +00002534 SourceRange Brackets) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00002535 // Since we don't unique expressions, it isn't possible to unique VLA's
2536 // that have an expression provided for their size.
John McCall3b657512011-01-19 10:06:00 +00002537 QualType Canon;
Douglas Gregor715e9c82010-05-23 16:10:32 +00002538
John McCall3b657512011-01-19 10:06:00 +00002539 // Be sure to pull qualifiers off the element type.
2540 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2541 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00002542 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002543 IndexTypeQuals, Brackets);
John McCall200fa532012-02-08 00:46:36 +00002544 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor715e9c82010-05-23 16:10:32 +00002545 }
2546
John McCall6b304a02009-09-24 23:30:46 +00002547 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002548 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002549
2550 VariableArrayTypes.push_back(New);
2551 Types.push_back(New);
2552 return QualType(New, 0);
2553}
2554
Douglas Gregor898574e2008-12-05 23:32:09 +00002555/// getDependentSizedArrayType - Returns a non-unique reference to
2556/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00002557/// type.
John McCall3b657512011-01-19 10:06:00 +00002558QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2559 Expr *numElements,
Douglas Gregor898574e2008-12-05 23:32:09 +00002560 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00002561 unsigned elementTypeQuals,
2562 SourceRange brackets) const {
2563 assert((!numElements || numElements->isTypeDependent() ||
2564 numElements->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00002565 "Size must be type- or value-dependent!");
2566
John McCall3b657512011-01-19 10:06:00 +00002567 // Dependently-sized array types that do not have a specified number
2568 // of elements will have their sizes deduced from a dependent
2569 // initializer. We do no canonicalization here at all, which is okay
2570 // because they can't be used in most locations.
2571 if (!numElements) {
2572 DependentSizedArrayType *newType
2573 = new (*this, TypeAlignment)
2574 DependentSizedArrayType(*this, elementType, QualType(),
2575 numElements, ASM, elementTypeQuals,
2576 brackets);
2577 Types.push_back(newType);
2578 return QualType(newType, 0);
2579 }
2580
2581 // Otherwise, we actually build a new type every time, but we
2582 // also build a canonical type.
2583
2584 SplitQualType canonElementType = getCanonicalType(elementType).split();
2585
2586 void *insertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00002587 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00002588 DependentSizedArrayType::Profile(ID, *this,
John McCall200fa532012-02-08 00:46:36 +00002589 QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002590 ASM, elementTypeQuals, numElements);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002591
John McCall3b657512011-01-19 10:06:00 +00002592 // Look for an existing type with these properties.
2593 DependentSizedArrayType *canonTy =
2594 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002595
John McCall3b657512011-01-19 10:06:00 +00002596 // If we don't have one, build one.
2597 if (!canonTy) {
2598 canonTy = new (*this, TypeAlignment)
John McCall200fa532012-02-08 00:46:36 +00002599 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002600 QualType(), numElements, ASM, elementTypeQuals,
2601 brackets);
2602 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2603 Types.push_back(canonTy);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002604 }
2605
John McCall3b657512011-01-19 10:06:00 +00002606 // Apply qualifiers from the element type to the array.
2607 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall200fa532012-02-08 00:46:36 +00002608 canonElementType.Quals);
Mike Stump1eb44332009-09-09 15:08:12 +00002609
John McCall3b657512011-01-19 10:06:00 +00002610 // If we didn't need extra canonicalization for the element type,
2611 // then just use that as our result.
John McCall200fa532012-02-08 00:46:36 +00002612 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall3b657512011-01-19 10:06:00 +00002613 return canon;
2614
2615 // Otherwise, we need to build a type which follows the spelling
2616 // of the element type.
2617 DependentSizedArrayType *sugaredType
2618 = new (*this, TypeAlignment)
2619 DependentSizedArrayType(*this, elementType, canon, numElements,
2620 ASM, elementTypeQuals, brackets);
2621 Types.push_back(sugaredType);
2622 return QualType(sugaredType, 0);
Douglas Gregor898574e2008-12-05 23:32:09 +00002623}
2624
John McCall3b657512011-01-19 10:06:00 +00002625QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanc5773c42008-02-15 18:16:39 +00002626 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00002627 unsigned elementTypeQuals) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00002628 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00002629 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002630
John McCall3b657512011-01-19 10:06:00 +00002631 void *insertPos = 0;
2632 if (IncompleteArrayType *iat =
2633 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2634 return QualType(iat, 0);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002635
2636 // If the element type isn't canonical, this won't be a canonical type
John McCall3b657512011-01-19 10:06:00 +00002637 // either, so fill in the canonical type field. We also have to pull
2638 // qualifiers off the element type.
2639 QualType canon;
Eli Friedmanc5773c42008-02-15 18:16:39 +00002640
John McCall3b657512011-01-19 10:06:00 +00002641 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2642 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall200fa532012-02-08 00:46:36 +00002643 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002644 ASM, elementTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00002645 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002646
2647 // Get the new insert position for the node we care about.
John McCall3b657512011-01-19 10:06:00 +00002648 IncompleteArrayType *existing =
2649 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2650 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00002651 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00002652
John McCall3b657512011-01-19 10:06:00 +00002653 IncompleteArrayType *newType = new (*this, TypeAlignment)
2654 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002655
John McCall3b657512011-01-19 10:06:00 +00002656 IncompleteArrayTypes.InsertNode(newType, insertPos);
2657 Types.push_back(newType);
2658 return QualType(newType, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00002659}
2660
Steve Naroff73322922007-07-18 18:00:27 +00002661/// getVectorType - Return the unique reference to a vector type of
2662/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00002663QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad4ba2a172011-01-12 09:06:06 +00002664 VectorType::VectorKind VecKind) const {
John McCall3b657512011-01-19 10:06:00 +00002665 assert(vecType->isBuiltinType());
Mike Stump1eb44332009-09-09 15:08:12 +00002666
Reid Spencer5f016e22007-07-11 17:01:13 +00002667 // Check if we've already instantiated a vector of this type.
2668 llvm::FoldingSetNodeID ID;
Bob Wilsone86d78c2010-11-10 21:56:12 +00002669 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner788b0fd2010-06-23 06:00:24 +00002670
Reid Spencer5f016e22007-07-11 17:01:13 +00002671 void *InsertPos = 0;
2672 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2673 return QualType(VTP, 0);
2674
2675 // If the element type isn't canonical, this won't be a canonical type either,
2676 // so fill in the canonical type field.
2677 QualType Canonical;
Douglas Gregor255210e2010-08-06 10:14:59 +00002678 if (!vecType.isCanonical()) {
Bob Wilson231da7e2010-11-16 00:32:20 +00002679 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump1eb44332009-09-09 15:08:12 +00002680
Reid Spencer5f016e22007-07-11 17:01:13 +00002681 // Get the new insert position for the node we care about.
2682 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002683 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002684 }
John McCall6b304a02009-09-24 23:30:46 +00002685 VectorType *New = new (*this, TypeAlignment)
Bob Wilsone86d78c2010-11-10 21:56:12 +00002686 VectorType(vecType, NumElts, Canonical, VecKind);
Reid Spencer5f016e22007-07-11 17:01:13 +00002687 VectorTypes.InsertNode(New, InsertPos);
2688 Types.push_back(New);
2689 return QualType(New, 0);
2690}
2691
Nate Begeman213541a2008-04-18 23:10:10 +00002692/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00002693/// the specified element type and size. VectorType must be a built-in type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002694QualType
2695ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor4ac01402011-06-15 16:02:29 +00002696 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump1eb44332009-09-09 15:08:12 +00002697
Steve Naroff73322922007-07-18 18:00:27 +00002698 // Check if we've already instantiated a vector of this type.
2699 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00002700 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsone86d78c2010-11-10 21:56:12 +00002701 VectorType::GenericVector);
Steve Naroff73322922007-07-18 18:00:27 +00002702 void *InsertPos = 0;
2703 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2704 return QualType(VTP, 0);
2705
2706 // If the element type isn't canonical, this won't be a canonical type either,
2707 // so fill in the canonical type field.
2708 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002709 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00002710 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00002711
Steve Naroff73322922007-07-18 18:00:27 +00002712 // Get the new insert position for the node we care about.
2713 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002714 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00002715 }
John McCall6b304a02009-09-24 23:30:46 +00002716 ExtVectorType *New = new (*this, TypeAlignment)
2717 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00002718 VectorTypes.InsertNode(New, InsertPos);
2719 Types.push_back(New);
2720 return QualType(New, 0);
2721}
2722
Jay Foad4ba2a172011-01-12 09:06:06 +00002723QualType
2724ASTContext::getDependentSizedExtVectorType(QualType vecType,
2725 Expr *SizeExpr,
2726 SourceLocation AttrLoc) const {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002727 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00002728 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002729 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002730
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002731 void *InsertPos = 0;
2732 DependentSizedExtVectorType *Canon
2733 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2734 DependentSizedExtVectorType *New;
2735 if (Canon) {
2736 // We already have a canonical version of this array type; use it as
2737 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00002738 New = new (*this, TypeAlignment)
2739 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2740 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002741 } else {
2742 QualType CanonVecTy = getCanonicalType(vecType);
2743 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00002744 New = new (*this, TypeAlignment)
2745 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2746 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002747
2748 DependentSizedExtVectorType *CanonCheck
2749 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2750 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2751 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002752 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2753 } else {
2754 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2755 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00002756 New = new (*this, TypeAlignment)
2757 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002758 }
2759 }
Mike Stump1eb44332009-09-09 15:08:12 +00002760
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00002761 Types.push_back(New);
2762 return QualType(New, 0);
2763}
2764
Douglas Gregor72564e72009-02-26 23:50:07 +00002765/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00002766///
Jay Foad4ba2a172011-01-12 09:06:06 +00002767QualType
2768ASTContext::getFunctionNoProtoType(QualType ResultTy,
2769 const FunctionType::ExtInfo &Info) const {
Roman Divackycfe9af22011-03-01 17:40:53 +00002770 const CallingConv DefaultCC = Info.getCC();
2771 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2772 CC_X86StdCall : DefaultCC;
Reid Spencer5f016e22007-07-11 17:01:13 +00002773 // Unique functions, to guarantee there is only one function of a particular
2774 // structure.
2775 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00002776 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00002777
Reid Spencer5f016e22007-07-11 17:01:13 +00002778 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002779 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00002780 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002781 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002782
Reid Spencer5f016e22007-07-11 17:01:13 +00002783 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00002784 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00002785 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00002786 Canonical =
2787 getFunctionNoProtoType(getCanonicalType(ResultTy),
2788 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump1eb44332009-09-09 15:08:12 +00002789
Reid Spencer5f016e22007-07-11 17:01:13 +00002790 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002791 FunctionNoProtoType *NewIP =
2792 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002793 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002794 }
Mike Stump1eb44332009-09-09 15:08:12 +00002795
Roman Divackycfe9af22011-03-01 17:40:53 +00002796 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall6b304a02009-09-24 23:30:46 +00002797 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divackycfe9af22011-03-01 17:40:53 +00002798 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00002799 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00002800 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002801 return QualType(New, 0);
2802}
2803
Douglas Gregor02dd7982013-01-17 23:36:45 +00002804/// \brief Determine whether \p T is canonical as the result type of a function.
2805static bool isCanonicalResultType(QualType T) {
2806 return T.isCanonical() &&
2807 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2808 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2809}
2810
Reid Spencer5f016e22007-07-11 17:01:13 +00002811/// getFunctionType - Return a normal function type with a typed argument
2812/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad4ba2a172011-01-12 09:06:06 +00002813QualType
Jordan Rosebea522f2013-03-08 21:51:21 +00002814ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad4ba2a172011-01-12 09:06:06 +00002815 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rosebea522f2013-03-08 21:51:21 +00002816 size_t NumArgs = ArgArray.size();
2817
Reid Spencer5f016e22007-07-11 17:01:13 +00002818 // Unique functions, to guarantee there is only one function of a particular
2819 // structure.
2820 llvm::FoldingSetNodeID ID;
Jordan Rosebea522f2013-03-08 21:51:21 +00002821 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
2822 *this);
Reid Spencer5f016e22007-07-11 17:01:13 +00002823
2824 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002825 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00002826 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002827 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00002828
2829 // Determine whether the type being created is already canonical or not.
Richard Smitheefb3d52012-02-10 09:58:53 +00002830 bool isCanonical =
Douglas Gregor02dd7982013-01-17 23:36:45 +00002831 EPI.ExceptionSpecType == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smitheefb3d52012-02-10 09:58:53 +00002832 !EPI.HasTrailingReturn;
Reid Spencer5f016e22007-07-11 17:01:13 +00002833 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002834 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00002835 isCanonical = false;
2836
Roman Divackycfe9af22011-03-01 17:40:53 +00002837 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2838 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2839 CC_X86StdCall : DefaultCC;
John McCalle23cf432010-12-14 08:05:40 +00002840
Reid Spencer5f016e22007-07-11 17:01:13 +00002841 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00002842 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002843 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00002844 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002845 SmallVector<QualType, 16> CanonicalArgs;
Reid Spencer5f016e22007-07-11 17:01:13 +00002846 CanonicalArgs.reserve(NumArgs);
2847 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002848 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00002849
John McCalle23cf432010-12-14 08:05:40 +00002850 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smitheefb3d52012-02-10 09:58:53 +00002851 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002852 CanonicalEPI.ExceptionSpecType = EST_None;
2853 CanonicalEPI.NumExceptions = 0;
John McCalle23cf432010-12-14 08:05:40 +00002854 CanonicalEPI.ExtInfo
2855 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2856
Douglas Gregor02dd7982013-01-17 23:36:45 +00002857 // Result types do not have ARC lifetime qualifiers.
2858 QualType CanResultTy = getCanonicalType(ResultTy);
2859 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2860 Qualifiers Qs = CanResultTy.getQualifiers();
2861 Qs.removeObjCLifetime();
2862 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2863 }
2864
Jordan Rosebea522f2013-03-08 21:51:21 +00002865 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl465226e2009-05-27 22:11:52 +00002866
Reid Spencer5f016e22007-07-11 17:01:13 +00002867 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002868 FunctionProtoType *NewIP =
2869 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002870 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002871 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002872
John McCallf85e1932011-06-15 23:02:42 +00002873 // FunctionProtoType objects are allocated with extra bytes after
2874 // them for three variable size arrays at the end:
2875 // - parameter types
2876 // - exception types
2877 // - consumed-arguments flags
2878 // Instead of the exception types, there could be a noexcept
Richard Smithb9d0b762012-07-27 04:22:15 +00002879 // expression, or information used to resolve the exception
2880 // specification.
John McCalle23cf432010-12-14 08:05:40 +00002881 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redl60618fa2011-03-12 11:50:43 +00002882 NumArgs * sizeof(QualType);
Richard Smithb9d0b762012-07-27 04:22:15 +00002883 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redl60618fa2011-03-12 11:50:43 +00002884 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithb9d0b762012-07-27 04:22:15 +00002885 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002886 Size += sizeof(Expr*);
Richard Smithe6975e92012-04-17 00:58:00 +00002887 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smith13bffc52012-04-19 00:08:28 +00002888 Size += 2 * sizeof(FunctionDecl*);
Richard Smithb9d0b762012-07-27 04:22:15 +00002889 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2890 Size += sizeof(FunctionDecl*);
Sebastian Redl60618fa2011-03-12 11:50:43 +00002891 }
John McCallf85e1932011-06-15 23:02:42 +00002892 if (EPI.ConsumedArguments)
2893 Size += NumArgs * sizeof(bool);
2894
John McCalle23cf432010-12-14 08:05:40 +00002895 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divackycfe9af22011-03-01 17:40:53 +00002896 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2897 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Jordan Rosebea522f2013-03-08 21:51:21 +00002898 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00002899 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00002900 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002901 return QualType(FTP, 0);
2902}
2903
John McCall3cb0ebd2010-03-10 03:28:59 +00002904#ifndef NDEBUG
2905static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2906 if (!isa<CXXRecordDecl>(D)) return false;
2907 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2908 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2909 return true;
2910 if (RD->getDescribedClassTemplate() &&
2911 !isa<ClassTemplateSpecializationDecl>(RD))
2912 return true;
2913 return false;
2914}
2915#endif
2916
2917/// getInjectedClassNameType - Return the unique reference to the
2918/// injected class name type for the specified templated declaration.
2919QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00002920 QualType TST) const {
John McCall3cb0ebd2010-03-10 03:28:59 +00002921 assert(NeedsInjectedClassNameType(Decl));
2922 if (Decl->TypeForDecl) {
2923 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregoref96ee02012-01-14 16:38:05 +00002924 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00002925 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2926 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2927 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2928 } else {
John McCallf4c73712011-01-19 06:33:43 +00002929 Type *newType =
John McCall31f17ec2010-04-27 00:57:59 +00002930 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCallf4c73712011-01-19 06:33:43 +00002931 Decl->TypeForDecl = newType;
2932 Types.push_back(newType);
John McCall3cb0ebd2010-03-10 03:28:59 +00002933 }
2934 return QualType(Decl->TypeForDecl, 0);
2935}
2936
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002937/// getTypeDeclType - Return the unique reference to the type for the
2938/// specified type declaration.
Jay Foad4ba2a172011-01-12 09:06:06 +00002939QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00002940 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00002941 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00002942
Richard Smith162e1c12011-04-15 14:24:37 +00002943 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002944 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00002945
John McCallbecb8d52010-03-10 06:48:02 +00002946 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2947 "Template type parameter types are always available.");
2948
John McCall19c85762010-02-16 03:57:14 +00002949 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002950 assert(!Record->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002951 "struct/union has previous declaration");
2952 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002953 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00002954 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002955 assert(!Enum->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002956 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002957 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00002958 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00002959 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCallf4c73712011-01-19 06:33:43 +00002960 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2961 Decl->TypeForDecl = newType;
2962 Types.push_back(newType);
Mike Stump9fdbab32009-07-31 02:02:20 +00002963 } else
John McCallbecb8d52010-03-10 06:48:02 +00002964 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002965
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002966 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002967}
2968
Reid Spencer5f016e22007-07-11 17:01:13 +00002969/// getTypedefType - Return the unique reference to the type for the
Richard Smith162e1c12011-04-15 14:24:37 +00002970/// specified typedef name decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002971QualType
Richard Smith162e1c12011-04-15 14:24:37 +00002972ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2973 QualType Canonical) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002974 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002975
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002976 if (Canonical.isNull())
2977 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCallf4c73712011-01-19 06:33:43 +00002978 TypedefType *newType = new(*this, TypeAlignment)
John McCall6b304a02009-09-24 23:30:46 +00002979 TypedefType(Type::Typedef, Decl, Canonical);
John McCallf4c73712011-01-19 06:33:43 +00002980 Decl->TypeForDecl = newType;
2981 Types.push_back(newType);
2982 return QualType(newType, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002983}
2984
Jay Foad4ba2a172011-01-12 09:06:06 +00002985QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002986 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2987
Douglas Gregoref96ee02012-01-14 16:38:05 +00002988 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002989 if (PrevDecl->TypeForDecl)
2990 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2991
John McCallf4c73712011-01-19 06:33:43 +00002992 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2993 Decl->TypeForDecl = newType;
2994 Types.push_back(newType);
2995 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002996}
2997
Jay Foad4ba2a172011-01-12 09:06:06 +00002998QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002999 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3000
Douglas Gregoref96ee02012-01-14 16:38:05 +00003001 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00003002 if (PrevDecl->TypeForDecl)
3003 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3004
John McCallf4c73712011-01-19 06:33:43 +00003005 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3006 Decl->TypeForDecl = newType;
3007 Types.push_back(newType);
3008 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00003009}
3010
John McCall9d156a72011-01-06 01:58:22 +00003011QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3012 QualType modifiedType,
3013 QualType equivalentType) {
3014 llvm::FoldingSetNodeID id;
3015 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3016
3017 void *insertPos = 0;
3018 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3019 if (type) return QualType(type, 0);
3020
3021 QualType canon = getCanonicalType(equivalentType);
3022 type = new (*this, TypeAlignment)
3023 AttributedType(canon, attrKind, modifiedType, equivalentType);
3024
3025 Types.push_back(type);
3026 AttributedTypes.InsertNode(type, insertPos);
3027
3028 return QualType(type, 0);
3029}
3030
3031
John McCall49a832b2009-10-18 09:09:24 +00003032/// \brief Retrieve a substitution-result type.
3033QualType
3034ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad4ba2a172011-01-12 09:06:06 +00003035 QualType Replacement) const {
John McCall467b27b2009-10-22 20:10:53 +00003036 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00003037 && "replacement types must always be canonical");
3038
3039 llvm::FoldingSetNodeID ID;
3040 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
3041 void *InsertPos = 0;
3042 SubstTemplateTypeParmType *SubstParm
3043 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3044
3045 if (!SubstParm) {
3046 SubstParm = new (*this, TypeAlignment)
3047 SubstTemplateTypeParmType(Parm, Replacement);
3048 Types.push_back(SubstParm);
3049 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3050 }
3051
3052 return QualType(SubstParm, 0);
3053}
3054
Douglas Gregorc3069d62011-01-14 02:55:32 +00003055/// \brief Retrieve a
3056QualType ASTContext::getSubstTemplateTypeParmPackType(
3057 const TemplateTypeParmType *Parm,
3058 const TemplateArgument &ArgPack) {
3059#ifndef NDEBUG
3060 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
3061 PEnd = ArgPack.pack_end();
3062 P != PEnd; ++P) {
3063 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3064 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
3065 }
3066#endif
3067
3068 llvm::FoldingSetNodeID ID;
3069 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
3070 void *InsertPos = 0;
3071 if (SubstTemplateTypeParmPackType *SubstParm
3072 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3073 return QualType(SubstParm, 0);
3074
3075 QualType Canon;
3076 if (!Parm->isCanonicalUnqualified()) {
3077 Canon = getCanonicalType(QualType(Parm, 0));
3078 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3079 ArgPack);
3080 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3081 }
3082
3083 SubstTemplateTypeParmPackType *SubstParm
3084 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3085 ArgPack);
3086 Types.push_back(SubstParm);
3087 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3088 return QualType(SubstParm, 0);
3089}
3090
Douglas Gregorfab9d672009-02-05 23:33:38 +00003091/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00003092/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003093/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00003094QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003095 bool ParameterPack,
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003096 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregorfab9d672009-02-05 23:33:38 +00003097 llvm::FoldingSetNodeID ID;
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003098 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregorfab9d672009-02-05 23:33:38 +00003099 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003100 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00003101 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3102
3103 if (TypeParm)
3104 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00003105
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003106 if (TTPDecl) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003107 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003108 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003109
3110 TemplateTypeParmType *TypeCheck
3111 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3112 assert(!TypeCheck && "Template type parameter canonical type broken");
3113 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003114 } else
John McCall6b304a02009-09-24 23:30:46 +00003115 TypeParm = new (*this, TypeAlignment)
3116 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00003117
3118 Types.push_back(TypeParm);
3119 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3120
3121 return QualType(TypeParm, 0);
3122}
3123
John McCall3cb0ebd2010-03-10 03:28:59 +00003124TypeSourceInfo *
3125ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3126 SourceLocation NameLoc,
3127 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003128 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003129 assert(!Name.getAsDependentTemplateName() &&
3130 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00003131 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCall3cb0ebd2010-03-10 03:28:59 +00003132
3133 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie39e6ab42013-02-18 22:06:02 +00003134 TemplateSpecializationTypeLoc TL =
3135 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara55d23c92012-02-06 14:41:24 +00003136 TL.setTemplateKeywordLoc(SourceLocation());
John McCall3cb0ebd2010-03-10 03:28:59 +00003137 TL.setTemplateNameLoc(NameLoc);
3138 TL.setLAngleLoc(Args.getLAngleLoc());
3139 TL.setRAngleLoc(Args.getRAngleLoc());
3140 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3141 TL.setArgLocInfo(i, Args[i].getLocInfo());
3142 return DI;
3143}
3144
Mike Stump1eb44332009-09-09 15:08:12 +00003145QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00003146ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00003147 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003148 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003149 assert(!Template.getAsDependentTemplateName() &&
3150 "No dependent template names here!");
3151
John McCalld5532b62009-11-23 01:53:49 +00003152 unsigned NumArgs = Args.size();
3153
Chris Lattner5f9e2722011-07-23 10:55:15 +00003154 SmallVector<TemplateArgument, 4> ArgVec;
John McCall833ca992009-10-29 08:12:44 +00003155 ArgVec.reserve(NumArgs);
3156 for (unsigned i = 0; i != NumArgs; ++i)
3157 ArgVec.push_back(Args[i].getArgument());
3158
John McCall31f17ec2010-04-27 00:57:59 +00003159 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003160 Underlying);
John McCall833ca992009-10-29 08:12:44 +00003161}
3162
Douglas Gregorb70126a2012-02-03 17:16:23 +00003163#ifndef NDEBUG
3164static bool hasAnyPackExpansions(const TemplateArgument *Args,
3165 unsigned NumArgs) {
3166 for (unsigned I = 0; I != NumArgs; ++I)
3167 if (Args[I].isPackExpansion())
3168 return true;
3169
3170 return true;
3171}
3172#endif
3173
John McCall833ca992009-10-29 08:12:44 +00003174QualType
3175ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003176 const TemplateArgument *Args,
3177 unsigned NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003178 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003179 assert(!Template.getAsDependentTemplateName() &&
3180 "No dependent template names here!");
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00003181 // Look through qualified template names.
3182 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3183 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003184
Douglas Gregorb70126a2012-02-03 17:16:23 +00003185 bool IsTypeAlias =
Richard Smith3e4c6c42011-05-05 21:57:07 +00003186 Template.getAsTemplateDecl() &&
3187 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00003188 QualType CanonType;
3189 if (!Underlying.isNull())
3190 CanonType = getCanonicalType(Underlying);
3191 else {
Douglas Gregorb70126a2012-02-03 17:16:23 +00003192 // We can get here with an alias template when the specialization contains
3193 // a pack expansion that does not match up with a parameter pack.
3194 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3195 "Caller must compute aliased type");
3196 IsTypeAlias = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00003197 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3198 NumArgs);
3199 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00003200
Douglas Gregor1275ae02009-07-28 23:00:59 +00003201 // Allocate the (non-canonical) template specialization type, but don't
3202 // try to unique it: these types typically have location information that
3203 // we don't unique and don't want to lose.
Richard Smith3e4c6c42011-05-05 21:57:07 +00003204 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3205 sizeof(TemplateArgument) * NumArgs +
Douglas Gregorb70126a2012-02-03 17:16:23 +00003206 (IsTypeAlias? sizeof(QualType) : 0),
John McCall6b304a02009-09-24 23:30:46 +00003207 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00003208 TemplateSpecializationType *Spec
Douglas Gregorb70126a2012-02-03 17:16:23 +00003209 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3210 IsTypeAlias ? Underlying : QualType());
Mike Stump1eb44332009-09-09 15:08:12 +00003211
Douglas Gregor55f6b142009-02-09 18:46:07 +00003212 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00003213 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00003214}
3215
Mike Stump1eb44332009-09-09 15:08:12 +00003216QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003217ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3218 const TemplateArgument *Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00003219 unsigned NumArgs) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003220 assert(!Template.getAsDependentTemplateName() &&
3221 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00003222
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00003223 // Look through qualified template names.
3224 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3225 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003226
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003227 // Build the canonical template specialization type.
3228 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003229 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003230 CanonArgs.reserve(NumArgs);
3231 for (unsigned I = 0; I != NumArgs; ++I)
3232 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3233
3234 // Determine whether this canonical template specialization type already
3235 // exists.
3236 llvm::FoldingSetNodeID ID;
3237 TemplateSpecializationType::Profile(ID, CanonTemplate,
3238 CanonArgs.data(), NumArgs, *this);
3239
3240 void *InsertPos = 0;
3241 TemplateSpecializationType *Spec
3242 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3243
3244 if (!Spec) {
3245 // Allocate a new canonical template specialization type.
3246 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3247 sizeof(TemplateArgument) * NumArgs),
3248 TypeAlignment);
3249 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3250 CanonArgs.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003251 QualType(), QualType());
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003252 Types.push_back(Spec);
3253 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3254 }
3255
3256 assert(Spec->isDependentType() &&
3257 "Non-dependent template-id type must have a canonical type");
3258 return QualType(Spec, 0);
3259}
3260
3261QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003262ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3263 NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00003264 QualType NamedType) const {
Douglas Gregore4e5b052009-03-19 00:18:19 +00003265 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003266 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003267
3268 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003269 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003270 if (T)
3271 return QualType(T, 0);
3272
Douglas Gregor789b1f62010-02-04 18:10:26 +00003273 QualType Canon = NamedType;
3274 if (!Canon.isCanonical()) {
3275 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003276 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3277 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00003278 (void)CheckT;
3279 }
3280
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003281 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003282 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003283 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003284 return QualType(T, 0);
3285}
3286
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003287QualType
Jay Foad4ba2a172011-01-12 09:06:06 +00003288ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003289 llvm::FoldingSetNodeID ID;
3290 ParenType::Profile(ID, InnerType);
3291
3292 void *InsertPos = 0;
3293 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3294 if (T)
3295 return QualType(T, 0);
3296
3297 QualType Canon = InnerType;
3298 if (!Canon.isCanonical()) {
3299 Canon = getCanonicalType(InnerType);
3300 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3301 assert(!CheckT && "Paren canonical type broken");
3302 (void)CheckT;
3303 }
3304
3305 T = new (*this) ParenType(InnerType, Canon);
3306 Types.push_back(T);
3307 ParenTypes.InsertNode(T, InsertPos);
3308 return QualType(T, 0);
3309}
3310
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003311QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3312 NestedNameSpecifier *NNS,
3313 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00003314 QualType Canon) const {
Douglas Gregord57959a2009-03-27 23:10:48 +00003315 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
3316
3317 if (Canon.isNull()) {
3318 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003319 ElaboratedTypeKeyword CanonKeyword = Keyword;
3320 if (Keyword == ETK_None)
3321 CanonKeyword = ETK_Typename;
3322
3323 if (CanonNNS != NNS || CanonKeyword != Keyword)
3324 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00003325 }
3326
3327 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003328 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00003329
3330 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00003331 DependentNameType *T
3332 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00003333 if (T)
3334 return QualType(T, 0);
3335
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003336 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00003337 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00003338 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00003339 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00003340}
3341
Mike Stump1eb44332009-09-09 15:08:12 +00003342QualType
John McCall33500952010-06-11 00:33:02 +00003343ASTContext::getDependentTemplateSpecializationType(
3344 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003345 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00003346 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00003347 const TemplateArgumentListInfo &Args) const {
John McCall33500952010-06-11 00:33:02 +00003348 // TODO: avoid this copy
Chris Lattner5f9e2722011-07-23 10:55:15 +00003349 SmallVector<TemplateArgument, 16> ArgCopy;
John McCall33500952010-06-11 00:33:02 +00003350 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3351 ArgCopy.push_back(Args[I].getArgument());
3352 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3353 ArgCopy.size(),
3354 ArgCopy.data());
3355}
3356
3357QualType
3358ASTContext::getDependentTemplateSpecializationType(
3359 ElaboratedTypeKeyword Keyword,
3360 NestedNameSpecifier *NNS,
3361 const IdentifierInfo *Name,
3362 unsigned NumArgs,
Jay Foad4ba2a172011-01-12 09:06:06 +00003363 const TemplateArgument *Args) const {
Douglas Gregoraa2187d2011-02-28 00:04:36 +00003364 assert((!NNS || NNS->isDependent()) &&
3365 "nested-name-specifier must be dependent");
Douglas Gregor17343172009-04-01 00:28:59 +00003366
Douglas Gregor789b1f62010-02-04 18:10:26 +00003367 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00003368 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3369 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003370
3371 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00003372 DependentTemplateSpecializationType *T
3373 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003374 if (T)
3375 return QualType(T, 0);
3376
John McCall33500952010-06-11 00:33:02 +00003377 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003378
John McCall33500952010-06-11 00:33:02 +00003379 ElaboratedTypeKeyword CanonKeyword = Keyword;
3380 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3381
3382 bool AnyNonCanonArgs = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003383 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCall33500952010-06-11 00:33:02 +00003384 for (unsigned I = 0; I != NumArgs; ++I) {
3385 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3386 if (!CanonArgs[I].structurallyEquals(Args[I]))
3387 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00003388 }
3389
John McCall33500952010-06-11 00:33:02 +00003390 QualType Canon;
3391 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3392 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3393 Name, NumArgs,
3394 CanonArgs.data());
3395
3396 // Find the insert position again.
3397 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3398 }
3399
3400 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3401 sizeof(TemplateArgument) * NumArgs),
3402 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00003403 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00003404 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00003405 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00003406 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00003407 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00003408}
3409
Douglas Gregorcded4f62011-01-14 17:04:44 +00003410QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikiedc84cd52013-02-20 22:23:23 +00003411 Optional<unsigned> NumExpansions) {
Douglas Gregor7536dd52010-12-20 02:24:11 +00003412 llvm::FoldingSetNodeID ID;
Douglas Gregorcded4f62011-01-14 17:04:44 +00003413 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003414
3415 assert(Pattern->containsUnexpandedParameterPack() &&
3416 "Pack expansions must expand one or more parameter packs");
3417 void *InsertPos = 0;
3418 PackExpansionType *T
3419 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3420 if (T)
3421 return QualType(T, 0);
3422
3423 QualType Canon;
3424 if (!Pattern.isCanonical()) {
Richard Smithd8672ef2012-07-16 00:20:35 +00003425 Canon = getCanonicalType(Pattern);
3426 // The canonical type might not contain an unexpanded parameter pack, if it
3427 // contains an alias template specialization which ignores one of its
3428 // parameters.
3429 if (Canon->containsUnexpandedParameterPack()) {
3430 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003431
Richard Smithd8672ef2012-07-16 00:20:35 +00003432 // Find the insert position again, in case we inserted an element into
3433 // PackExpansionTypes and invalidated our insert position.
3434 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3435 }
Douglas Gregor7536dd52010-12-20 02:24:11 +00003436 }
3437
Douglas Gregorcded4f62011-01-14 17:04:44 +00003438 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003439 Types.push_back(T);
3440 PackExpansionTypes.InsertNode(T, InsertPos);
3441 return QualType(T, 0);
3442}
3443
Chris Lattner88cb27a2008-04-07 04:56:42 +00003444/// CmpProtocolNames - Comparison predicate for sorting protocols
3445/// alphabetically.
3446static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3447 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003448 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00003449}
3450
John McCallc12c5bb2010-05-15 11:32:37 +00003451static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00003452 unsigned NumProtocols) {
3453 if (NumProtocols == 0) return true;
3454
Douglas Gregor61cc2962012-01-02 02:00:30 +00003455 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3456 return false;
3457
John McCall54e14c42009-10-22 22:37:11 +00003458 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregor61cc2962012-01-02 02:00:30 +00003459 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3460 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCall54e14c42009-10-22 22:37:11 +00003461 return false;
3462 return true;
3463}
3464
3465static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00003466 unsigned &NumProtocols) {
3467 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00003468
Chris Lattner88cb27a2008-04-07 04:56:42 +00003469 // Sort protocols, keyed by name.
3470 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3471
Douglas Gregor61cc2962012-01-02 02:00:30 +00003472 // Canonicalize.
3473 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3474 Protocols[I] = Protocols[I]->getCanonicalDecl();
3475
Chris Lattner88cb27a2008-04-07 04:56:42 +00003476 // Remove duplicates.
3477 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3478 NumProtocols = ProtocolsEnd-Protocols;
3479}
3480
John McCallc12c5bb2010-05-15 11:32:37 +00003481QualType ASTContext::getObjCObjectType(QualType BaseType,
3482 ObjCProtocolDecl * const *Protocols,
Jay Foad4ba2a172011-01-12 09:06:06 +00003483 unsigned NumProtocols) const {
John McCallc12c5bb2010-05-15 11:32:37 +00003484 // If the base type is an interface and there aren't any protocols
3485 // to add, then the interface type will do just fine.
3486 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3487 return BaseType;
3488
3489 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003490 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00003491 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003492 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00003493 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3494 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003495
John McCallc12c5bb2010-05-15 11:32:37 +00003496 // Build the canonical type, which has the canonical base type and
3497 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00003498 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00003499 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3500 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3501 if (!ProtocolsSorted) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003502 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer02379412010-04-27 17:12:11 +00003503 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00003504 unsigned UniqueCount = NumProtocols;
3505
John McCall54e14c42009-10-22 22:37:11 +00003506 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00003507 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3508 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00003509 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00003510 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3511 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00003512 }
3513
3514 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00003515 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3516 }
3517
3518 unsigned Size = sizeof(ObjCObjectTypeImpl);
3519 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3520 void *Mem = Allocate(Size, TypeAlignment);
3521 ObjCObjectTypeImpl *T =
3522 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3523
3524 Types.push_back(T);
3525 ObjCObjectTypes.InsertNode(T, InsertPos);
3526 return QualType(T, 0);
3527}
3528
3529/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3530/// the given object type.
Jay Foad4ba2a172011-01-12 09:06:06 +00003531QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCallc12c5bb2010-05-15 11:32:37 +00003532 llvm::FoldingSetNodeID ID;
3533 ObjCObjectPointerType::Profile(ID, ObjectT);
3534
3535 void *InsertPos = 0;
3536 if (ObjCObjectPointerType *QT =
3537 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3538 return QualType(QT, 0);
3539
3540 // Find the canonical object type.
3541 QualType Canonical;
3542 if (!ObjectT.isCanonical()) {
3543 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3544
3545 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00003546 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3547 }
3548
Douglas Gregorfd6a0882010-02-08 22:59:26 +00003549 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00003550 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3551 ObjCObjectPointerType *QType =
3552 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00003553
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003554 Types.push_back(QType);
3555 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00003556 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003557}
Chris Lattner88cb27a2008-04-07 04:56:42 +00003558
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003559/// getObjCInterfaceType - Return the unique reference to the type for the
3560/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregor0af55012011-12-16 03:12:41 +00003561QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3562 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003563 if (Decl->TypeForDecl)
3564 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00003565
Douglas Gregor0af55012011-12-16 03:12:41 +00003566 if (PrevDecl) {
3567 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3568 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3569 return QualType(PrevDecl->TypeForDecl, 0);
3570 }
3571
Douglas Gregor8d2dbbf2011-12-16 16:34:57 +00003572 // Prefer the definition, if there is one.
3573 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3574 Decl = Def;
3575
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003576 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3577 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3578 Decl->TypeForDecl = T;
3579 Types.push_back(T);
3580 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00003581}
3582
Douglas Gregor72564e72009-02-26 23:50:07 +00003583/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3584/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00003585/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00003586/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00003587/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00003588QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003589 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00003590 if (tofExpr->isTypeDependent()) {
3591 llvm::FoldingSetNodeID ID;
3592 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00003593
Douglas Gregorb1975722009-07-30 23:18:24 +00003594 void *InsertPos = 0;
3595 DependentTypeOfExprType *Canon
3596 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3597 if (Canon) {
3598 // We already have a "canonical" version of an identical, dependent
3599 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00003600 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00003601 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00003602 } else {
Douglas Gregorb1975722009-07-30 23:18:24 +00003603 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00003604 Canon
3605 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00003606 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3607 toe = Canon;
3608 }
3609 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003610 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00003611 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00003612 }
Steve Naroff9752f252007-08-01 18:02:17 +00003613 Types.push_back(toe);
3614 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00003615}
3616
Steve Naroff9752f252007-08-01 18:02:17 +00003617/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3618/// TypeOfType AST's. The only motivation to unique these nodes would be
3619/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00003620/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00003621/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00003622QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00003623 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00003624 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00003625 Types.push_back(tot);
3626 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00003627}
3628
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00003629
Anders Carlsson395b4752009-06-24 19:06:50 +00003630/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3631/// DecltypeType AST's. The only motivation to unique these nodes would be
3632/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00003633/// an issue. This doesn't effect the type checker, since it operates
David Blaikie39e02032011-11-06 22:28:03 +00003634/// on canonical types (which are always unique).
Douglas Gregorf8af9822012-02-12 18:42:33 +00003635QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003636 DecltypeType *dt;
Douglas Gregor561f8122011-07-01 01:22:09 +00003637
3638 // C++0x [temp.type]p2:
3639 // If an expression e involves a template parameter, decltype(e) denotes a
3640 // unique dependent type. Two such decltype-specifiers refer to the same
3641 // type only if their expressions are equivalent (14.5.6.1).
3642 if (e->isInstantiationDependent()) {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003643 llvm::FoldingSetNodeID ID;
3644 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00003645
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003646 void *InsertPos = 0;
3647 DependentDecltypeType *Canon
3648 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3649 if (Canon) {
3650 // We already have a "canonical" version of an equivalent, dependent
3651 // decltype type. Use that as our canonical type.
Richard Smith0d729102012-08-13 20:08:14 +00003652 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003653 QualType((DecltypeType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00003654 } else {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003655 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00003656 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003657 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3658 dt = Canon;
3659 }
3660 } else {
Douglas Gregorf8af9822012-02-12 18:42:33 +00003661 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3662 getCanonicalType(UnderlyingType));
Douglas Gregordd0257c2009-07-08 00:03:05 +00003663 }
Anders Carlsson395b4752009-06-24 19:06:50 +00003664 Types.push_back(dt);
3665 return QualType(dt, 0);
3666}
3667
Sean Huntca63c202011-05-24 22:41:36 +00003668/// getUnaryTransformationType - We don't unique these, since the memory
3669/// savings are minimal and these are rare.
3670QualType ASTContext::getUnaryTransformType(QualType BaseType,
3671 QualType UnderlyingType,
3672 UnaryTransformType::UTTKind Kind)
3673 const {
3674 UnaryTransformType *Ty =
Douglas Gregor69d97752011-05-25 17:51:54 +00003675 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3676 Kind,
3677 UnderlyingType->isDependentType() ?
Peter Collingbourne12fc4b02012-03-05 16:02:06 +00003678 QualType() : getCanonicalType(UnderlyingType));
Sean Huntca63c202011-05-24 22:41:36 +00003679 Types.push_back(Ty);
3680 return QualType(Ty, 0);
3681}
3682
Richard Smith60e141e2013-05-04 07:00:32 +00003683/// getAutoType - Return the uniqued reference to the 'auto' type which has been
3684/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3685/// canonical deduced-but-dependent 'auto' type.
3686QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
Richard Smithdc7a4f52013-04-30 13:56:41 +00003687 bool IsDependent) const {
Richard Smith60e141e2013-05-04 07:00:32 +00003688 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
3689 return getAutoDeductType();
3690
3691 // Look in the folding set for an existing type.
Richard Smith483b9f32011-02-21 20:05:19 +00003692 void *InsertPos = 0;
Richard Smith60e141e2013-05-04 07:00:32 +00003693 llvm::FoldingSetNodeID ID;
3694 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
3695 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3696 return QualType(AT, 0);
Richard Smith483b9f32011-02-21 20:05:19 +00003697
Richard Smitha2c36462013-04-26 16:15:35 +00003698 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smithdc7a4f52013-04-30 13:56:41 +00003699 IsDecltypeAuto,
3700 IsDependent);
Richard Smith483b9f32011-02-21 20:05:19 +00003701 Types.push_back(AT);
3702 if (InsertPos)
3703 AutoTypes.InsertNode(AT, InsertPos);
3704 return QualType(AT, 0);
Richard Smith34b41d92011-02-20 03:19:35 +00003705}
3706
Eli Friedmanb001de72011-10-06 23:00:33 +00003707/// getAtomicType - Return the uniqued reference to the atomic type for
3708/// the given value type.
3709QualType ASTContext::getAtomicType(QualType T) const {
3710 // Unique pointers, to guarantee there is only one pointer of a particular
3711 // structure.
3712 llvm::FoldingSetNodeID ID;
3713 AtomicType::Profile(ID, T);
3714
3715 void *InsertPos = 0;
3716 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3717 return QualType(AT, 0);
3718
3719 // If the atomic value type isn't canonical, this won't be a canonical type
3720 // either, so fill in the canonical type field.
3721 QualType Canonical;
3722 if (!T.isCanonical()) {
3723 Canonical = getAtomicType(getCanonicalType(T));
3724
3725 // Get the new insert position for the node we care about.
3726 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3727 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3728 }
3729 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3730 Types.push_back(New);
3731 AtomicTypes.InsertNode(New, InsertPos);
3732 return QualType(New, 0);
3733}
3734
Richard Smithad762fc2011-04-14 22:09:26 +00003735/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3736QualType ASTContext::getAutoDeductType() const {
3737 if (AutoDeductTy.isNull())
Richard Smith60e141e2013-05-04 07:00:32 +00003738 AutoDeductTy = QualType(
3739 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
3740 /*dependent*/false),
3741 0);
Richard Smithad762fc2011-04-14 22:09:26 +00003742 return AutoDeductTy;
3743}
3744
3745/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3746QualType ASTContext::getAutoRRefDeductType() const {
3747 if (AutoRRefDeductTy.isNull())
3748 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3749 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3750 return AutoRRefDeductTy;
3751}
3752
Reid Spencer5f016e22007-07-11 17:01:13 +00003753/// getTagDeclType - Return the unique reference to the type for the
3754/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad4ba2a172011-01-12 09:06:06 +00003755QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenekd778f882007-11-26 21:16:01 +00003756 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00003757 // FIXME: What is the design on getTagDeclType when it requires casting
3758 // away const? mutable?
3759 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003760}
3761
Mike Stump1eb44332009-09-09 15:08:12 +00003762/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3763/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3764/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00003765CanQualType ASTContext::getSizeType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003766 return getFromTargetType(Target->getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00003767}
3768
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003769/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3770CanQualType ASTContext::getIntMaxType() const {
3771 return getFromTargetType(Target->getIntMaxType());
3772}
3773
3774/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3775CanQualType ASTContext::getUIntMaxType() const {
3776 return getFromTargetType(Target->getUIntMaxType());
3777}
3778
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00003779/// getSignedWCharType - Return the type of "signed wchar_t".
3780/// Used when in C++, as a GCC extension.
3781QualType ASTContext::getSignedWCharType() const {
3782 // FIXME: derive from "Target" ?
3783 return WCharTy;
3784}
3785
3786/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3787/// Used when in C++, as a GCC extension.
3788QualType ASTContext::getUnsignedWCharType() const {
3789 // FIXME: derive from "Target" ?
3790 return UnsignedIntTy;
3791}
3792
Enea Zaffanella9677eb82013-01-26 17:08:37 +00003793QualType ASTContext::getIntPtrType() const {
3794 return getFromTargetType(Target->getIntPtrType());
3795}
3796
3797QualType ASTContext::getUIntPtrType() const {
3798 return getCorrespondingUnsignedType(getIntPtrType());
3799}
3800
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003801/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattner8b9023b2007-07-13 03:05:23 +00003802/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3803QualType ASTContext::getPointerDiffType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003804 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00003805}
3806
Eli Friedman6902e412012-11-27 02:58:24 +00003807/// \brief Return the unique type for "pid_t" defined in
3808/// <sys/types.h>. We need this to compute the correct type for vfork().
3809QualType ASTContext::getProcessIDType() const {
3810 return getFromTargetType(Target->getProcessIDType());
3811}
3812
Chris Lattnere6327742008-04-02 05:18:44 +00003813//===----------------------------------------------------------------------===//
3814// Type Operators
3815//===----------------------------------------------------------------------===//
3816
Jay Foad4ba2a172011-01-12 09:06:06 +00003817CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCall54e14c42009-10-22 22:37:11 +00003818 // Push qualifiers into arrays, and then discard any remaining
3819 // qualifiers.
3820 T = getCanonicalType(T);
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003821 T = getVariableArrayDecayedType(T);
John McCall54e14c42009-10-22 22:37:11 +00003822 const Type *Ty = T.getTypePtr();
John McCall54e14c42009-10-22 22:37:11 +00003823 QualType Result;
3824 if (isa<ArrayType>(Ty)) {
3825 Result = getArrayDecayedType(QualType(Ty,0));
3826 } else if (isa<FunctionType>(Ty)) {
3827 Result = getPointerType(QualType(Ty, 0));
3828 } else {
3829 Result = QualType(Ty, 0);
3830 }
3831
3832 return CanQualType::CreateUnsafe(Result);
3833}
3834
John McCall62c28c82011-01-18 07:41:22 +00003835QualType ASTContext::getUnqualifiedArrayType(QualType type,
3836 Qualifiers &quals) {
3837 SplitQualType splitType = type.getSplitUnqualifiedType();
3838
3839 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3840 // the unqualified desugared type and then drops it on the floor.
3841 // We then have to strip that sugar back off with
3842 // getUnqualifiedDesugaredType(), which is silly.
3843 const ArrayType *AT =
John McCall200fa532012-02-08 00:46:36 +00003844 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall62c28c82011-01-18 07:41:22 +00003845
3846 // If we don't have an array, just use the results in splitType.
Douglas Gregor9dadd942010-05-17 18:45:21 +00003847 if (!AT) {
John McCall200fa532012-02-08 00:46:36 +00003848 quals = splitType.Quals;
3849 return QualType(splitType.Ty, 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003850 }
3851
John McCall62c28c82011-01-18 07:41:22 +00003852 // Otherwise, recurse on the array's element type.
3853 QualType elementType = AT->getElementType();
3854 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3855
3856 // If that didn't change the element type, AT has no qualifiers, so we
3857 // can just use the results in splitType.
3858 if (elementType == unqualElementType) {
3859 assert(quals.empty()); // from the recursive call
John McCall200fa532012-02-08 00:46:36 +00003860 quals = splitType.Quals;
3861 return QualType(splitType.Ty, 0);
John McCall62c28c82011-01-18 07:41:22 +00003862 }
3863
3864 // Otherwise, add in the qualifiers from the outermost type, then
3865 // build the type back up.
John McCall200fa532012-02-08 00:46:36 +00003866 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003867
Douglas Gregor9dadd942010-05-17 18:45:21 +00003868 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003869 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003870 CAT->getSizeModifier(), 0);
3871 }
3872
Douglas Gregor9dadd942010-05-17 18:45:21 +00003873 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003874 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003875 }
3876
Douglas Gregor9dadd942010-05-17 18:45:21 +00003877 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003878 return getVariableArrayType(unqualElementType,
John McCall3fa5cae2010-10-26 07:05:15 +00003879 VAT->getSizeExpr(),
Douglas Gregor9dadd942010-05-17 18:45:21 +00003880 VAT->getSizeModifier(),
3881 VAT->getIndexTypeCVRQualifiers(),
3882 VAT->getBracketsRange());
3883 }
3884
3885 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall62c28c82011-01-18 07:41:22 +00003886 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003887 DSAT->getSizeModifier(), 0,
3888 SourceRange());
3889}
3890
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003891/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3892/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3893/// they point to and return true. If T1 and T2 aren't pointer types
3894/// or pointer-to-member types, or if they are not similar at this
3895/// level, returns false and leaves T1 and T2 unchanged. Top-level
3896/// qualifiers on T1 and T2 are ignored. This function will typically
3897/// be called in a loop that successively "unwraps" pointer and
3898/// pointer-to-member types to compare them at each level.
3899bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3900 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3901 *T2PtrType = T2->getAs<PointerType>();
3902 if (T1PtrType && T2PtrType) {
3903 T1 = T1PtrType->getPointeeType();
3904 T2 = T2PtrType->getPointeeType();
3905 return true;
3906 }
3907
3908 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3909 *T2MPType = T2->getAs<MemberPointerType>();
3910 if (T1MPType && T2MPType &&
3911 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3912 QualType(T2MPType->getClass(), 0))) {
3913 T1 = T1MPType->getPointeeType();
3914 T2 = T2MPType->getPointeeType();
3915 return true;
3916 }
3917
David Blaikie4e4d0842012-03-11 07:00:24 +00003918 if (getLangOpts().ObjC1) {
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003919 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3920 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3921 if (T1OPType && T2OPType) {
3922 T1 = T1OPType->getPointeeType();
3923 T2 = T2OPType->getPointeeType();
3924 return true;
3925 }
3926 }
3927
3928 // FIXME: Block pointers, too?
3929
3930 return false;
3931}
3932
Jay Foad4ba2a172011-01-12 09:06:06 +00003933DeclarationNameInfo
3934ASTContext::getNameForTemplate(TemplateName Name,
3935 SourceLocation NameLoc) const {
John McCall14606042011-06-30 08:33:18 +00003936 switch (Name.getKind()) {
3937 case TemplateName::QualifiedTemplate:
3938 case TemplateName::Template:
Abramo Bagnara25777432010-08-11 22:01:17 +00003939 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCall14606042011-06-30 08:33:18 +00003940 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3941 NameLoc);
Abramo Bagnara25777432010-08-11 22:01:17 +00003942
John McCall14606042011-06-30 08:33:18 +00003943 case TemplateName::OverloadedTemplate: {
3944 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3945 // DNInfo work in progress: CHECKME: what about DNLoc?
3946 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3947 }
3948
3949 case TemplateName::DependentTemplate: {
3950 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnara25777432010-08-11 22:01:17 +00003951 DeclarationName DName;
John McCall80ad16f2009-11-24 18:42:40 +00003952 if (DTN->isIdentifier()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00003953 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3954 return DeclarationNameInfo(DName, NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003955 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00003956 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3957 // DNInfo work in progress: FIXME: source locations?
3958 DeclarationNameLoc DNLoc;
3959 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3960 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3961 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003962 }
3963 }
3964
John McCall14606042011-06-30 08:33:18 +00003965 case TemplateName::SubstTemplateTemplateParm: {
3966 SubstTemplateTemplateParmStorage *subst
3967 = Name.getAsSubstTemplateTemplateParm();
3968 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3969 NameLoc);
3970 }
3971
3972 case TemplateName::SubstTemplateTemplateParmPack: {
3973 SubstTemplateTemplateParmPackStorage *subst
3974 = Name.getAsSubstTemplateTemplateParmPack();
3975 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3976 NameLoc);
3977 }
3978 }
3979
3980 llvm_unreachable("bad template name kind!");
John McCall80ad16f2009-11-24 18:42:40 +00003981}
3982
Jay Foad4ba2a172011-01-12 09:06:06 +00003983TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCall14606042011-06-30 08:33:18 +00003984 switch (Name.getKind()) {
3985 case TemplateName::QualifiedTemplate:
3986 case TemplateName::Template: {
3987 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003988 if (TemplateTemplateParmDecl *TTP
John McCall14606042011-06-30 08:33:18 +00003989 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003990 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3991
3992 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00003993 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003994 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003995
John McCall14606042011-06-30 08:33:18 +00003996 case TemplateName::OverloadedTemplate:
3997 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump1eb44332009-09-09 15:08:12 +00003998
John McCall14606042011-06-30 08:33:18 +00003999 case TemplateName::DependentTemplate: {
4000 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4001 assert(DTN && "Non-dependent template names must refer to template decls.");
4002 return DTN->CanonicalTemplateName;
4003 }
4004
4005 case TemplateName::SubstTemplateTemplateParm: {
4006 SubstTemplateTemplateParmStorage *subst
4007 = Name.getAsSubstTemplateTemplateParm();
4008 return getCanonicalTemplateName(subst->getReplacement());
4009 }
4010
4011 case TemplateName::SubstTemplateTemplateParmPack: {
4012 SubstTemplateTemplateParmPackStorage *subst
4013 = Name.getAsSubstTemplateTemplateParmPack();
4014 TemplateTemplateParmDecl *canonParameter
4015 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4016 TemplateArgument canonArgPack
4017 = getCanonicalTemplateArgument(subst->getArgumentPack());
4018 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4019 }
4020 }
4021
4022 llvm_unreachable("bad template name!");
Douglas Gregor25a3ef72009-05-07 06:41:52 +00004023}
4024
Douglas Gregordb0d4b72009-11-11 23:06:43 +00004025bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4026 X = getCanonicalTemplateName(X);
4027 Y = getCanonicalTemplateName(Y);
4028 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4029}
4030
Mike Stump1eb44332009-09-09 15:08:12 +00004031TemplateArgument
Jay Foad4ba2a172011-01-12 09:06:06 +00004032ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregor1275ae02009-07-28 23:00:59 +00004033 switch (Arg.getKind()) {
4034 case TemplateArgument::Null:
4035 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00004036
Douglas Gregor1275ae02009-07-28 23:00:59 +00004037 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00004038 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00004039
Douglas Gregord2008e22012-04-06 22:40:38 +00004040 case TemplateArgument::Declaration: {
Eli Friedmand7a6b162012-09-26 02:36:12 +00004041 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
4042 return TemplateArgument(D, Arg.isDeclForReferenceParam());
Douglas Gregord2008e22012-04-06 22:40:38 +00004043 }
Mike Stump1eb44332009-09-09 15:08:12 +00004044
Eli Friedmand7a6b162012-09-26 02:36:12 +00004045 case TemplateArgument::NullPtr:
4046 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4047 /*isNullPtr*/true);
4048
Douglas Gregor788cd062009-11-11 01:00:40 +00004049 case TemplateArgument::Template:
4050 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregora7fc9012011-01-05 18:58:31 +00004051
4052 case TemplateArgument::TemplateExpansion:
4053 return TemplateArgument(getCanonicalTemplateName(
4054 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregor2be29f42011-01-14 23:41:42 +00004055 Arg.getNumTemplateExpansions());
Douglas Gregora7fc9012011-01-05 18:58:31 +00004056
Douglas Gregor1275ae02009-07-28 23:00:59 +00004057 case TemplateArgument::Integral:
Benjamin Kramer85524372012-06-07 15:09:51 +00004058 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00004059
Douglas Gregor1275ae02009-07-28 23:00:59 +00004060 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00004061 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00004062
Douglas Gregor1275ae02009-07-28 23:00:59 +00004063 case TemplateArgument::Pack: {
Douglas Gregor87dd6972010-12-20 16:52:59 +00004064 if (Arg.pack_size() == 0)
4065 return Arg;
4066
Douglas Gregor910f8002010-11-07 23:05:16 +00004067 TemplateArgument *CanonArgs
4068 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregor1275ae02009-07-28 23:00:59 +00004069 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004070 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00004071 AEnd = Arg.pack_end();
4072 A != AEnd; (void)++A, ++Idx)
4073 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00004074
Douglas Gregor910f8002010-11-07 23:05:16 +00004075 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregor1275ae02009-07-28 23:00:59 +00004076 }
4077 }
4078
4079 // Silence GCC warning
David Blaikieb219cfc2011-09-23 05:06:16 +00004080 llvm_unreachable("Unhandled template argument kind");
Douglas Gregor1275ae02009-07-28 23:00:59 +00004081}
4082
Douglas Gregord57959a2009-03-27 23:10:48 +00004083NestedNameSpecifier *
Jay Foad4ba2a172011-01-12 09:06:06 +00004084ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump1eb44332009-09-09 15:08:12 +00004085 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00004086 return 0;
4087
4088 switch (NNS->getKind()) {
4089 case NestedNameSpecifier::Identifier:
4090 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00004091 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00004092 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4093 NNS->getAsIdentifier());
4094
4095 case NestedNameSpecifier::Namespace:
4096 // A namespace is canonical; build a nested-name-specifier with
4097 // this namespace and no prefix.
Douglas Gregor14aba762011-02-24 02:36:08 +00004098 return NestedNameSpecifier::Create(*this, 0,
4099 NNS->getAsNamespace()->getOriginalNamespace());
4100
4101 case NestedNameSpecifier::NamespaceAlias:
4102 // A namespace is canonical; build a nested-name-specifier with
4103 // this namespace and no prefix.
4104 return NestedNameSpecifier::Create(*this, 0,
4105 NNS->getAsNamespaceAlias()->getNamespace()
4106 ->getOriginalNamespace());
Douglas Gregord57959a2009-03-27 23:10:48 +00004107
4108 case NestedNameSpecifier::TypeSpec:
4109 case NestedNameSpecifier::TypeSpecWithTemplate: {
4110 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor264bf662010-11-04 00:09:33 +00004111
4112 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4113 // break it apart into its prefix and identifier, then reconsititute those
4114 // as the canonical nested-name-specifier. This is required to canonicalize
4115 // a dependent nested-name-specifier involving typedefs of dependent-name
4116 // types, e.g.,
4117 // typedef typename T::type T1;
4118 // typedef typename T1::type T2;
Eli Friedman16412ef2012-03-03 04:09:56 +00004119 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4120 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor264bf662010-11-04 00:09:33 +00004121 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor264bf662010-11-04 00:09:33 +00004122
Eli Friedman16412ef2012-03-03 04:09:56 +00004123 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4124 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4125 // first place?
John McCall3b657512011-01-19 10:06:00 +00004126 return NestedNameSpecifier::Create(*this, 0, false,
4127 const_cast<Type*>(T.getTypePtr()));
Douglas Gregord57959a2009-03-27 23:10:48 +00004128 }
4129
4130 case NestedNameSpecifier::Global:
4131 // The global specifier is canonical and unique.
4132 return NNS;
4133 }
4134
David Blaikie7530c032012-01-17 06:56:22 +00004135 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregord57959a2009-03-27 23:10:48 +00004136}
4137
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004138
Jay Foad4ba2a172011-01-12 09:06:06 +00004139const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004140 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004141 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004142 // Handle the common positive case fast.
4143 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4144 return AT;
4145 }
Mike Stump1eb44332009-09-09 15:08:12 +00004146
John McCall0953e762009-09-24 19:53:00 +00004147 // Handle the common negative case fast.
John McCall3b657512011-01-19 10:06:00 +00004148 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004149 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004150
John McCall0953e762009-09-24 19:53:00 +00004151 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004152 // implements C99 6.7.3p8: "If the specification of an array type includes
4153 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00004154
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004155 // If we get here, we either have type qualifiers on the type, or we have
4156 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00004157 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00004158
John McCall3b657512011-01-19 10:06:00 +00004159 SplitQualType split = T.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00004160 Qualifiers qs = split.Quals;
Mike Stump1eb44332009-09-09 15:08:12 +00004161
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004162 // If we have a simple case, just return now.
John McCall200fa532012-02-08 00:46:36 +00004163 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall3b657512011-01-19 10:06:00 +00004164 if (ATy == 0 || qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004165 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00004166
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004167 // Otherwise, we have an array and we have qualifiers on it. Push the
4168 // qualifiers into the array element type and return a new array type.
John McCall3b657512011-01-19 10:06:00 +00004169 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump1eb44332009-09-09 15:08:12 +00004170
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004171 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4172 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4173 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004174 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004175 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4176 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4177 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004178 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00004179
Mike Stump1eb44332009-09-09 15:08:12 +00004180 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00004181 = dyn_cast<DependentSizedArrayType>(ATy))
4182 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00004183 getDependentSizedArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00004184 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00004185 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004186 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004187 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00004188
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004189 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004190 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00004191 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004192 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004193 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004194 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00004195}
4196
Abramo Bagnaraad9689f2012-05-17 12:44:05 +00004197QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner12df2462013-06-24 17:51:48 +00004198 if (T->isArrayType() || T->isFunctionType())
4199 return getDecayedType(T);
4200 return T;
Douglas Gregor79e6bd32011-07-12 04:42:08 +00004201}
4202
Abramo Bagnaraad9689f2012-05-17 12:44:05 +00004203QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor79e6bd32011-07-12 04:42:08 +00004204 T = getVariableArrayDecayedType(T);
4205 T = getAdjustedParameterType(T);
4206 return T.getUnqualifiedType();
4207}
4208
Chris Lattnere6327742008-04-02 05:18:44 +00004209/// getArrayDecayedType - Return the properly qualified result of decaying the
4210/// specified array type to a pointer. This operation is non-trivial when
4211/// handling typedefs etc. The canonical type of "T" must be an array type,
4212/// this returns a pointer to a properly qualified element of the array.
4213///
4214/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad4ba2a172011-01-12 09:06:06 +00004215QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004216 // Get the element type with 'getAsArrayType' so that we don't lose any
4217 // typedefs in the element type of the array. This also handles propagation
4218 // of type qualifiers from the array type into the element type if present
4219 // (C99 6.7.3p8).
4220 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4221 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00004222
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004223 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00004224
4225 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00004226 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00004227}
4228
John McCall3b657512011-01-19 10:06:00 +00004229QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4230 return getBaseElementType(array->getElementType());
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00004231}
4232
John McCall3b657512011-01-19 10:06:00 +00004233QualType ASTContext::getBaseElementType(QualType type) const {
4234 Qualifiers qs;
4235 while (true) {
4236 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00004237 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall3b657512011-01-19 10:06:00 +00004238 if (!array) break;
Mike Stump1eb44332009-09-09 15:08:12 +00004239
John McCall3b657512011-01-19 10:06:00 +00004240 type = array->getElementType();
John McCall200fa532012-02-08 00:46:36 +00004241 qs.addConsistentQualifiers(split.Quals);
John McCall3b657512011-01-19 10:06:00 +00004242 }
Mike Stump1eb44332009-09-09 15:08:12 +00004243
John McCall3b657512011-01-19 10:06:00 +00004244 return getQualifiedType(type, qs);
Anders Carlsson6183a992008-12-21 03:44:36 +00004245}
4246
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004247/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00004248uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004249ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4250 uint64_t ElementCount = 1;
4251 do {
4252 ElementCount *= CA->getSize().getZExtValue();
Richard Smithd5e83942012-12-06 03:04:50 +00004253 CA = dyn_cast_or_null<ConstantArrayType>(
4254 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004255 } while (CA);
4256 return ElementCount;
4257}
4258
Reid Spencer5f016e22007-07-11 17:01:13 +00004259/// getFloatingRank - Return a relative rank for floating point types.
4260/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00004261static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00004262 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00004263 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00004264
John McCall183700f2009-09-21 23:43:11 +00004265 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4266 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004267 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00004268 case BuiltinType::Half: return HalfRank;
Reid Spencer5f016e22007-07-11 17:01:13 +00004269 case BuiltinType::Float: return FloatRank;
4270 case BuiltinType::Double: return DoubleRank;
4271 case BuiltinType::LongDouble: return LongDoubleRank;
4272 }
4273}
4274
Mike Stump1eb44332009-09-09 15:08:12 +00004275/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4276/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00004277/// 'typeDomain' is a real floating point or complex type.
4278/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00004279QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4280 QualType Domain) const {
4281 FloatingRank EltRank = getFloatingRank(Size);
4282 if (Domain->isComplexType()) {
4283 switch (EltRank) {
David Blaikie561d3ab2012-01-17 02:30:50 +00004284 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Narofff1448a02007-08-27 01:27:54 +00004285 case FloatRank: return FloatComplexTy;
4286 case DoubleRank: return DoubleComplexTy;
4287 case LongDoubleRank: return LongDoubleComplexTy;
4288 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004289 }
Chris Lattner1361b112008-04-06 23:58:54 +00004290
4291 assert(Domain->isRealFloatingType() && "Unknown domain!");
4292 switch (EltRank) {
Joey Gouly19dbb202013-01-23 11:56:20 +00004293 case HalfRank: return HalfTy;
Chris Lattner1361b112008-04-06 23:58:54 +00004294 case FloatRank: return FloatTy;
4295 case DoubleRank: return DoubleTy;
4296 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00004297 }
David Blaikie561d3ab2012-01-17 02:30:50 +00004298 llvm_unreachable("getFloatingRank(): illegal value for rank");
Reid Spencer5f016e22007-07-11 17:01:13 +00004299}
4300
Chris Lattner7cfeb082008-04-06 23:55:33 +00004301/// getFloatingTypeOrder - Compare the rank of the two specified floating
4302/// point types, ignoring the domain of the type (i.e. 'double' ==
4303/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00004304/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00004305int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnera75cea32008-04-06 23:38:49 +00004306 FloatingRank LHSR = getFloatingRank(LHS);
4307 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004308
Chris Lattnera75cea32008-04-06 23:38:49 +00004309 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00004310 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00004311 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00004312 return 1;
4313 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00004314}
4315
Chris Lattnerf52ab252008-04-06 22:59:24 +00004316/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4317/// routine will assert if passed a built-in type that isn't an integer or enum,
4318/// or if it is not canonicalized.
John McCallf4c73712011-01-19 06:33:43 +00004319unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCall467b27b2009-10-22 20:10:53 +00004320 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00004321
Chris Lattnerf52ab252008-04-06 22:59:24 +00004322 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004323 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattner7cfeb082008-04-06 23:55:33 +00004324 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004325 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004326 case BuiltinType::Char_S:
4327 case BuiltinType::Char_U:
4328 case BuiltinType::SChar:
4329 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004330 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004331 case BuiltinType::Short:
4332 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004333 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004334 case BuiltinType::Int:
4335 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004336 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004337 case BuiltinType::Long:
4338 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004339 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004340 case BuiltinType::LongLong:
4341 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004342 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00004343 case BuiltinType::Int128:
4344 case BuiltinType::UInt128:
4345 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00004346 }
4347}
4348
Eli Friedman04e83572009-08-20 04:21:42 +00004349/// \brief Whether this is a promotable bitfield reference according
4350/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4351///
4352/// \returns the type this bit-field will promote to, or NULL if no
4353/// promotion occurs.
Jay Foad4ba2a172011-01-12 09:06:06 +00004354QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregorceafbde2010-05-24 20:13:53 +00004355 if (E->isTypeDependent() || E->isValueDependent())
4356 return QualType();
4357
John McCall993f43f2013-05-06 21:39:12 +00004358 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman04e83572009-08-20 04:21:42 +00004359 if (!Field)
4360 return QualType();
4361
4362 QualType FT = Field->getType();
4363
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004364 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman04e83572009-08-20 04:21:42 +00004365 uint64_t IntSize = getTypeSize(IntTy);
4366 // GCC extension compatibility: if the bit-field size is less than or equal
4367 // to the size of int, it gets promoted no matter what its type is.
4368 // For instance, unsigned long bf : 4 gets promoted to signed int.
4369 if (BitWidth < IntSize)
4370 return IntTy;
4371
4372 if (BitWidth == IntSize)
4373 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4374
4375 // Types bigger than int are not subject to promotions, and therefore act
4376 // like the base type.
4377 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4378 // is ridiculous.
4379 return QualType();
4380}
4381
Eli Friedmana95d7572009-08-19 07:44:53 +00004382/// getPromotedIntegerType - Returns the type that Promotable will
4383/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4384/// integer type.
Jay Foad4ba2a172011-01-12 09:06:06 +00004385QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedmana95d7572009-08-19 07:44:53 +00004386 assert(!Promotable.isNull());
4387 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00004388 if (const EnumType *ET = Promotable->getAs<EnumType>())
4389 return ET->getDecl()->getPromotionType();
Eli Friedman68a2dc42011-10-26 07:22:48 +00004390
4391 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4392 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4393 // (3.9.1) can be converted to a prvalue of the first of the following
4394 // types that can represent all the values of its underlying type:
4395 // int, unsigned int, long int, unsigned long int, long long int, or
4396 // unsigned long long int [...]
4397 // FIXME: Is there some better way to compute this?
4398 if (BT->getKind() == BuiltinType::WChar_S ||
4399 BT->getKind() == BuiltinType::WChar_U ||
4400 BT->getKind() == BuiltinType::Char16 ||
4401 BT->getKind() == BuiltinType::Char32) {
4402 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4403 uint64_t FromSize = getTypeSize(BT);
4404 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4405 LongLongTy, UnsignedLongLongTy };
4406 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4407 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4408 if (FromSize < ToSize ||
4409 (FromSize == ToSize &&
4410 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4411 return PromoteTypes[Idx];
4412 }
4413 llvm_unreachable("char type should fit into long long");
4414 }
4415 }
4416
4417 // At this point, we should have a signed or unsigned integer type.
Eli Friedmana95d7572009-08-19 07:44:53 +00004418 if (Promotable->isSignedIntegerType())
4419 return IntTy;
Eli Friedman5b64e772012-11-15 01:21:59 +00004420 uint64_t PromotableSize = getIntWidth(Promotable);
4421 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedmana95d7572009-08-19 07:44:53 +00004422 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4423 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4424}
4425
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00004426/// \brief Recurses in pointer/array types until it finds an objc retainable
4427/// type and returns its ownership.
4428Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4429 while (!T.isNull()) {
4430 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4431 return T.getObjCLifetime();
4432 if (T->isArrayType())
4433 T = getBaseElementType(T);
4434 else if (const PointerType *PT = T->getAs<PointerType>())
4435 T = PT->getPointeeType();
4436 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis28445f02011-07-01 23:01:46 +00004437 T = RT->getPointeeType();
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00004438 else
4439 break;
4440 }
4441
4442 return Qualifiers::OCL_None;
4443}
4444
Mike Stump1eb44332009-09-09 15:08:12 +00004445/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00004446/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00004447/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00004448int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCallf4c73712011-01-19 06:33:43 +00004449 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4450 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00004451 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004452
Chris Lattnerf52ab252008-04-06 22:59:24 +00004453 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4454 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00004455
Chris Lattner7cfeb082008-04-06 23:55:33 +00004456 unsigned LHSRank = getIntegerRank(LHSC);
4457 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00004458
Chris Lattner7cfeb082008-04-06 23:55:33 +00004459 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4460 if (LHSRank == RHSRank) return 0;
4461 return LHSRank > RHSRank ? 1 : -1;
4462 }
Mike Stump1eb44332009-09-09 15:08:12 +00004463
Chris Lattner7cfeb082008-04-06 23:55:33 +00004464 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4465 if (LHSUnsigned) {
4466 // If the unsigned [LHS] type is larger, return it.
4467 if (LHSRank >= RHSRank)
4468 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004469
Chris Lattner7cfeb082008-04-06 23:55:33 +00004470 // If the signed type can represent all values of the unsigned type, it
4471 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00004472 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00004473 return -1;
4474 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00004475
Chris Lattner7cfeb082008-04-06 23:55:33 +00004476 // If the unsigned [RHS] type is larger, return it.
4477 if (RHSRank >= LHSRank)
4478 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00004479
Chris Lattner7cfeb082008-04-06 23:55:33 +00004480 // If the signed type can represent all values of the unsigned type, it
4481 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00004482 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00004483 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00004484}
Anders Carlsson71993dd2007-08-17 05:31:46 +00004485
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004486static RecordDecl *
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004487CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
4488 DeclContext *DC, IdentifierInfo *Id) {
4489 SourceLocation Loc;
David Blaikie4e4d0842012-03-11 07:00:24 +00004490 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004491 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004492 else
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004493 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004494}
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004495
Mike Stump1eb44332009-09-09 15:08:12 +00004496// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00004497QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson71993dd2007-08-17 05:31:46 +00004498 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00004499 CFConstantStringTypeDecl =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004500 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004501 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00004502 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004503
Anders Carlssonf06273f2007-11-19 00:25:30 +00004504 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00004505
Anders Carlsson71993dd2007-08-17 05:31:46 +00004506 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00004507 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00004508 // int flags;
4509 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00004510 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00004511 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00004512 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00004513 FieldTypes[3] = LongTy;
4514
Anders Carlsson71993dd2007-08-17 05:31:46 +00004515 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00004516 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00004517 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004518 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00004519 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00004520 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00004521 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004522 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004523 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004524 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004525 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00004526 }
4527
Douglas Gregor838db382010-02-11 01:19:42 +00004528 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00004529 }
Mike Stump1eb44332009-09-09 15:08:12 +00004530
Anders Carlsson71993dd2007-08-17 05:31:46 +00004531 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00004532}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004533
Fariborz Jahanianf7992132013-01-04 18:45:40 +00004534QualType ASTContext::getObjCSuperType() const {
4535 if (ObjCSuperType.isNull()) {
4536 RecordDecl *ObjCSuperTypeDecl =
4537 CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get("objc_super"));
4538 TUDecl->addDecl(ObjCSuperTypeDecl);
4539 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4540 }
4541 return ObjCSuperType;
4542}
4543
Douglas Gregor319ac892009-04-23 22:29:11 +00004544void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004545 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00004546 assert(Rec && "Invalid CFConstantStringType");
4547 CFConstantStringTypeDecl = Rec->getDecl();
4548}
4549
Jay Foad4ba2a172011-01-12 09:06:06 +00004550QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpadaaad32009-10-20 02:12:22 +00004551 if (BlockDescriptorType)
4552 return getTagDeclType(BlockDescriptorType);
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"));
John McCall5cfa0112010-02-05 01:33:36 +00004558 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00004559
4560 QualType FieldTypes[] = {
4561 UnsignedLongTy,
4562 UnsignedLongTy,
4563 };
4564
4565 const char *FieldNames[] = {
4566 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00004567 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00004568 };
4569
4570 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004571 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00004572 SourceLocation(),
4573 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004574 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00004575 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004576 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004577 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004578 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00004579 T->addDecl(Field);
4580 }
4581
Douglas Gregor838db382010-02-11 01:19:42 +00004582 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00004583
4584 BlockDescriptorType = T;
4585
4586 return getTagDeclType(BlockDescriptorType);
4587}
4588
Jay Foad4ba2a172011-01-12 09:06:06 +00004589QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stump083c25e2009-10-22 00:49:09 +00004590 if (BlockDescriptorExtendedType)
4591 return getTagDeclType(BlockDescriptorExtendedType);
4592
4593 RecordDecl *T;
4594 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004595 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004596 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00004597 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00004598
4599 QualType FieldTypes[] = {
4600 UnsignedLongTy,
4601 UnsignedLongTy,
4602 getPointerType(VoidPtrTy),
4603 getPointerType(VoidPtrTy)
4604 };
4605
4606 const char *FieldNames[] = {
4607 "reserved",
4608 "Size",
4609 "CopyFuncPtr",
4610 "DestroyFuncPtr"
4611 };
4612
4613 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004614 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stump083c25e2009-10-22 00:49:09 +00004615 SourceLocation(),
4616 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004617 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00004618 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004619 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004620 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004621 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00004622 T->addDecl(Field);
4623 }
4624
Douglas Gregor838db382010-02-11 01:19:42 +00004625 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00004626
4627 BlockDescriptorExtendedType = T;
4628
4629 return getTagDeclType(BlockDescriptorExtendedType);
4630}
4631
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00004632/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4633/// requires copy/dispose. Note that this must match the logic
4634/// in buildByrefHelpers.
4635bool ASTContext::BlockRequiresCopying(QualType Ty,
4636 const VarDecl *D) {
4637 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4638 const Expr *copyExpr = getBlockVarCopyInits(D);
4639 if (!copyExpr && record->hasTrivialDestructor()) return false;
4640
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004641 return true;
Fariborz Jahaniane38be612010-11-17 00:21:28 +00004642 }
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00004643
4644 if (!Ty->isObjCRetainableType()) return false;
4645
4646 Qualifiers qs = Ty.getQualifiers();
4647
4648 // If we have lifetime, that dominates.
4649 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4650 assert(getLangOpts().ObjCAutoRefCount);
4651
4652 switch (lifetime) {
4653 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4654
4655 // These are just bits as far as the runtime is concerned.
4656 case Qualifiers::OCL_ExplicitNone:
4657 case Qualifiers::OCL_Autoreleasing:
4658 return false;
4659
4660 // Tell the runtime that this is ARC __weak, called by the
4661 // byref routines.
4662 case Qualifiers::OCL_Weak:
4663 // ARC __strong __block variables need to be retained.
4664 case Qualifiers::OCL_Strong:
4665 return true;
4666 }
4667 llvm_unreachable("fell out of lifetime switch!");
4668 }
4669 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4670 Ty->isObjCObjectPointerType());
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004671}
4672
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00004673bool ASTContext::getByrefLifetime(QualType Ty,
4674 Qualifiers::ObjCLifetime &LifeTime,
4675 bool &HasByrefExtendedLayout) const {
4676
4677 if (!getLangOpts().ObjC1 ||
4678 getLangOpts().getGC() != LangOptions::NonGC)
4679 return false;
4680
4681 HasByrefExtendedLayout = false;
Fariborz Jahanian34db84f2012-12-11 19:58:01 +00004682 if (Ty->isRecordType()) {
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00004683 HasByrefExtendedLayout = true;
4684 LifeTime = Qualifiers::OCL_None;
4685 }
4686 else if (getLangOpts().ObjCAutoRefCount)
4687 LifeTime = Ty.getObjCLifetime();
4688 // MRR.
4689 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4690 LifeTime = Qualifiers::OCL_ExplicitNone;
4691 else
4692 LifeTime = Qualifiers::OCL_None;
4693 return true;
4694}
4695
Douglas Gregore97179c2011-09-08 01:46:34 +00004696TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4697 if (!ObjCInstanceTypeDecl)
4698 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4699 getTranslationUnitDecl(),
4700 SourceLocation(),
4701 SourceLocation(),
4702 &Idents.get("instancetype"),
4703 getTrivialTypeSourceInfo(getObjCIdType()));
4704 return ObjCInstanceTypeDecl;
4705}
4706
Anders Carlssone8c49532007-10-29 06:33:42 +00004707// This returns true if a type has been typedefed to BOOL:
4708// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00004709static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00004710 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00004711 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4712 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00004713
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004714 return false;
4715}
4716
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004717/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004718/// purpose.
Jay Foad4ba2a172011-01-12 09:06:06 +00004719CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregorf968d832011-05-27 01:19:52 +00004720 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4721 return CharUnits::Zero();
4722
Ken Dyck199c3d62010-01-11 17:06:35 +00004723 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00004724
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004725 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004726 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004727 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004728 // Treat arrays as pointers, since that's how they're passed in.
4729 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004730 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004731 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00004732}
4733
4734static inline
4735std::string charUnitsToString(const CharUnits &CU) {
4736 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004737}
4738
John McCall6b5a61b2011-02-07 10:33:21 +00004739/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00004740/// declaration.
John McCall6b5a61b2011-02-07 10:33:21 +00004741std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4742 std::string S;
4743
David Chisnall5e530af2009-11-17 19:33:30 +00004744 const BlockDecl *Decl = Expr->getBlockDecl();
4745 QualType BlockTy =
4746 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4747 // Encode result type.
Fariborz Jahanian3d145f62012-11-15 19:02:45 +00004748 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian06cffc02012-11-14 23:11:38 +00004749 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None,
4750 BlockTy->getAs<FunctionType>()->getResultType(),
4751 S, true /*Extended*/);
4752 else
4753 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(),
4754 S);
David Chisnall5e530af2009-11-17 19:33:30 +00004755 // Compute size of all parameters.
4756 // Start with computing size of a pointer in number of bytes.
4757 // FIXME: There might(should) be a better way of doing this computation!
4758 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004759 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4760 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00004761 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00004762 E = Decl->param_end(); PI != E; ++PI) {
4763 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004764 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahanian075a5432012-06-30 00:48:59 +00004765 if (sz.isZero())
4766 continue;
Ken Dyck199c3d62010-01-11 17:06:35 +00004767 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00004768 ParmOffset += sz;
4769 }
4770 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00004771 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00004772 // Block pointer and offset.
4773 S += "@?0";
David Chisnall5e530af2009-11-17 19:33:30 +00004774
4775 // Argument types.
4776 ParmOffset = PtrSize;
4777 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4778 Decl->param_end(); PI != E; ++PI) {
4779 ParmVarDecl *PVDecl = *PI;
4780 QualType PType = PVDecl->getOriginalType();
4781 if (const ArrayType *AT =
4782 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4783 // Use array's original type only if it has known number of
4784 // elements.
4785 if (!isa<ConstantArrayType>(AT))
4786 PType = PVDecl->getType();
4787 } else if (PType->isFunctionType())
4788 PType = PVDecl->getType();
Fariborz Jahanian3d145f62012-11-15 19:02:45 +00004789 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian06cffc02012-11-14 23:11:38 +00004790 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4791 S, true /*Extended*/);
4792 else
4793 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00004794 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004795 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00004796 }
John McCall6b5a61b2011-02-07 10:33:21 +00004797
4798 return S;
David Chisnall5e530af2009-11-17 19:33:30 +00004799}
4800
Douglas Gregorf968d832011-05-27 01:19:52 +00004801bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall5389f482010-12-30 14:05:53 +00004802 std::string& S) {
4803 // Encode result type.
4804 getObjCEncodingForType(Decl->getResultType(), S);
4805 CharUnits ParmOffset;
4806 // Compute size of all parameters.
4807 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4808 E = Decl->param_end(); PI != E; ++PI) {
4809 QualType PType = (*PI)->getType();
4810 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004811 if (sz.isZero())
Fariborz Jahanian7e68ba52012-06-29 22:54:56 +00004812 continue;
4813
David Chisnall5389f482010-12-30 14:05:53 +00004814 assert (sz.isPositive() &&
Douglas Gregorf968d832011-05-27 01:19:52 +00004815 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall5389f482010-12-30 14:05:53 +00004816 ParmOffset += sz;
4817 }
4818 S += charUnitsToString(ParmOffset);
4819 ParmOffset = CharUnits::Zero();
4820
4821 // Argument types.
4822 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4823 E = Decl->param_end(); PI != E; ++PI) {
4824 ParmVarDecl *PVDecl = *PI;
4825 QualType PType = PVDecl->getOriginalType();
4826 if (const ArrayType *AT =
4827 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4828 // Use array's original type only if it has known number of
4829 // elements.
4830 if (!isa<ConstantArrayType>(AT))
4831 PType = PVDecl->getType();
4832 } else if (PType->isFunctionType())
4833 PType = PVDecl->getType();
4834 getObjCEncodingForType(PType, S);
4835 S += charUnitsToString(ParmOffset);
4836 ParmOffset += getObjCEncodingTypeSize(PType);
4837 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004838
4839 return false;
David Chisnall5389f482010-12-30 14:05:53 +00004840}
4841
Bob Wilsondc8dab62011-11-30 01:57:58 +00004842/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4843/// method parameter or return type. If Extended, include class names and
4844/// block object types.
4845void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4846 QualType T, std::string& S,
4847 bool Extended) const {
4848 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4849 getObjCEncodingForTypeQualifier(QT, S);
4850 // Encode parameter type.
4851 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4852 true /*OutermostType*/,
4853 false /*EncodingProperty*/,
4854 false /*StructField*/,
4855 Extended /*EncodeBlockParameters*/,
4856 Extended /*EncodeClassNames*/);
4857}
4858
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004859/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004860/// declaration.
Douglas Gregorf968d832011-05-27 01:19:52 +00004861bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilsondc8dab62011-11-30 01:57:58 +00004862 std::string& S,
4863 bool Extended) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004864 // FIXME: This is not very efficient.
Bob Wilsondc8dab62011-11-30 01:57:58 +00004865 // Encode return type.
4866 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4867 Decl->getResultType(), S, Extended);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004868 // Compute size of all parameters.
4869 // Start with computing size of a pointer in number of bytes.
4870 // FIXME: There might(should) be a better way of doing this computation!
4871 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004872 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004873 // The first two arguments (self and _cmd) are pointers; account for
4874 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00004875 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004876 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004877 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00004878 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004879 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004880 if (sz.isZero())
Fariborz Jahanian7e68ba52012-06-29 22:54:56 +00004881 continue;
4882
Ken Dyck199c3d62010-01-11 17:06:35 +00004883 assert (sz.isPositive() &&
4884 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004885 ParmOffset += sz;
4886 }
Ken Dyck199c3d62010-01-11 17:06:35 +00004887 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004888 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00004889 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00004890
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004891 // Argument types.
4892 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004893 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004894 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004895 const ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00004896 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00004897 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00004898 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4899 // Use array's original type only if it has known number of
4900 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00004901 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00004902 PType = PVDecl->getType();
4903 } else if (PType->isFunctionType())
4904 PType = PVDecl->getType();
Bob Wilsondc8dab62011-11-30 01:57:58 +00004905 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4906 PType, S, Extended);
Ken Dyck199c3d62010-01-11 17:06:35 +00004907 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004908 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004909 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004910
4911 return false;
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004912}
4913
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004914/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004915/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004916/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4917/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00004918/// Property attributes are stored as a comma-delimited C string. The simple
4919/// attributes readonly and bycopy are encoded as single characters. The
4920/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4921/// encoded as single characters, followed by an identifier. Property types
4922/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004923/// these attributes are defined by the following enumeration:
4924/// @code
4925/// enum PropertyAttributes {
4926/// kPropertyReadOnly = 'R', // property is read-only.
4927/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4928/// kPropertyByref = '&', // property is a reference to the value last assigned
4929/// kPropertyDynamic = 'D', // property is dynamic
4930/// kPropertyGetter = 'G', // followed by getter selector name
4931/// kPropertySetter = 'S', // followed by setter selector name
4932/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson0d4cb852012-03-22 17:48:02 +00004933/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004934/// kPropertyWeak = 'W' // 'weak' property
4935/// kPropertyStrong = 'P' // property GC'able
4936/// kPropertyNonAtomic = 'N' // property non-atomic
4937/// };
4938/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00004939void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004940 const Decl *Container,
Jay Foad4ba2a172011-01-12 09:06:06 +00004941 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004942 // Collect information from the property implementation decl(s).
4943 bool Dynamic = false;
4944 ObjCPropertyImplDecl *SynthesizePID = 0;
4945
4946 // FIXME: Duplicated code due to poor abstraction.
4947 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00004948 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004949 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4950 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004951 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004952 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00004953 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004954 if (PID->getPropertyDecl() == PD) {
4955 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4956 Dynamic = true;
4957 } else {
4958 SynthesizePID = PID;
4959 }
4960 }
4961 }
4962 } else {
Chris Lattner61710852008-10-05 17:34:18 +00004963 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004964 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004965 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004966 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00004967 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004968 if (PID->getPropertyDecl() == PD) {
4969 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4970 Dynamic = true;
4971 } else {
4972 SynthesizePID = PID;
4973 }
4974 }
Mike Stump1eb44332009-09-09 15:08:12 +00004975 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004976 }
4977 }
4978
4979 // FIXME: This is not very efficient.
4980 S = "T";
4981
4982 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004983 // GCC has some special rules regarding encoding of properties which
4984 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00004985 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004986 true /* outermost type */,
4987 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004988
4989 if (PD->isReadOnly()) {
4990 S += ",R";
Nico Weberd7ceab32013-05-08 23:47:40 +00004991 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
4992 S += ",C";
4993 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
4994 S += ",&";
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004995 } else {
4996 switch (PD->getSetterKind()) {
4997 case ObjCPropertyDecl::Assign: break;
4998 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00004999 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian3a02b442011-08-12 20:47:08 +00005000 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00005001 }
5002 }
5003
5004 // It really isn't clear at all what this means, since properties
5005 // are "dynamic by default".
5006 if (Dynamic)
5007 S += ",D";
5008
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00005009 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5010 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00005011
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00005012 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5013 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00005014 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00005015 }
5016
5017 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5018 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00005019 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00005020 }
5021
5022 if (SynthesizePID) {
5023 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5024 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00005025 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00005026 }
5027
5028 // FIXME: OBJCGC: weak & strong
5029}
5030
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005031/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00005032/// Another legacy compatibility encoding: 32-bit longs are encoded as
5033/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005034/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5035///
5036void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00005037 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00005038 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad4ba2a172011-01-12 09:06:06 +00005039 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005040 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00005041 else
Jay Foad4ba2a172011-01-12 09:06:06 +00005042 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005043 PointeeTy = IntTy;
5044 }
5045 }
5046}
5047
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00005048void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad4ba2a172011-01-12 09:06:06 +00005049 const FieldDecl *Field) const {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00005050 // We follow the behavior of gcc, expanding structures which are
5051 // directly pointed to, and expanding embedded structures. Note that
5052 // these rules are sufficient to prevent recursive encoding of the
5053 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00005054 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00005055 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00005056}
5057
John McCall3624e9e2012-12-20 02:45:14 +00005058static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5059 BuiltinType::Kind kind) {
5060 switch (kind) {
David Chisnall64fd7e82010-06-04 01:10:52 +00005061 case BuiltinType::Void: return 'v';
5062 case BuiltinType::Bool: return 'B';
5063 case BuiltinType::Char_U:
5064 case BuiltinType::UChar: return 'C';
John McCall3624e9e2012-12-20 02:45:14 +00005065 case BuiltinType::Char16:
David Chisnall64fd7e82010-06-04 01:10:52 +00005066 case BuiltinType::UShort: return 'S';
John McCall3624e9e2012-12-20 02:45:14 +00005067 case BuiltinType::Char32:
David Chisnall64fd7e82010-06-04 01:10:52 +00005068 case BuiltinType::UInt: return 'I';
5069 case BuiltinType::ULong:
John McCall3624e9e2012-12-20 02:45:14 +00005070 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnall64fd7e82010-06-04 01:10:52 +00005071 case BuiltinType::UInt128: return 'T';
5072 case BuiltinType::ULongLong: return 'Q';
5073 case BuiltinType::Char_S:
5074 case BuiltinType::SChar: return 'c';
5075 case BuiltinType::Short: return 's';
Chris Lattner3f59c972010-12-25 23:25:43 +00005076 case BuiltinType::WChar_S:
5077 case BuiltinType::WChar_U:
David Chisnall64fd7e82010-06-04 01:10:52 +00005078 case BuiltinType::Int: return 'i';
5079 case BuiltinType::Long:
John McCall3624e9e2012-12-20 02:45:14 +00005080 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnall64fd7e82010-06-04 01:10:52 +00005081 case BuiltinType::LongLong: return 'q';
5082 case BuiltinType::Int128: return 't';
5083 case BuiltinType::Float: return 'f';
5084 case BuiltinType::Double: return 'd';
Daniel Dunbar3a0be842010-10-11 21:13:48 +00005085 case BuiltinType::LongDouble: return 'D';
John McCall3624e9e2012-12-20 02:45:14 +00005086 case BuiltinType::NullPtr: return '*'; // like char*
5087
5088 case BuiltinType::Half:
5089 // FIXME: potentially need @encodes for these!
5090 return ' ';
5091
5092 case BuiltinType::ObjCId:
5093 case BuiltinType::ObjCClass:
5094 case BuiltinType::ObjCSel:
5095 llvm_unreachable("@encoding ObjC primitive type");
5096
5097 // OpenCL and placeholder types don't need @encodings.
5098 case BuiltinType::OCLImage1d:
5099 case BuiltinType::OCLImage1dArray:
5100 case BuiltinType::OCLImage1dBuffer:
5101 case BuiltinType::OCLImage2d:
5102 case BuiltinType::OCLImage2dArray:
5103 case BuiltinType::OCLImage3d:
Guy Benyeie6b9d802013-01-20 12:31:11 +00005104 case BuiltinType::OCLEvent:
Guy Benyei21f18c42013-02-07 10:55:47 +00005105 case BuiltinType::OCLSampler:
John McCall3624e9e2012-12-20 02:45:14 +00005106 case BuiltinType::Dependent:
5107#define BUILTIN_TYPE(KIND, ID)
5108#define PLACEHOLDER_TYPE(KIND, ID) \
5109 case BuiltinType::KIND:
5110#include "clang/AST/BuiltinTypes.def"
5111 llvm_unreachable("invalid builtin type for @encode");
David Chisnall64fd7e82010-06-04 01:10:52 +00005112 }
David Blaikie719e53f2013-01-09 17:48:41 +00005113 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnall64fd7e82010-06-04 01:10:52 +00005114}
5115
Douglas Gregor5471bc82011-09-08 17:18:35 +00005116static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5117 EnumDecl *Enum = ET->getDecl();
5118
5119 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5120 if (!Enum->isFixed())
5121 return 'i';
5122
5123 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall3624e9e2012-12-20 02:45:14 +00005124 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5125 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor5471bc82011-09-08 17:18:35 +00005126}
5127
Jay Foad4ba2a172011-01-12 09:06:06 +00005128static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00005129 QualType T, const FieldDecl *FD) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005130 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00005131 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00005132 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5133 // The GNU runtime requires more information; bitfields are encoded as b,
5134 // then the offset (in bits) of the first element, then the type of the
5135 // bitfield, then the size in bits. For example, in this structure:
5136 //
5137 // struct
5138 // {
5139 // int integer;
5140 // int flags:2;
5141 // };
5142 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5143 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5144 // information is not especially sensible, but we're stuck with it for
5145 // compatibility with GCC, although providing it breaks anything that
5146 // actually uses runtime introspection and wants to work on both runtimes...
John McCall260611a2012-06-20 06:18:46 +00005147 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnall64fd7e82010-06-04 01:10:52 +00005148 const RecordDecl *RD = FD->getParent();
5149 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedman82905742011-07-07 01:54:01 +00005150 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor5471bc82011-09-08 17:18:35 +00005151 if (const EnumType *ET = T->getAs<EnumType>())
5152 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall3624e9e2012-12-20 02:45:14 +00005153 else {
5154 const BuiltinType *BT = T->castAs<BuiltinType>();
5155 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5156 }
David Chisnall64fd7e82010-06-04 01:10:52 +00005157 }
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005158 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00005159}
5160
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00005161// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00005162void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5163 bool ExpandPointedToStructures,
5164 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00005165 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00005166 bool OutermostType,
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005167 bool EncodingProperty,
Bob Wilsondc8dab62011-11-30 01:57:58 +00005168 bool StructField,
5169 bool EncodeBlockParameters,
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005170 bool EncodeClassNames,
5171 bool EncodePointerToObjCTypedef) const {
John McCall3624e9e2012-12-20 02:45:14 +00005172 CanQualType CT = getCanonicalType(T);
5173 switch (CT->getTypeClass()) {
5174 case Type::Builtin:
5175 case Type::Enum:
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005176 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00005177 return EncodeBitField(this, S, T, FD);
John McCall3624e9e2012-12-20 02:45:14 +00005178 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5179 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5180 else
5181 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005182 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005183
John McCall3624e9e2012-12-20 02:45:14 +00005184 case Type::Complex: {
5185 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlssonc612f7b2009-04-09 21:55:45 +00005186 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00005187 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00005188 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005189 return;
5190 }
John McCall3624e9e2012-12-20 02:45:14 +00005191
5192 case Type::Atomic: {
5193 const AtomicType *AT = T->castAs<AtomicType>();
5194 S += 'A';
5195 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, 0,
5196 false, false);
5197 return;
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00005198 }
John McCall3624e9e2012-12-20 02:45:14 +00005199
5200 // encoding for pointer or reference types.
5201 case Type::Pointer:
5202 case Type::LValueReference:
5203 case Type::RValueReference: {
5204 QualType PointeeTy;
5205 if (isa<PointerType>(CT)) {
5206 const PointerType *PT = T->castAs<PointerType>();
5207 if (PT->isObjCSelType()) {
5208 S += ':';
5209 return;
5210 }
5211 PointeeTy = PT->getPointeeType();
5212 } else {
5213 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5214 }
5215
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005216 bool isReadOnly = false;
5217 // For historical/compatibility reasons, the read-only qualifier of the
5218 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5219 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00005220 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00005221 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005222 if (OutermostType && T.isConstQualified()) {
5223 isReadOnly = true;
5224 S += 'r';
5225 }
Mike Stump9fdbab32009-07-31 02:02:20 +00005226 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005227 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00005228 while (P->getAs<PointerType>())
5229 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005230 if (P.isConstQualified()) {
5231 isReadOnly = true;
5232 S += 'r';
5233 }
5234 }
5235 if (isReadOnly) {
5236 // Another legacy compatibility encoding. Some ObjC qualifier and type
5237 // combinations need to be rearranged.
5238 // Rewrite "in const" from "nr" to "rn"
Chris Lattner5f9e2722011-07-23 10:55:15 +00005239 if (StringRef(S).endswith("nr"))
Benjamin Kramer02379412010-04-27 17:12:11 +00005240 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005241 }
Mike Stump1eb44332009-09-09 15:08:12 +00005242
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005243 if (PointeeTy->isCharType()) {
5244 // char pointer types should be encoded as '*' unless it is a
5245 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00005246 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005247 S += '*';
5248 return;
5249 }
Ted Kremenek6217b802009-07-29 21:53:49 +00005250 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00005251 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5252 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5253 S += '#';
5254 return;
5255 }
5256 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5257 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5258 S += '@';
5259 return;
5260 }
5261 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005262 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005263 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005264 getLegacyIntegralTypeEncoding(PointeeTy);
5265
Mike Stump1eb44332009-09-09 15:08:12 +00005266 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005267 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005268 return;
5269 }
John McCall3624e9e2012-12-20 02:45:14 +00005270
5271 case Type::ConstantArray:
5272 case Type::IncompleteArray:
5273 case Type::VariableArray: {
5274 const ArrayType *AT = cast<ArrayType>(CT);
5275
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005276 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlsson559a8332009-02-22 01:38:57 +00005277 // Incomplete arrays are encoded as a pointer to the array element.
5278 S += '^';
5279
Mike Stump1eb44332009-09-09 15:08:12 +00005280 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00005281 false, ExpandStructures, FD);
5282 } else {
5283 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00005284
Fariborz Jahanian48eff6c2013-06-04 16:04:37 +00005285 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5286 S += llvm::utostr(CAT->getSize().getZExtValue());
5287 else {
Anders Carlsson559a8332009-02-22 01:38:57 +00005288 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005289 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5290 "Unknown array type!");
Anders Carlsson559a8332009-02-22 01:38:57 +00005291 S += '0';
5292 }
Mike Stump1eb44332009-09-09 15:08:12 +00005293
5294 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00005295 false, ExpandStructures, FD);
5296 S += ']';
5297 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005298 return;
5299 }
Mike Stump1eb44332009-09-09 15:08:12 +00005300
John McCall3624e9e2012-12-20 02:45:14 +00005301 case Type::FunctionNoProto:
5302 case Type::FunctionProto:
Anders Carlssonc0a87b72007-10-30 00:06:20 +00005303 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005304 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005305
John McCall3624e9e2012-12-20 02:45:14 +00005306 case Type::Record: {
5307 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005308 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00005309 // Anonymous structures print as '?'
5310 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5311 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00005312 if (ClassTemplateSpecializationDecl *Spec
5313 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5314 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer5eada842013-02-22 15:46:01 +00005315 llvm::raw_string_ostream OS(S);
5316 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor910f8002010-11-07 23:05:16 +00005317 TemplateArgs.data(),
5318 TemplateArgs.size(),
Douglas Gregor30c42402011-09-27 22:38:19 +00005319 (*this).getPrintingPolicy());
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00005320 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00005321 } else {
5322 S += '?';
5323 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00005324 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00005325 S += '=';
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005326 if (!RDecl->isUnion()) {
5327 getObjCEncodingForStructureImpl(RDecl, S, FD);
5328 } else {
5329 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5330 FieldEnd = RDecl->field_end();
5331 Field != FieldEnd; ++Field) {
5332 if (FD) {
5333 S += '"';
5334 S += Field->getNameAsString();
5335 S += '"';
5336 }
Mike Stump1eb44332009-09-09 15:08:12 +00005337
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005338 // Special case bit-fields.
5339 if (Field->isBitField()) {
5340 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie581deb32012-06-06 20:45:41 +00005341 *Field);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005342 } else {
5343 QualType qt = Field->getType();
5344 getLegacyIntegralTypeEncoding(qt);
5345 getObjCEncodingForTypeImpl(qt, S, false, true,
5346 FD, /*OutermostType*/false,
5347 /*EncodingProperty*/false,
5348 /*StructField*/true);
5349 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005350 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00005351 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00005352 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005353 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005354 return;
5355 }
Mike Stump1eb44332009-09-09 15:08:12 +00005356
John McCall3624e9e2012-12-20 02:45:14 +00005357 case Type::BlockPointer: {
5358 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff21a98b12009-02-02 18:24:29 +00005359 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilsondc8dab62011-11-30 01:57:58 +00005360 if (EncodeBlockParameters) {
John McCall3624e9e2012-12-20 02:45:14 +00005361 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilsondc8dab62011-11-30 01:57:58 +00005362
5363 S += '<';
5364 // Block return type
5365 getObjCEncodingForTypeImpl(FT->getResultType(), S,
5366 ExpandPointedToStructures, ExpandStructures,
5367 FD,
5368 false /* OutermostType */,
5369 EncodingProperty,
5370 false /* StructField */,
5371 EncodeBlockParameters,
5372 EncodeClassNames);
5373 // Block self
5374 S += "@?";
5375 // Block parameters
5376 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
5377 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
5378 E = FPT->arg_type_end(); I && (I != E); ++I) {
5379 getObjCEncodingForTypeImpl(*I, S,
5380 ExpandPointedToStructures,
5381 ExpandStructures,
5382 FD,
5383 false /* OutermostType */,
5384 EncodingProperty,
5385 false /* StructField */,
5386 EncodeBlockParameters,
5387 EncodeClassNames);
5388 }
5389 }
5390 S += '>';
5391 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005392 return;
5393 }
Mike Stump1eb44332009-09-09 15:08:12 +00005394
John McCall3624e9e2012-12-20 02:45:14 +00005395 case Type::ObjCObject:
5396 case Type::ObjCInterface: {
5397 // Ignore protocol qualifiers when mangling at this level.
5398 T = T->castAs<ObjCObjectType>()->getBaseType();
John McCallc12c5bb2010-05-15 11:32:37 +00005399
John McCall3624e9e2012-12-20 02:45:14 +00005400 // The assumption seems to be that this assert will succeed
5401 // because nested levels will have filtered out 'id' and 'Class'.
5402 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005403 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00005404 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005405 S += '{';
5406 const IdentifierInfo *II = OI->getIdentifier();
5407 S += II->getName();
5408 S += '=';
Jordy Rosedb8264e2011-07-22 02:08:32 +00005409 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00005410 DeepCollectObjCIvars(OI, true, Ivars);
5411 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00005412 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00005413 if (Field->isBitField())
5414 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005415 else
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005416 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5417 false, false, false, false, false,
5418 EncodePointerToObjCTypedef);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005419 }
5420 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005421 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005422 }
Mike Stump1eb44332009-09-09 15:08:12 +00005423
John McCall3624e9e2012-12-20 02:45:14 +00005424 case Type::ObjCObjectPointer: {
5425 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff14108da2009-07-10 23:34:53 +00005426 if (OPT->isObjCIdType()) {
5427 S += '@';
5428 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005429 }
Mike Stump1eb44332009-09-09 15:08:12 +00005430
Steve Naroff27d20a22009-10-28 22:03:49 +00005431 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5432 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5433 // Since this is a binary compatibility issue, need to consult with runtime
5434 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00005435 S += '#';
5436 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005437 }
Mike Stump1eb44332009-09-09 15:08:12 +00005438
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005439 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005440 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00005441 ExpandPointedToStructures,
5442 ExpandStructures, FD);
Bob Wilsondc8dab62011-11-30 01:57:58 +00005443 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff14108da2009-07-10 23:34:53 +00005444 // Note that we do extended encoding of protocol qualifer list
5445 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00005446 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005447 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5448 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00005449 S += '<';
5450 S += (*I)->getNameAsString();
5451 S += '>';
5452 }
5453 S += '"';
5454 }
5455 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005456 }
Mike Stump1eb44332009-09-09 15:08:12 +00005457
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005458 QualType PointeeTy = OPT->getPointeeType();
5459 if (!EncodingProperty &&
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005460 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5461 !EncodePointerToObjCTypedef) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005462 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00005463 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005464 // {...};
5465 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00005466 getObjCEncodingForTypeImpl(PointeeTy, S,
5467 false, ExpandPointedToStructures,
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005468 NULL,
5469 false, false, false, false, false,
5470 /*EncodePointerToObjCTypedef*/true);
Steve Naroff14108da2009-07-10 23:34:53 +00005471 return;
5472 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005473
5474 S += '@';
Bob Wilsondc8dab62011-11-30 01:57:58 +00005475 if (OPT->getInterfaceDecl() &&
5476 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005477 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00005478 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005479 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5480 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005481 S += '<';
5482 S += (*I)->getNameAsString();
5483 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00005484 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005485 S += '"';
5486 }
5487 return;
5488 }
Mike Stump1eb44332009-09-09 15:08:12 +00005489
John McCall532ec7b2010-05-17 23:56:34 +00005490 // gcc just blithely ignores member pointers.
John McCall3624e9e2012-12-20 02:45:14 +00005491 // FIXME: we shoul do better than that. 'M' is available.
5492 case Type::MemberPointer:
John McCall532ec7b2010-05-17 23:56:34 +00005493 return;
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005494
John McCall3624e9e2012-12-20 02:45:14 +00005495 case Type::Vector:
5496 case Type::ExtVector:
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005497 // This matches gcc's encoding, even though technically it is
5498 // insufficient.
5499 // FIXME. We should do a better job than gcc.
5500 return;
John McCall3624e9e2012-12-20 02:45:14 +00005501
Richard Smithdc7a4f52013-04-30 13:56:41 +00005502 case Type::Auto:
5503 // We could see an undeduced auto type here during error recovery.
5504 // Just ignore it.
5505 return;
5506
John McCall3624e9e2012-12-20 02:45:14 +00005507#define ABSTRACT_TYPE(KIND, BASE)
5508#define TYPE(KIND, BASE)
5509#define DEPENDENT_TYPE(KIND, BASE) \
5510 case Type::KIND:
5511#define NON_CANONICAL_TYPE(KIND, BASE) \
5512 case Type::KIND:
5513#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5514 case Type::KIND:
5515#include "clang/AST/TypeNodes.def"
5516 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005517 }
John McCall3624e9e2012-12-20 02:45:14 +00005518 llvm_unreachable("bad type kind!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005519}
5520
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005521void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5522 std::string &S,
5523 const FieldDecl *FD,
5524 bool includeVBases) const {
5525 assert(RDecl && "Expected non-null RecordDecl");
5526 assert(!RDecl->isUnion() && "Should not be called for unions");
5527 if (!RDecl->getDefinition())
5528 return;
5529
5530 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5531 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5532 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5533
5534 if (CXXRec) {
5535 for (CXXRecordDecl::base_class_iterator
5536 BI = CXXRec->bases_begin(),
5537 BE = CXXRec->bases_end(); BI != BE; ++BI) {
5538 if (!BI->isVirtual()) {
5539 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005540 if (base->isEmpty())
5541 continue;
Benjamin Kramerd4f51982012-07-04 18:45:14 +00005542 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005543 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5544 std::make_pair(offs, base));
5545 }
5546 }
5547 }
5548
5549 unsigned i = 0;
5550 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5551 FieldEnd = RDecl->field_end();
5552 Field != FieldEnd; ++Field, ++i) {
5553 uint64_t offs = layout.getFieldOffset(i);
5554 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie581deb32012-06-06 20:45:41 +00005555 std::make_pair(offs, *Field));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005556 }
5557
5558 if (CXXRec && includeVBases) {
5559 for (CXXRecordDecl::base_class_iterator
5560 BI = CXXRec->vbases_begin(),
5561 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
5562 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005563 if (base->isEmpty())
5564 continue;
Benjamin Kramerd4f51982012-07-04 18:45:14 +00005565 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Argyrios Kyrtzidis19aa8602011-09-26 18:14:24 +00005566 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
5567 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5568 std::make_pair(offs, base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005569 }
5570 }
5571
5572 CharUnits size;
5573 if (CXXRec) {
5574 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5575 } else {
5576 size = layout.getSize();
5577 }
5578
5579 uint64_t CurOffs = 0;
5580 std::multimap<uint64_t, NamedDecl *>::iterator
5581 CurLayObj = FieldOrBaseOffsets.begin();
5582
Douglas Gregor58db7a52012-04-27 22:30:01 +00005583 if (CXXRec && CXXRec->isDynamicClass() &&
5584 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005585 if (FD) {
5586 S += "\"_vptr$";
5587 std::string recname = CXXRec->getNameAsString();
5588 if (recname.empty()) recname = "?";
5589 S += recname;
5590 S += '"';
5591 }
5592 S += "^^?";
5593 CurOffs += getTypeSize(VoidPtrTy);
5594 }
5595
5596 if (!RDecl->hasFlexibleArrayMember()) {
5597 // Mark the end of the structure.
5598 uint64_t offs = toBits(size);
5599 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5600 std::make_pair(offs, (NamedDecl*)0));
5601 }
5602
5603 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5604 assert(CurOffs <= CurLayObj->first);
5605
5606 if (CurOffs < CurLayObj->first) {
5607 uint64_t padding = CurLayObj->first - CurOffs;
5608 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5609 // packing/alignment of members is different that normal, in which case
5610 // the encoding will be out-of-sync with the real layout.
5611 // If the runtime switches to just consider the size of types without
5612 // taking into account alignment, we could make padding explicit in the
5613 // encoding (e.g. using arrays of chars). The encoding strings would be
5614 // longer then though.
5615 CurOffs += padding;
5616 }
5617
5618 NamedDecl *dcl = CurLayObj->second;
5619 if (dcl == 0)
5620 break; // reached end of structure.
5621
5622 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5623 // We expand the bases without their virtual bases since those are going
5624 // in the initial structure. Note that this differs from gcc which
5625 // expands virtual bases each time one is encountered in the hierarchy,
5626 // making the encoding type bigger than it really is.
5627 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005628 assert(!base->isEmpty());
5629 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005630 } else {
5631 FieldDecl *field = cast<FieldDecl>(dcl);
5632 if (FD) {
5633 S += '"';
5634 S += field->getNameAsString();
5635 S += '"';
5636 }
5637
5638 if (field->isBitField()) {
5639 EncodeBitField(this, S, field->getType(), field);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005640 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005641 } else {
5642 QualType qt = field->getType();
5643 getLegacyIntegralTypeEncoding(qt);
5644 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5645 /*OutermostType*/false,
5646 /*EncodingProperty*/false,
5647 /*StructField*/true);
5648 CurOffs += getTypeSize(field->getType());
5649 }
5650 }
5651 }
5652}
5653
Mike Stump1eb44332009-09-09 15:08:12 +00005654void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00005655 std::string& S) const {
5656 if (QT & Decl::OBJC_TQ_In)
5657 S += 'n';
5658 if (QT & Decl::OBJC_TQ_Inout)
5659 S += 'N';
5660 if (QT & Decl::OBJC_TQ_Out)
5661 S += 'o';
5662 if (QT & Decl::OBJC_TQ_Bycopy)
5663 S += 'O';
5664 if (QT & Decl::OBJC_TQ_Byref)
5665 S += 'R';
5666 if (QT & Decl::OBJC_TQ_Oneway)
5667 S += 'V';
5668}
5669
Douglas Gregor4dfd02a2011-08-12 05:46:01 +00005670TypedefDecl *ASTContext::getObjCIdDecl() const {
5671 if (!ObjCIdDecl) {
5672 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5673 T = getObjCObjectPointerType(T);
5674 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
5675 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5676 getTranslationUnitDecl(),
5677 SourceLocation(), SourceLocation(),
5678 &Idents.get("id"), IdInfo);
5679 }
5680
5681 return ObjCIdDecl;
Steve Naroff7e219e42007-10-15 14:41:52 +00005682}
5683
Douglas Gregor7a27ea52011-08-12 06:17:30 +00005684TypedefDecl *ASTContext::getObjCSelDecl() const {
5685 if (!ObjCSelDecl) {
5686 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5687 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5688 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5689 getTranslationUnitDecl(),
5690 SourceLocation(), SourceLocation(),
5691 &Idents.get("SEL"), SelInfo);
5692 }
5693 return ObjCSelDecl;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00005694}
5695
Douglas Gregor79d67262011-08-12 05:59:41 +00005696TypedefDecl *ASTContext::getObjCClassDecl() const {
5697 if (!ObjCClassDecl) {
5698 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5699 T = getObjCObjectPointerType(T);
5700 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5701 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5702 getTranslationUnitDecl(),
5703 SourceLocation(), SourceLocation(),
5704 &Idents.get("Class"), ClassInfo);
5705 }
5706
5707 return ObjCClassDecl;
Anders Carlsson8baaca52007-10-31 02:53:19 +00005708}
5709
Douglas Gregora6ea10e2012-01-17 18:09:05 +00005710ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5711 if (!ObjCProtocolClassDecl) {
5712 ObjCProtocolClassDecl
5713 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5714 SourceLocation(),
5715 &Idents.get("Protocol"),
5716 /*PrevDecl=*/0,
5717 SourceLocation(), true);
5718 }
5719
5720 return ObjCProtocolClassDecl;
5721}
5722
Meador Ingec5613b22012-06-16 03:34:49 +00005723//===----------------------------------------------------------------------===//
5724// __builtin_va_list Construction Functions
5725//===----------------------------------------------------------------------===//
5726
5727static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5728 // typedef char* __builtin_va_list;
5729 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5730 TypeSourceInfo *TInfo
5731 = Context->getTrivialTypeSourceInfo(CharPtrType);
5732
5733 TypedefDecl *VaListTypeDecl
5734 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5735 Context->getTranslationUnitDecl(),
5736 SourceLocation(), SourceLocation(),
5737 &Context->Idents.get("__builtin_va_list"),
5738 TInfo);
5739 return VaListTypeDecl;
5740}
5741
5742static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5743 // typedef void* __builtin_va_list;
5744 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5745 TypeSourceInfo *TInfo
5746 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5747
5748 TypedefDecl *VaListTypeDecl
5749 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5750 Context->getTranslationUnitDecl(),
5751 SourceLocation(), SourceLocation(),
5752 &Context->Idents.get("__builtin_va_list"),
5753 TInfo);
5754 return VaListTypeDecl;
5755}
5756
Tim Northoverc264e162013-01-31 12:13:10 +00005757static TypedefDecl *
5758CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
5759 RecordDecl *VaListTagDecl;
5760 if (Context->getLangOpts().CPlusPlus) {
5761 // namespace std { struct __va_list {
5762 NamespaceDecl *NS;
5763 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5764 Context->getTranslationUnitDecl(),
5765 /*Inline*/false, SourceLocation(),
5766 SourceLocation(), &Context->Idents.get("std"),
5767 /*PrevDecl*/0);
5768
5769 VaListTagDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5770 Context->getTranslationUnitDecl(),
5771 SourceLocation(), SourceLocation(),
5772 &Context->Idents.get("__va_list"));
5773 VaListTagDecl->setDeclContext(NS);
5774 } else {
5775 // struct __va_list
5776 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5777 Context->getTranslationUnitDecl(),
5778 &Context->Idents.get("__va_list"));
5779 }
5780
5781 VaListTagDecl->startDefinition();
5782
5783 const size_t NumFields = 5;
5784 QualType FieldTypes[NumFields];
5785 const char *FieldNames[NumFields];
5786
5787 // void *__stack;
5788 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
5789 FieldNames[0] = "__stack";
5790
5791 // void *__gr_top;
5792 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
5793 FieldNames[1] = "__gr_top";
5794
5795 // void *__vr_top;
5796 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5797 FieldNames[2] = "__vr_top";
5798
5799 // int __gr_offs;
5800 FieldTypes[3] = Context->IntTy;
5801 FieldNames[3] = "__gr_offs";
5802
5803 // int __vr_offs;
5804 FieldTypes[4] = Context->IntTy;
5805 FieldNames[4] = "__vr_offs";
5806
5807 // Create fields
5808 for (unsigned i = 0; i < NumFields; ++i) {
5809 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5810 VaListTagDecl,
5811 SourceLocation(),
5812 SourceLocation(),
5813 &Context->Idents.get(FieldNames[i]),
5814 FieldTypes[i], /*TInfo=*/0,
5815 /*BitWidth=*/0,
5816 /*Mutable=*/false,
5817 ICIS_NoInit);
5818 Field->setAccess(AS_public);
5819 VaListTagDecl->addDecl(Field);
5820 }
5821 VaListTagDecl->completeDefinition();
5822 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5823 Context->VaListTagTy = VaListTagType;
5824
5825 // } __builtin_va_list;
5826 TypedefDecl *VaListTypedefDecl
5827 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5828 Context->getTranslationUnitDecl(),
5829 SourceLocation(), SourceLocation(),
5830 &Context->Idents.get("__builtin_va_list"),
5831 Context->getTrivialTypeSourceInfo(VaListTagType));
5832
5833 return VaListTypedefDecl;
5834}
5835
Meador Ingec5613b22012-06-16 03:34:49 +00005836static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5837 // typedef struct __va_list_tag {
5838 RecordDecl *VaListTagDecl;
5839
5840 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5841 Context->getTranslationUnitDecl(),
5842 &Context->Idents.get("__va_list_tag"));
5843 VaListTagDecl->startDefinition();
5844
5845 const size_t NumFields = 5;
5846 QualType FieldTypes[NumFields];
5847 const char *FieldNames[NumFields];
5848
5849 // unsigned char gpr;
5850 FieldTypes[0] = Context->UnsignedCharTy;
5851 FieldNames[0] = "gpr";
5852
5853 // unsigned char fpr;
5854 FieldTypes[1] = Context->UnsignedCharTy;
5855 FieldNames[1] = "fpr";
5856
5857 // unsigned short reserved;
5858 FieldTypes[2] = Context->UnsignedShortTy;
5859 FieldNames[2] = "reserved";
5860
5861 // void* overflow_arg_area;
5862 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5863 FieldNames[3] = "overflow_arg_area";
5864
5865 // void* reg_save_area;
5866 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5867 FieldNames[4] = "reg_save_area";
5868
5869 // Create fields
5870 for (unsigned i = 0; i < NumFields; ++i) {
5871 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5872 SourceLocation(),
5873 SourceLocation(),
5874 &Context->Idents.get(FieldNames[i]),
5875 FieldTypes[i], /*TInfo=*/0,
5876 /*BitWidth=*/0,
5877 /*Mutable=*/false,
5878 ICIS_NoInit);
5879 Field->setAccess(AS_public);
5880 VaListTagDecl->addDecl(Field);
5881 }
5882 VaListTagDecl->completeDefinition();
5883 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingefb40e3f2012-07-01 15:57:25 +00005884 Context->VaListTagTy = VaListTagType;
Meador Ingec5613b22012-06-16 03:34:49 +00005885
5886 // } __va_list_tag;
5887 TypedefDecl *VaListTagTypedefDecl
5888 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5889 Context->getTranslationUnitDecl(),
5890 SourceLocation(), SourceLocation(),
5891 &Context->Idents.get("__va_list_tag"),
5892 Context->getTrivialTypeSourceInfo(VaListTagType));
5893 QualType VaListTagTypedefType =
5894 Context->getTypedefType(VaListTagTypedefDecl);
5895
5896 // typedef __va_list_tag __builtin_va_list[1];
5897 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5898 QualType VaListTagArrayType
5899 = Context->getConstantArrayType(VaListTagTypedefType,
5900 Size, ArrayType::Normal, 0);
5901 TypeSourceInfo *TInfo
5902 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5903 TypedefDecl *VaListTypedefDecl
5904 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5905 Context->getTranslationUnitDecl(),
5906 SourceLocation(), SourceLocation(),
5907 &Context->Idents.get("__builtin_va_list"),
5908 TInfo);
5909
5910 return VaListTypedefDecl;
5911}
5912
5913static TypedefDecl *
5914CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5915 // typedef struct __va_list_tag {
5916 RecordDecl *VaListTagDecl;
5917 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5918 Context->getTranslationUnitDecl(),
5919 &Context->Idents.get("__va_list_tag"));
5920 VaListTagDecl->startDefinition();
5921
5922 const size_t NumFields = 4;
5923 QualType FieldTypes[NumFields];
5924 const char *FieldNames[NumFields];
5925
5926 // unsigned gp_offset;
5927 FieldTypes[0] = Context->UnsignedIntTy;
5928 FieldNames[0] = "gp_offset";
5929
5930 // unsigned fp_offset;
5931 FieldTypes[1] = Context->UnsignedIntTy;
5932 FieldNames[1] = "fp_offset";
5933
5934 // void* overflow_arg_area;
5935 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5936 FieldNames[2] = "overflow_arg_area";
5937
5938 // void* reg_save_area;
5939 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5940 FieldNames[3] = "reg_save_area";
5941
5942 // Create fields
5943 for (unsigned i = 0; i < NumFields; ++i) {
5944 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5945 VaListTagDecl,
5946 SourceLocation(),
5947 SourceLocation(),
5948 &Context->Idents.get(FieldNames[i]),
5949 FieldTypes[i], /*TInfo=*/0,
5950 /*BitWidth=*/0,
5951 /*Mutable=*/false,
5952 ICIS_NoInit);
5953 Field->setAccess(AS_public);
5954 VaListTagDecl->addDecl(Field);
5955 }
5956 VaListTagDecl->completeDefinition();
5957 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingefb40e3f2012-07-01 15:57:25 +00005958 Context->VaListTagTy = VaListTagType;
Meador Ingec5613b22012-06-16 03:34:49 +00005959
5960 // } __va_list_tag;
5961 TypedefDecl *VaListTagTypedefDecl
5962 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5963 Context->getTranslationUnitDecl(),
5964 SourceLocation(), SourceLocation(),
5965 &Context->Idents.get("__va_list_tag"),
5966 Context->getTrivialTypeSourceInfo(VaListTagType));
5967 QualType VaListTagTypedefType =
5968 Context->getTypedefType(VaListTagTypedefDecl);
5969
5970 // typedef __va_list_tag __builtin_va_list[1];
5971 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5972 QualType VaListTagArrayType
5973 = Context->getConstantArrayType(VaListTagTypedefType,
5974 Size, ArrayType::Normal,0);
5975 TypeSourceInfo *TInfo
5976 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5977 TypedefDecl *VaListTypedefDecl
5978 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5979 Context->getTranslationUnitDecl(),
5980 SourceLocation(), SourceLocation(),
5981 &Context->Idents.get("__builtin_va_list"),
5982 TInfo);
5983
5984 return VaListTypedefDecl;
5985}
5986
5987static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5988 // typedef int __builtin_va_list[4];
5989 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5990 QualType IntArrayType
5991 = Context->getConstantArrayType(Context->IntTy,
5992 Size, ArrayType::Normal, 0);
5993 TypedefDecl *VaListTypedefDecl
5994 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5995 Context->getTranslationUnitDecl(),
5996 SourceLocation(), SourceLocation(),
5997 &Context->Idents.get("__builtin_va_list"),
5998 Context->getTrivialTypeSourceInfo(IntArrayType));
5999
6000 return VaListTypedefDecl;
6001}
6002
Logan Chieneae5a8202012-10-10 06:56:20 +00006003static TypedefDecl *
6004CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
6005 RecordDecl *VaListDecl;
6006 if (Context->getLangOpts().CPlusPlus) {
6007 // namespace std { struct __va_list {
6008 NamespaceDecl *NS;
6009 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6010 Context->getTranslationUnitDecl(),
6011 /*Inline*/false, SourceLocation(),
6012 SourceLocation(), &Context->Idents.get("std"),
6013 /*PrevDecl*/0);
6014
6015 VaListDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
6016 Context->getTranslationUnitDecl(),
6017 SourceLocation(), SourceLocation(),
6018 &Context->Idents.get("__va_list"));
6019
6020 VaListDecl->setDeclContext(NS);
6021
6022 } else {
6023 // struct __va_list {
6024 VaListDecl = CreateRecordDecl(*Context, TTK_Struct,
6025 Context->getTranslationUnitDecl(),
6026 &Context->Idents.get("__va_list"));
6027 }
6028
6029 VaListDecl->startDefinition();
6030
6031 // void * __ap;
6032 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6033 VaListDecl,
6034 SourceLocation(),
6035 SourceLocation(),
6036 &Context->Idents.get("__ap"),
6037 Context->getPointerType(Context->VoidTy),
6038 /*TInfo=*/0,
6039 /*BitWidth=*/0,
6040 /*Mutable=*/false,
6041 ICIS_NoInit);
6042 Field->setAccess(AS_public);
6043 VaListDecl->addDecl(Field);
6044
6045 // };
6046 VaListDecl->completeDefinition();
6047
6048 // typedef struct __va_list __builtin_va_list;
6049 TypeSourceInfo *TInfo
6050 = Context->getTrivialTypeSourceInfo(Context->getRecordType(VaListDecl));
6051
6052 TypedefDecl *VaListTypeDecl
6053 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6054 Context->getTranslationUnitDecl(),
6055 SourceLocation(), SourceLocation(),
6056 &Context->Idents.get("__builtin_va_list"),
6057 TInfo);
6058
6059 return VaListTypeDecl;
6060}
6061
Ulrich Weigandb8409212013-05-06 16:26:41 +00006062static TypedefDecl *
6063CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
6064 // typedef struct __va_list_tag {
6065 RecordDecl *VaListTagDecl;
6066 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
6067 Context->getTranslationUnitDecl(),
6068 &Context->Idents.get("__va_list_tag"));
6069 VaListTagDecl->startDefinition();
6070
6071 const size_t NumFields = 4;
6072 QualType FieldTypes[NumFields];
6073 const char *FieldNames[NumFields];
6074
6075 // long __gpr;
6076 FieldTypes[0] = Context->LongTy;
6077 FieldNames[0] = "__gpr";
6078
6079 // long __fpr;
6080 FieldTypes[1] = Context->LongTy;
6081 FieldNames[1] = "__fpr";
6082
6083 // void *__overflow_arg_area;
6084 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6085 FieldNames[2] = "__overflow_arg_area";
6086
6087 // void *__reg_save_area;
6088 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6089 FieldNames[3] = "__reg_save_area";
6090
6091 // Create fields
6092 for (unsigned i = 0; i < NumFields; ++i) {
6093 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6094 VaListTagDecl,
6095 SourceLocation(),
6096 SourceLocation(),
6097 &Context->Idents.get(FieldNames[i]),
6098 FieldTypes[i], /*TInfo=*/0,
6099 /*BitWidth=*/0,
6100 /*Mutable=*/false,
6101 ICIS_NoInit);
6102 Field->setAccess(AS_public);
6103 VaListTagDecl->addDecl(Field);
6104 }
6105 VaListTagDecl->completeDefinition();
6106 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6107 Context->VaListTagTy = VaListTagType;
6108
6109 // } __va_list_tag;
6110 TypedefDecl *VaListTagTypedefDecl
6111 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6112 Context->getTranslationUnitDecl(),
6113 SourceLocation(), SourceLocation(),
6114 &Context->Idents.get("__va_list_tag"),
6115 Context->getTrivialTypeSourceInfo(VaListTagType));
6116 QualType VaListTagTypedefType =
6117 Context->getTypedefType(VaListTagTypedefDecl);
6118
6119 // typedef __va_list_tag __builtin_va_list[1];
6120 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6121 QualType VaListTagArrayType
6122 = Context->getConstantArrayType(VaListTagTypedefType,
6123 Size, ArrayType::Normal,0);
6124 TypeSourceInfo *TInfo
6125 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
6126 TypedefDecl *VaListTypedefDecl
6127 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6128 Context->getTranslationUnitDecl(),
6129 SourceLocation(), SourceLocation(),
6130 &Context->Idents.get("__builtin_va_list"),
6131 TInfo);
6132
6133 return VaListTypedefDecl;
6134}
6135
Meador Ingec5613b22012-06-16 03:34:49 +00006136static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6137 TargetInfo::BuiltinVaListKind Kind) {
6138 switch (Kind) {
6139 case TargetInfo::CharPtrBuiltinVaList:
6140 return CreateCharPtrBuiltinVaListDecl(Context);
6141 case TargetInfo::VoidPtrBuiltinVaList:
6142 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northoverc264e162013-01-31 12:13:10 +00006143 case TargetInfo::AArch64ABIBuiltinVaList:
6144 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Ingec5613b22012-06-16 03:34:49 +00006145 case TargetInfo::PowerABIBuiltinVaList:
6146 return CreatePowerABIBuiltinVaListDecl(Context);
6147 case TargetInfo::X86_64ABIBuiltinVaList:
6148 return CreateX86_64ABIBuiltinVaListDecl(Context);
6149 case TargetInfo::PNaClABIBuiltinVaList:
6150 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chieneae5a8202012-10-10 06:56:20 +00006151 case TargetInfo::AAPCSABIBuiltinVaList:
6152 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigandb8409212013-05-06 16:26:41 +00006153 case TargetInfo::SystemZBuiltinVaList:
6154 return CreateSystemZBuiltinVaListDecl(Context);
Meador Ingec5613b22012-06-16 03:34:49 +00006155 }
6156
6157 llvm_unreachable("Unhandled __builtin_va_list type kind");
6158}
6159
6160TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
6161 if (!BuiltinVaListDecl)
6162 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
6163
6164 return BuiltinVaListDecl;
6165}
6166
Meador Ingefb40e3f2012-07-01 15:57:25 +00006167QualType ASTContext::getVaListTagType() const {
6168 // Force the creation of VaListTagTy by building the __builtin_va_list
6169 // declaration.
6170 if (VaListTagTy.isNull())
6171 (void) getBuiltinVaListDecl();
6172
6173 return VaListTagTy;
6174}
6175
Ted Kremeneka526c5c2008-01-07 19:49:32 +00006176void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00006177 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00006178 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00006179
Ted Kremeneka526c5c2008-01-07 19:49:32 +00006180 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00006181}
6182
John McCall0bd6feb2009-12-02 08:04:21 +00006183/// \brief Retrieve the template name that corresponds to a non-empty
6184/// lookup.
Jay Foad4ba2a172011-01-12 09:06:06 +00006185TemplateName
6186ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6187 UnresolvedSetIterator End) const {
John McCall0bd6feb2009-12-02 08:04:21 +00006188 unsigned size = End - Begin;
6189 assert(size > 1 && "set is not overloaded!");
6190
6191 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6192 size * sizeof(FunctionTemplateDecl*));
6193 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6194
6195 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00006196 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00006197 NamedDecl *D = *I;
6198 assert(isa<FunctionTemplateDecl>(D) ||
6199 (isa<UsingShadowDecl>(D) &&
6200 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6201 *Storage++ = D;
6202 }
6203
6204 return TemplateName(OT);
6205}
6206
Douglas Gregor7532dc62009-03-30 22:58:21 +00006207/// \brief Retrieve the template name that represents a qualified
6208/// template name such as \c std::vector.
Jay Foad4ba2a172011-01-12 09:06:06 +00006209TemplateName
6210ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6211 bool TemplateKeyword,
6212 TemplateDecl *Template) const {
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00006213 assert(NNS && "Missing nested-name-specifier in qualified template name");
6214
Douglas Gregor789b1f62010-02-04 18:10:26 +00006215 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00006216 llvm::FoldingSetNodeID ID;
6217 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6218
6219 void *InsertPos = 0;
6220 QualifiedTemplateName *QTN =
6221 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6222 if (!QTN) {
Richard Smith2f47cab2012-08-16 01:19:31 +00006223 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6224 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregor7532dc62009-03-30 22:58:21 +00006225 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6226 }
6227
6228 return TemplateName(QTN);
6229}
6230
6231/// \brief Retrieve the template name that represents a dependent
6232/// template name such as \c MetaFun::template apply.
Jay Foad4ba2a172011-01-12 09:06:06 +00006233TemplateName
6234ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6235 const IdentifierInfo *Name) const {
Mike Stump1eb44332009-09-09 15:08:12 +00006236 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00006237 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00006238
6239 llvm::FoldingSetNodeID ID;
6240 DependentTemplateName::Profile(ID, NNS, Name);
6241
6242 void *InsertPos = 0;
6243 DependentTemplateName *QTN =
6244 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6245
6246 if (QTN)
6247 return TemplateName(QTN);
6248
6249 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6250 if (CanonNNS == NNS) {
Richard Smith2f47cab2012-08-16 01:19:31 +00006251 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6252 DependentTemplateName(NNS, Name);
Douglas Gregor7532dc62009-03-30 22:58:21 +00006253 } else {
6254 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smith2f47cab2012-08-16 01:19:31 +00006255 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6256 DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00006257 DependentTemplateName *CheckQTN =
6258 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6259 assert(!CheckQTN && "Dependent type name canonicalization broken");
6260 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00006261 }
6262
6263 DependentTemplateNames.InsertNode(QTN, InsertPos);
6264 return TemplateName(QTN);
6265}
6266
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006267/// \brief Retrieve the template name that represents a dependent
6268/// template name such as \c MetaFun::template operator+.
6269TemplateName
6270ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00006271 OverloadedOperatorKind Operator) const {
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006272 assert((!NNS || NNS->isDependent()) &&
6273 "Nested name specifier must be dependent");
6274
6275 llvm::FoldingSetNodeID ID;
6276 DependentTemplateName::Profile(ID, NNS, Operator);
6277
6278 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00006279 DependentTemplateName *QTN
6280 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006281
6282 if (QTN)
6283 return TemplateName(QTN);
6284
6285 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6286 if (CanonNNS == NNS) {
Richard Smith2f47cab2012-08-16 01:19:31 +00006287 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6288 DependentTemplateName(NNS, Operator);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006289 } else {
6290 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smith2f47cab2012-08-16 01:19:31 +00006291 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6292 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00006293
6294 DependentTemplateName *CheckQTN
6295 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6296 assert(!CheckQTN && "Dependent template name canonicalization broken");
6297 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006298 }
6299
6300 DependentTemplateNames.InsertNode(QTN, InsertPos);
6301 return TemplateName(QTN);
6302}
6303
Douglas Gregor1aee05d2011-01-15 06:45:20 +00006304TemplateName
John McCall14606042011-06-30 08:33:18 +00006305ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6306 TemplateName replacement) const {
6307 llvm::FoldingSetNodeID ID;
6308 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
6309
6310 void *insertPos = 0;
6311 SubstTemplateTemplateParmStorage *subst
6312 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6313
6314 if (!subst) {
6315 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6316 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6317 }
6318
6319 return TemplateName(subst);
6320}
6321
6322TemplateName
Douglas Gregor1aee05d2011-01-15 06:45:20 +00006323ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6324 const TemplateArgument &ArgPack) const {
6325 ASTContext &Self = const_cast<ASTContext &>(*this);
6326 llvm::FoldingSetNodeID ID;
6327 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
6328
6329 void *InsertPos = 0;
6330 SubstTemplateTemplateParmPackStorage *Subst
6331 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6332
6333 if (!Subst) {
John McCall14606042011-06-30 08:33:18 +00006334 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor1aee05d2011-01-15 06:45:20 +00006335 ArgPack.pack_size(),
6336 ArgPack.pack_begin());
6337 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6338 }
6339
6340 return TemplateName(Subst);
6341}
6342
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006343/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00006344/// TargetInfo, produce the corresponding type. The unsigned @p Type
6345/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00006346CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006347 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00006348 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006349 case TargetInfo::SignedShort: return ShortTy;
6350 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6351 case TargetInfo::SignedInt: return IntTy;
6352 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6353 case TargetInfo::SignedLong: return LongTy;
6354 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6355 case TargetInfo::SignedLongLong: return LongLongTy;
6356 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6357 }
6358
David Blaikieb219cfc2011-09-23 05:06:16 +00006359 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006360}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00006361
6362//===----------------------------------------------------------------------===//
6363// Type Predicates.
6364//===----------------------------------------------------------------------===//
6365
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00006366/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6367/// garbage collection attribute.
6368///
John McCallae278a32011-01-12 00:34:59 +00006369Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikie4e4d0842012-03-11 07:00:24 +00006370 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCallae278a32011-01-12 00:34:59 +00006371 return Qualifiers::GCNone;
6372
David Blaikie4e4d0842012-03-11 07:00:24 +00006373 assert(getLangOpts().ObjC1);
John McCallae278a32011-01-12 00:34:59 +00006374 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6375
6376 // Default behaviour under objective-C's gc is for ObjC pointers
6377 // (or pointers to them) be treated as though they were declared
6378 // as __strong.
6379 if (GCAttrs == Qualifiers::GCNone) {
6380 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6381 return Qualifiers::Strong;
6382 else if (Ty->isPointerType())
6383 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6384 } else {
6385 // It's not valid to set GC attributes on anything that isn't a
6386 // pointer.
6387#ifndef NDEBUG
6388 QualType CT = Ty->getCanonicalTypeInternal();
6389 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6390 CT = AT->getElementType();
6391 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6392#endif
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00006393 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00006394 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00006395}
6396
Chris Lattner6ac46a42008-04-07 06:51:04 +00006397//===----------------------------------------------------------------------===//
6398// Type Compatibility Testing
6399//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00006400
Mike Stump1eb44332009-09-09 15:08:12 +00006401/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00006402/// compatible.
6403static bool areCompatVectorTypes(const VectorType *LHS,
6404 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00006405 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00006406 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00006407 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00006408}
6409
Douglas Gregor255210e2010-08-06 10:14:59 +00006410bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6411 QualType SecondVec) {
6412 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6413 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6414
6415 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6416 return true;
6417
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00006418 // Treat Neon vector types and most AltiVec vector types as if they are the
6419 // equivalent GCC vector types.
Douglas Gregor255210e2010-08-06 10:14:59 +00006420 const VectorType *First = FirstVec->getAs<VectorType>();
6421 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00006422 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor255210e2010-08-06 10:14:59 +00006423 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00006424 First->getVectorKind() != VectorType::AltiVecPixel &&
6425 First->getVectorKind() != VectorType::AltiVecBool &&
6426 Second->getVectorKind() != VectorType::AltiVecPixel &&
6427 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor255210e2010-08-06 10:14:59 +00006428 return true;
6429
6430 return false;
6431}
6432
Steve Naroff4084c302009-07-23 01:01:38 +00006433//===----------------------------------------------------------------------===//
6434// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6435//===----------------------------------------------------------------------===//
6436
6437/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6438/// inheritance hierarchy of 'rProto'.
Jay Foad4ba2a172011-01-12 09:06:06 +00006439bool
6440ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6441 ObjCProtocolDecl *rProto) const {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00006442 if (declaresSameEntity(lProto, rProto))
Steve Naroff4084c302009-07-23 01:01:38 +00006443 return true;
6444 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
6445 E = rProto->protocol_end(); PI != E; ++PI)
6446 if (ProtocolCompatibleWithProtocol(lProto, *PI))
6447 return true;
6448 return false;
6449}
6450
Dmitri Gribenko4c3b8a32012-08-28 02:49:14 +00006451/// QualifiedIdConformsQualifiedId - compare id<pr,...> with id<pr1,...>
Steve Naroff4084c302009-07-23 01:01:38 +00006452/// return true if lhs's protocols conform to rhs's protocol; false
6453/// otherwise.
6454bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
6455 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
6456 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
6457 return false;
6458}
6459
Dmitri Gribenko4c3b8a32012-08-28 02:49:14 +00006460/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6461/// Class<pr1, ...>.
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00006462bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6463 QualType rhs) {
6464 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6465 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6466 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6467
6468 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6469 E = lhsQID->qual_end(); I != E; ++I) {
6470 bool match = false;
6471 ObjCProtocolDecl *lhsProto = *I;
6472 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6473 E = rhsOPT->qual_end(); J != E; ++J) {
6474 ObjCProtocolDecl *rhsProto = *J;
6475 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6476 match = true;
6477 break;
6478 }
6479 }
6480 if (!match)
6481 return false;
6482 }
6483 return true;
6484}
6485
Steve Naroff4084c302009-07-23 01:01:38 +00006486/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6487/// ObjCQualifiedIDType.
6488bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6489 bool compare) {
6490 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00006491 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00006492 lhs->isObjCIdType() || lhs->isObjCClassType())
6493 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00006494 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00006495 rhs->isObjCIdType() || rhs->isObjCClassType())
6496 return true;
6497
6498 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00006499 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00006500
Steve Naroff4084c302009-07-23 01:01:38 +00006501 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006502
Steve Naroff4084c302009-07-23 01:01:38 +00006503 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006504 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00006505 // make sure we check the class hierarchy.
6506 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6507 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6508 E = lhsQID->qual_end(); I != E; ++I) {
6509 // when comparing an id<P> on lhs with a static type on rhs,
6510 // see if static class implements all of id's protocols, directly or
6511 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00006512 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00006513 return false;
6514 }
6515 }
6516 // If there are no qualifiers and no interface, we have an 'id'.
6517 return true;
6518 }
Mike Stump1eb44332009-09-09 15:08:12 +00006519 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00006520 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6521 E = lhsQID->qual_end(); I != E; ++I) {
6522 ObjCProtocolDecl *lhsProto = *I;
6523 bool match = false;
6524
6525 // when comparing an id<P> on lhs with a static type on rhs,
6526 // see if static class implements all of id's protocols, directly or
6527 // through its super class and categories.
6528 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6529 E = rhsOPT->qual_end(); J != E; ++J) {
6530 ObjCProtocolDecl *rhsProto = *J;
6531 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6532 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6533 match = true;
6534 break;
6535 }
6536 }
Mike Stump1eb44332009-09-09 15:08:12 +00006537 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00006538 // make sure we check the class hierarchy.
6539 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6540 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6541 E = lhsQID->qual_end(); I != E; ++I) {
6542 // when comparing an id<P> on lhs with a static type on rhs,
6543 // see if static class implements all of id's protocols, directly or
6544 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00006545 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00006546 match = true;
6547 break;
6548 }
6549 }
6550 }
6551 if (!match)
6552 return false;
6553 }
Mike Stump1eb44332009-09-09 15:08:12 +00006554
Steve Naroff4084c302009-07-23 01:01:38 +00006555 return true;
6556 }
Mike Stump1eb44332009-09-09 15:08:12 +00006557
Steve Naroff4084c302009-07-23 01:01:38 +00006558 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6559 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6560
Mike Stump1eb44332009-09-09 15:08:12 +00006561 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00006562 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006563 // If both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00006564 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
6565 E = lhsOPT->qual_end(); I != E; ++I) {
6566 ObjCProtocolDecl *lhsProto = *I;
6567 bool match = false;
6568
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006569 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff4084c302009-07-23 01:01:38 +00006570 // see if static class implements all of id's protocols, directly or
6571 // through its super class and categories.
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006572 // First, lhs protocols in the qualifier list must be found, direct
6573 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff4084c302009-07-23 01:01:38 +00006574 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6575 E = rhsQID->qual_end(); J != E; ++J) {
6576 ObjCProtocolDecl *rhsProto = *J;
6577 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6578 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6579 match = true;
6580 break;
6581 }
6582 }
6583 if (!match)
6584 return false;
6585 }
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006586
6587 // Static class's protocols, or its super class or category protocols
6588 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6589 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6590 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6591 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6592 // This is rather dubious but matches gcc's behavior. If lhs has
6593 // no type qualifier and its class has no static protocol(s)
6594 // assume that it is mismatch.
6595 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6596 return false;
6597 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6598 LHSInheritedProtocols.begin(),
6599 E = LHSInheritedProtocols.end(); I != E; ++I) {
6600 bool match = false;
6601 ObjCProtocolDecl *lhsProto = (*I);
6602 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6603 E = rhsQID->qual_end(); J != E; ++J) {
6604 ObjCProtocolDecl *rhsProto = *J;
6605 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6606 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6607 match = true;
6608 break;
6609 }
6610 }
6611 if (!match)
6612 return false;
6613 }
6614 }
Steve Naroff4084c302009-07-23 01:01:38 +00006615 return true;
6616 }
6617 return false;
6618}
6619
Eli Friedman3d815e72008-08-22 00:56:42 +00006620/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00006621/// compatible for assignment from RHS to LHS. This handles validation of any
6622/// protocol qualifiers on the LHS or RHS.
6623///
Steve Naroff14108da2009-07-10 23:34:53 +00006624bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6625 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00006626 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6627 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6628
Steve Naroffde2e22d2009-07-15 18:40:39 +00006629 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00006630 if (LHS->isObjCUnqualifiedIdOrClass() ||
6631 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00006632 return true;
6633
John McCallc12c5bb2010-05-15 11:32:37 +00006634 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00006635 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6636 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00006637 false);
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00006638
6639 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6640 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6641 QualType(RHSOPT,0));
6642
John McCallc12c5bb2010-05-15 11:32:37 +00006643 // If we have 2 user-defined types, fall into that path.
6644 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00006645 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00006646
Steve Naroff4084c302009-07-23 01:01:38 +00006647 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00006648}
6649
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006650/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00006651/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006652/// arguments in block literals. When passed as arguments, passing 'A*' where
6653/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6654/// not OK. For the return type, the opposite is not OK.
6655bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6656 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006657 const ObjCObjectPointerType *RHSOPT,
6658 bool BlockReturnType) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00006659 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006660 return true;
6661
6662 if (LHSOPT->isObjCBuiltinType()) {
6663 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6664 }
6665
Fariborz Jahaniana9834482010-04-06 17:23:39 +00006666 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006667 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6668 QualType(RHSOPT,0),
6669 false);
6670
6671 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6672 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6673 if (LHS && RHS) { // We have 2 user-defined types.
6674 if (LHS != RHS) {
6675 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006676 return BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006677 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006678 return !BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006679 }
6680 else
6681 return true;
6682 }
6683 return false;
6684}
6685
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006686/// getIntersectionOfProtocols - This routine finds the intersection of set
6687/// of protocols inherited from two distinct objective-c pointer objects.
6688/// It is used to build composite qualifier list of the composite type of
6689/// the conditional expression involving two objective-c pointer objects.
6690static
6691void getIntersectionOfProtocols(ASTContext &Context,
6692 const ObjCObjectPointerType *LHSOPT,
6693 const ObjCObjectPointerType *RHSOPT,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006694 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006695
John McCallc12c5bb2010-05-15 11:32:37 +00006696 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6697 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6698 assert(LHS->getInterface() && "LHS must have an interface base");
6699 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006700
6701 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6702 unsigned LHSNumProtocols = LHS->getNumProtocols();
6703 if (LHSNumProtocols > 0)
6704 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6705 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006706 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006707 Context.CollectInheritedProtocols(LHS->getInterface(),
6708 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006709 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6710 LHSInheritedProtocols.end());
6711 }
6712
6713 unsigned RHSNumProtocols = RHS->getNumProtocols();
6714 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00006715 ObjCProtocolDecl **RHSProtocols =
6716 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006717 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6718 if (InheritedProtocolSet.count(RHSProtocols[i]))
6719 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier30601782011-08-17 23:08:45 +00006720 } else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006721 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006722 Context.CollectInheritedProtocols(RHS->getInterface(),
6723 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006724 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6725 RHSInheritedProtocols.begin(),
6726 E = RHSInheritedProtocols.end(); I != E; ++I)
6727 if (InheritedProtocolSet.count((*I)))
6728 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006729 }
6730}
6731
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006732/// areCommonBaseCompatible - Returns common base class of the two classes if
6733/// one found. Note that this is O'2 algorithm. But it will be called as the
6734/// last type comparison in a ?-exp of ObjC pointer types before a
6735/// warning is issued. So, its invokation is extremely rare.
6736QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00006737 const ObjCObjectPointerType *Lptr,
6738 const ObjCObjectPointerType *Rptr) {
6739 const ObjCObjectType *LHS = Lptr->getObjectType();
6740 const ObjCObjectType *RHS = Rptr->getObjectType();
6741 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6742 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor60ef3082011-12-15 00:29:59 +00006743 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006744 return QualType();
6745
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00006746 do {
John McCallc12c5bb2010-05-15 11:32:37 +00006747 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006748 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006749 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006750 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6751
6752 QualType Result = QualType(LHS, 0);
6753 if (!Protocols.empty())
6754 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6755 Result = getObjCObjectPointerType(Result);
6756 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006757 }
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00006758 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006759
6760 return QualType();
6761}
6762
John McCallc12c5bb2010-05-15 11:32:37 +00006763bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6764 const ObjCObjectType *RHS) {
6765 assert(LHS->getInterface() && "LHS is not an interface type");
6766 assert(RHS->getInterface() && "RHS is not an interface type");
6767
Chris Lattner6ac46a42008-04-07 06:51:04 +00006768 // Verify that the base decls are compatible: the RHS must be a subclass of
6769 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00006770 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00006771 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006772
Chris Lattner6ac46a42008-04-07 06:51:04 +00006773 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6774 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00006775 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00006776 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00006777
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006778 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6779 // more detailed analysis is required.
6780 if (RHS->getNumProtocols() == 0) {
6781 // OK, if LHS is a superclass of RHS *and*
6782 // this superclass is assignment compatible with LHS.
6783 // false otherwise.
Fariborz Jahanian627788c2011-04-12 16:34:14 +00006784 bool IsSuperClass =
6785 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6786 if (IsSuperClass) {
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006787 // OK if conversion of LHS to SuperClass results in narrowing of types
6788 // ; i.e., SuperClass may implement at least one of the protocols
6789 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6790 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6791 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian627788c2011-04-12 16:34:14 +00006792 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006793 // If super class has no protocols, it is not a match.
6794 if (SuperClassInheritedProtocols.empty())
6795 return false;
6796
6797 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6798 LHSPE = LHS->qual_end();
6799 LHSPI != LHSPE; LHSPI++) {
6800 bool SuperImplementsProtocol = false;
6801 ObjCProtocolDecl *LHSProto = (*LHSPI);
6802
6803 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6804 SuperClassInheritedProtocols.begin(),
6805 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6806 ObjCProtocolDecl *SuperClassProto = (*I);
6807 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6808 SuperImplementsProtocol = true;
6809 break;
6810 }
6811 }
6812 if (!SuperImplementsProtocol)
6813 return false;
6814 }
6815 return true;
6816 }
6817 return false;
6818 }
Mike Stump1eb44332009-09-09 15:08:12 +00006819
John McCallc12c5bb2010-05-15 11:32:37 +00006820 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6821 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006822 LHSPI != LHSPE; LHSPI++) {
6823 bool RHSImplementsProtocol = false;
6824
6825 // If the RHS doesn't implement the protocol on the left, the types
6826 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00006827 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6828 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00006829 RHSPI != RHSPE; RHSPI++) {
6830 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006831 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00006832 break;
6833 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006834 }
6835 // FIXME: For better diagnostics, consider passing back the protocol name.
6836 if (!RHSImplementsProtocol)
6837 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00006838 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006839 // The RHS implements all protocols listed on the LHS.
6840 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00006841}
6842
Steve Naroff389bf462009-02-12 17:52:19 +00006843bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6844 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00006845 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6846 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00006847
Steve Naroff14108da2009-07-10 23:34:53 +00006848 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00006849 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00006850
6851 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6852 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00006853}
6854
Douglas Gregor569c3162010-08-07 11:51:51 +00006855bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6856 return canAssignObjCInterfaces(
6857 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6858 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6859}
6860
Mike Stump1eb44332009-09-09 15:08:12 +00006861/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00006862/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00006863/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00006864/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor447234d2010-07-29 15:18:02 +00006865bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6866 bool CompareUnqualified) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006867 if (getLangOpts().CPlusPlus)
Douglas Gregor0e709ab2010-02-03 21:02:30 +00006868 return hasSameType(LHS, RHS);
6869
Douglas Gregor447234d2010-07-29 15:18:02 +00006870 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman3d815e72008-08-22 00:56:42 +00006871}
6872
Fariborz Jahanianc286f382011-07-12 22:05:16 +00006873bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanian82378392011-07-12 23:20:13 +00006874 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc286f382011-07-12 22:05:16 +00006875}
6876
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006877bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6878 return !mergeTypes(LHS, RHS, true).isNull();
6879}
6880
Peter Collingbourne48466752010-10-24 18:30:18 +00006881/// mergeTransparentUnionType - if T is a transparent union type and a member
6882/// of T is compatible with SubType, return the merged type, else return
6883/// QualType()
6884QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6885 bool OfBlockPointer,
6886 bool Unqualified) {
6887 if (const RecordType *UT = T->getAsUnionType()) {
6888 RecordDecl *UD = UT->getDecl();
6889 if (UD->hasAttr<TransparentUnionAttr>()) {
6890 for (RecordDecl::field_iterator it = UD->field_begin(),
6891 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbournef91d7572010-12-02 21:00:06 +00006892 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00006893 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6894 if (!MT.isNull())
6895 return MT;
6896 }
6897 }
6898 }
6899
6900 return QualType();
6901}
6902
6903/// mergeFunctionArgumentTypes - merge two types which appear as function
6904/// argument types
6905QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
6906 bool OfBlockPointer,
6907 bool Unqualified) {
6908 // GNU extension: two types are compatible if they appear as a function
6909 // argument, one of the types is a transparent union type and the other
6910 // type is compatible with a union member
6911 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6912 Unqualified);
6913 if (!lmerge.isNull())
6914 return lmerge;
6915
6916 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6917 Unqualified);
6918 if (!rmerge.isNull())
6919 return rmerge;
6920
6921 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6922}
6923
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006924QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor447234d2010-07-29 15:18:02 +00006925 bool OfBlockPointer,
6926 bool Unqualified) {
John McCall183700f2009-09-21 23:43:11 +00006927 const FunctionType *lbase = lhs->getAs<FunctionType>();
6928 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00006929 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6930 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00006931 bool allLTypes = true;
6932 bool allRTypes = true;
6933
6934 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006935 QualType retType;
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00006936 if (OfBlockPointer) {
6937 QualType RHS = rbase->getResultType();
6938 QualType LHS = lbase->getResultType();
6939 bool UnqualifiedResult = Unqualified;
6940 if (!UnqualifiedResult)
6941 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006942 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00006943 }
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006944 else
John McCall8cc246c2010-12-15 01:06:38 +00006945 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6946 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006947 if (retType.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006948
6949 if (Unqualified)
6950 retType = retType.getUnqualifiedType();
6951
6952 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6953 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6954 if (Unqualified) {
6955 LRetType = LRetType.getUnqualifiedType();
6956 RRetType = RRetType.getUnqualifiedType();
6957 }
6958
6959 if (getCanonicalType(retType) != LRetType)
Chris Lattner61710852008-10-05 17:34:18 +00006960 allLTypes = false;
Douglas Gregor447234d2010-07-29 15:18:02 +00006961 if (getCanonicalType(retType) != RRetType)
Chris Lattner61710852008-10-05 17:34:18 +00006962 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00006963
Daniel Dunbar6a15c852010-04-28 16:20:58 +00006964 // FIXME: double check this
6965 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6966 // rbase->getRegParmAttr() != 0 &&
6967 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00006968 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6969 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8cc246c2010-12-15 01:06:38 +00006970
Douglas Gregorab8bbf42010-01-18 17:14:39 +00006971 // Compatible functions must have compatible calling conventions
John McCall8cc246c2010-12-15 01:06:38 +00006972 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00006973 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00006974
John McCall8cc246c2010-12-15 01:06:38 +00006975 // Regparm is part of the calling convention.
Eli Friedmana49218e2011-04-09 08:18:08 +00006976 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6977 return QualType();
John McCall8cc246c2010-12-15 01:06:38 +00006978 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6979 return QualType();
6980
John McCallf85e1932011-06-15 23:02:42 +00006981 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6982 return QualType();
6983
John McCall8cc246c2010-12-15 01:06:38 +00006984 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6985 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8cc246c2010-12-15 01:06:38 +00006986
Rafael Espindola8b8a09e2012-11-29 16:09:03 +00006987 if (lbaseInfo.getNoReturn() != NoReturn)
6988 allLTypes = false;
6989 if (rbaseInfo.getNoReturn() != NoReturn)
6990 allRTypes = false;
6991
John McCallf85e1932011-06-15 23:02:42 +00006992 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00006993
Eli Friedman3d815e72008-08-22 00:56:42 +00006994 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00006995 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6996 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00006997 unsigned lproto_nargs = lproto->getNumArgs();
6998 unsigned rproto_nargs = rproto->getNumArgs();
6999
7000 // Compatible functions must have the same number of arguments
7001 if (lproto_nargs != rproto_nargs)
7002 return QualType();
7003
7004 // Variadic and non-variadic functions aren't compatible
7005 if (lproto->isVariadic() != rproto->isVariadic())
7006 return QualType();
7007
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00007008 if (lproto->getTypeQuals() != rproto->getTypeQuals())
7009 return QualType();
7010
Fariborz Jahanian78213e42011-09-28 21:52:05 +00007011 if (LangOpts.ObjCAutoRefCount &&
7012 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
7013 return QualType();
7014
Eli Friedman3d815e72008-08-22 00:56:42 +00007015 // Check argument compatibility
Chris Lattner5f9e2722011-07-23 10:55:15 +00007016 SmallVector<QualType, 10> types;
Eli Friedman3d815e72008-08-22 00:56:42 +00007017 for (unsigned i = 0; i < lproto_nargs; i++) {
7018 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
7019 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00007020 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
7021 OfBlockPointer,
7022 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00007023 if (argtype.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00007024
7025 if (Unqualified)
7026 argtype = argtype.getUnqualifiedType();
7027
Eli Friedman3d815e72008-08-22 00:56:42 +00007028 types.push_back(argtype);
Douglas Gregor447234d2010-07-29 15:18:02 +00007029 if (Unqualified) {
7030 largtype = largtype.getUnqualifiedType();
7031 rargtype = rargtype.getUnqualifiedType();
7032 }
7033
Chris Lattner61710852008-10-05 17:34:18 +00007034 if (getCanonicalType(argtype) != getCanonicalType(largtype))
7035 allLTypes = false;
7036 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
7037 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00007038 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00007039
Eli Friedman3d815e72008-08-22 00:56:42 +00007040 if (allLTypes) return lhs;
7041 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00007042
7043 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7044 EPI.ExtInfo = einfo;
Jordan Rosebea522f2013-03-08 21:51:21 +00007045 return getFunctionType(retType, types, EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00007046 }
7047
7048 if (lproto) allRTypes = false;
7049 if (rproto) allLTypes = false;
7050
Douglas Gregor72564e72009-02-26 23:50:07 +00007051 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00007052 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00007053 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00007054 if (proto->isVariadic()) return QualType();
7055 // Check that the types are compatible with the types that
7056 // would result from default argument promotions (C99 6.7.5.3p15).
7057 // The only types actually affected are promotable integer
7058 // types and floats, which would be passed as a different
7059 // type depending on whether the prototype is visible.
7060 unsigned proto_nargs = proto->getNumArgs();
7061 for (unsigned i = 0; i < proto_nargs; ++i) {
7062 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00007063
Eli Friedmanc586d5d2012-08-30 00:44:15 +00007064 // Look at the converted type of enum types, since that is the type used
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00007065 // to pass enum values.
Eli Friedmanc586d5d2012-08-30 00:44:15 +00007066 if (const EnumType *Enum = argTy->getAs<EnumType>()) {
7067 argTy = Enum->getDecl()->getIntegerType();
7068 if (argTy.isNull())
7069 return QualType();
7070 }
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00007071
Eli Friedman3d815e72008-08-22 00:56:42 +00007072 if (argTy->isPromotableIntegerType() ||
7073 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
7074 return QualType();
7075 }
7076
7077 if (allLTypes) return lhs;
7078 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00007079
7080 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7081 EPI.ExtInfo = einfo;
Reid Kleckner0567a792013-06-10 20:51:09 +00007082 return getFunctionType(retType, proto->getArgTypes(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00007083 }
7084
7085 if (allLTypes) return lhs;
7086 if (allRTypes) return rhs;
John McCall8cc246c2010-12-15 01:06:38 +00007087 return getFunctionNoProtoType(retType, einfo);
Eli Friedman3d815e72008-08-22 00:56:42 +00007088}
7089
John McCallb9da7132013-03-21 00:10:07 +00007090/// Given that we have an enum type and a non-enum type, try to merge them.
7091static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7092 QualType other, bool isBlockReturnType) {
7093 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7094 // a signed integer type, or an unsigned integer type.
7095 // Compatibility is based on the underlying type, not the promotion
7096 // type.
7097 QualType underlyingType = ET->getDecl()->getIntegerType();
7098 if (underlyingType.isNull()) return QualType();
7099 if (Context.hasSameType(underlyingType, other))
7100 return other;
7101
7102 // In block return types, we're more permissive and accept any
7103 // integral type of the same size.
7104 if (isBlockReturnType && other->isIntegerType() &&
7105 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7106 return other;
7107
7108 return QualType();
7109}
7110
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00007111QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor447234d2010-07-29 15:18:02 +00007112 bool OfBlockPointer,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00007113 bool Unqualified, bool BlockReturnType) {
Bill Wendling43d69752007-12-03 07:33:35 +00007114 // C++ [expr]: If an expression initially has the type "reference to T", the
7115 // type is adjusted to "T" prior to any further analysis, the expression
7116 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00007117 // expression is an lvalue unless the reference is an rvalue reference and
7118 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00007119 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7120 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor447234d2010-07-29 15:18:02 +00007121
7122 if (Unqualified) {
7123 LHS = LHS.getUnqualifiedType();
7124 RHS = RHS.getUnqualifiedType();
7125 }
Douglas Gregor0e709ab2010-02-03 21:02:30 +00007126
Eli Friedman3d815e72008-08-22 00:56:42 +00007127 QualType LHSCan = getCanonicalType(LHS),
7128 RHSCan = getCanonicalType(RHS);
7129
7130 // If two types are identical, they are compatible.
7131 if (LHSCan == RHSCan)
7132 return LHS;
7133
John McCall0953e762009-09-24 19:53:00 +00007134 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00007135 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7136 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00007137 if (LQuals != RQuals) {
7138 // If any of these qualifiers are different, we have a type
7139 // mismatch.
7140 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCallf85e1932011-06-15 23:02:42 +00007141 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7142 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall0953e762009-09-24 19:53:00 +00007143 return QualType();
7144
7145 // Exactly one GC qualifier difference is allowed: __strong is
7146 // okay if the other type has no GC qualifier but is an Objective
7147 // C object pointer (i.e. implicitly strong by default). We fix
7148 // this by pretending that the unqualified type was actually
7149 // qualified __strong.
7150 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7151 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7152 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7153
7154 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7155 return QualType();
7156
7157 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7158 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7159 }
7160 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7161 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7162 }
Eli Friedman3d815e72008-08-22 00:56:42 +00007163 return QualType();
John McCall0953e762009-09-24 19:53:00 +00007164 }
7165
7166 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00007167
Eli Friedman852d63b2009-06-01 01:22:52 +00007168 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7169 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00007170
Chris Lattner1adb8832008-01-14 05:45:46 +00007171 // We want to consider the two function types to be the same for these
7172 // comparisons, just force one to the other.
7173 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7174 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00007175
7176 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00007177 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7178 LHSClass = Type::ConstantArray;
7179 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7180 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00007181
John McCallc12c5bb2010-05-15 11:32:37 +00007182 // ObjCInterfaces are just specialized ObjCObjects.
7183 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7184 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7185
Nate Begeman213541a2008-04-18 23:10:10 +00007186 // Canonicalize ExtVector -> Vector.
7187 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7188 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00007189
Chris Lattnera36a61f2008-04-07 05:43:21 +00007190 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00007191 if (LHSClass != RHSClass) {
John McCallb9da7132013-03-21 00:10:07 +00007192 // Note that we only have special rules for turning block enum
7193 // returns into block int returns, not vice-versa.
John McCall183700f2009-09-21 23:43:11 +00007194 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCallb9da7132013-03-21 00:10:07 +00007195 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmanbab96962008-02-12 08:46:17 +00007196 }
John McCall183700f2009-09-21 23:43:11 +00007197 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCallb9da7132013-03-21 00:10:07 +00007198 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmanbab96962008-02-12 08:46:17 +00007199 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00007200 // allow block pointer type to match an 'id' type.
Fariborz Jahanian41963632012-01-26 17:08:50 +00007201 if (OfBlockPointer && !BlockReturnType) {
7202 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7203 return LHS;
7204 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7205 return RHS;
7206 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00007207
Eli Friedman3d815e72008-08-22 00:56:42 +00007208 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00007209 }
Eli Friedman3d815e72008-08-22 00:56:42 +00007210
Steve Naroff4a746782008-01-09 22:43:08 +00007211 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00007212 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00007213#define TYPE(Class, Base)
7214#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00007215#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00007216#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7217#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7218#include "clang/AST/TypeNodes.def"
David Blaikieb219cfc2011-09-23 05:06:16 +00007219 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregor72564e72009-02-26 23:50:07 +00007220
Richard Smithdc7a4f52013-04-30 13:56:41 +00007221 case Type::Auto:
Sebastian Redl7c80bd62009-03-16 23:22:08 +00007222 case Type::LValueReference:
7223 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00007224 case Type::MemberPointer:
David Blaikieb219cfc2011-09-23 05:06:16 +00007225 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregor72564e72009-02-26 23:50:07 +00007226
John McCallc12c5bb2010-05-15 11:32:37 +00007227 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00007228 case Type::IncompleteArray:
7229 case Type::VariableArray:
7230 case Type::FunctionProto:
7231 case Type::ExtVector:
David Blaikieb219cfc2011-09-23 05:06:16 +00007232 llvm_unreachable("Types are eliminated above");
Douglas Gregor72564e72009-02-26 23:50:07 +00007233
Chris Lattner1adb8832008-01-14 05:45:46 +00007234 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00007235 {
7236 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00007237 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7238 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00007239 if (Unqualified) {
7240 LHSPointee = LHSPointee.getUnqualifiedType();
7241 RHSPointee = RHSPointee.getUnqualifiedType();
7242 }
7243 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7244 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00007245 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00007246 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00007247 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00007248 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00007249 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00007250 return getPointerType(ResultType);
7251 }
Steve Naroffc0febd52008-12-10 17:49:55 +00007252 case Type::BlockPointer:
7253 {
7254 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00007255 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7256 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00007257 if (Unqualified) {
7258 LHSPointee = LHSPointee.getUnqualifiedType();
7259 RHSPointee = RHSPointee.getUnqualifiedType();
7260 }
7261 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7262 Unqualified);
Steve Naroffc0febd52008-12-10 17:49:55 +00007263 if (ResultType.isNull()) return QualType();
7264 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7265 return LHS;
7266 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7267 return RHS;
7268 return getBlockPointerType(ResultType);
7269 }
Eli Friedmanb001de72011-10-06 23:00:33 +00007270 case Type::Atomic:
7271 {
7272 // Merge two pointer types, while trying to preserve typedef info
7273 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7274 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7275 if (Unqualified) {
7276 LHSValue = LHSValue.getUnqualifiedType();
7277 RHSValue = RHSValue.getUnqualifiedType();
7278 }
7279 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7280 Unqualified);
7281 if (ResultType.isNull()) return QualType();
7282 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7283 return LHS;
7284 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7285 return RHS;
7286 return getAtomicType(ResultType);
7287 }
Chris Lattner1adb8832008-01-14 05:45:46 +00007288 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00007289 {
7290 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7291 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7292 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7293 return QualType();
7294
7295 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7296 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor447234d2010-07-29 15:18:02 +00007297 if (Unqualified) {
7298 LHSElem = LHSElem.getUnqualifiedType();
7299 RHSElem = RHSElem.getUnqualifiedType();
7300 }
7301
7302 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00007303 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00007304 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7305 return LHS;
7306 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7307 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00007308 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7309 ArrayType::ArraySizeModifier(), 0);
7310 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7311 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00007312 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7313 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00007314 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7315 return LHS;
7316 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7317 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00007318 if (LVAT) {
7319 // FIXME: This isn't correct! But tricky to implement because
7320 // the array's size has to be the size of LHS, but the type
7321 // has to be different.
7322 return LHS;
7323 }
7324 if (RVAT) {
7325 // FIXME: This isn't correct! But tricky to implement because
7326 // the array's size has to be the size of RHS, but the type
7327 // has to be different.
7328 return RHS;
7329 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00007330 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7331 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00007332 return getIncompleteArrayType(ResultType,
7333 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00007334 }
Chris Lattner1adb8832008-01-14 05:45:46 +00007335 case Type::FunctionNoProto:
Douglas Gregor447234d2010-07-29 15:18:02 +00007336 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregor72564e72009-02-26 23:50:07 +00007337 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00007338 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00007339 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00007340 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00007341 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00007342 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00007343 case Type::Complex:
7344 // Distinct complex types are incompatible.
7345 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00007346 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00007347 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00007348 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7349 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00007350 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00007351 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00007352 case Type::ObjCObject: {
7353 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00007354 // FIXME: This should be type compatibility, e.g. whether
7355 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00007356 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7357 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7358 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00007359 return LHS;
7360
Eli Friedman3d815e72008-08-22 00:56:42 +00007361 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00007362 }
Steve Naroff14108da2009-07-10 23:34:53 +00007363 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00007364 if (OfBlockPointer) {
7365 if (canAssignObjCInterfacesInBlockPointer(
7366 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00007367 RHS->getAs<ObjCObjectPointerType>(),
7368 BlockReturnType))
David Blaikie7530c032012-01-17 06:56:22 +00007369 return LHS;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00007370 return QualType();
7371 }
John McCall183700f2009-09-21 23:43:11 +00007372 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7373 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00007374 return LHS;
7375
Steve Naroffbc76dd02008-12-10 22:14:21 +00007376 return QualType();
David Blaikie7530c032012-01-17 06:56:22 +00007377 }
Steve Naroffec0550f2007-10-15 20:41:53 +00007378 }
Douglas Gregor72564e72009-02-26 23:50:07 +00007379
David Blaikie7530c032012-01-17 06:56:22 +00007380 llvm_unreachable("Invalid Type::Class!");
Steve Naroffec0550f2007-10-15 20:41:53 +00007381}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00007382
Fariborz Jahanian78213e42011-09-28 21:52:05 +00007383bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7384 const FunctionProtoType *FromFunctionType,
7385 const FunctionProtoType *ToFunctionType) {
7386 if (FromFunctionType->hasAnyConsumedArgs() !=
7387 ToFunctionType->hasAnyConsumedArgs())
7388 return false;
7389 FunctionProtoType::ExtProtoInfo FromEPI =
7390 FromFunctionType->getExtProtoInfo();
7391 FunctionProtoType::ExtProtoInfo ToEPI =
7392 ToFunctionType->getExtProtoInfo();
7393 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
7394 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
7395 ArgIdx != NumArgs; ++ArgIdx) {
7396 if (FromEPI.ConsumedArguments[ArgIdx] !=
7397 ToEPI.ConsumedArguments[ArgIdx])
7398 return false;
7399 }
7400 return true;
7401}
7402
Fariborz Jahanian2390a722010-05-19 21:37:30 +00007403/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7404/// 'RHS' attributes and returns the merged version; including for function
7405/// return types.
7406QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7407 QualType LHSCan = getCanonicalType(LHS),
7408 RHSCan = getCanonicalType(RHS);
7409 // If two types are identical, they are compatible.
7410 if (LHSCan == RHSCan)
7411 return LHS;
7412 if (RHSCan->isFunctionType()) {
7413 if (!LHSCan->isFunctionType())
7414 return QualType();
7415 QualType OldReturnType =
7416 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
7417 QualType NewReturnType =
7418 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
7419 QualType ResReturnType =
7420 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7421 if (ResReturnType.isNull())
7422 return QualType();
7423 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7424 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7425 // In either case, use OldReturnType to build the new function type.
7426 const FunctionType *F = LHS->getAs<FunctionType>();
7427 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalle23cf432010-12-14 08:05:40 +00007428 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7429 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner0567a792013-06-10 20:51:09 +00007430 QualType ResultType =
7431 getFunctionType(OldReturnType, FPT->getArgTypes(), EPI);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00007432 return ResultType;
7433 }
7434 }
7435 return QualType();
7436 }
7437
7438 // If the qualifiers are different, the types can still be merged.
7439 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7440 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7441 if (LQuals != RQuals) {
7442 // If any of these qualifiers are different, we have a type mismatch.
7443 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7444 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7445 return QualType();
7446
7447 // Exactly one GC qualifier difference is allowed: __strong is
7448 // okay if the other type has no GC qualifier but is an Objective
7449 // C object pointer (i.e. implicitly strong by default). We fix
7450 // this by pretending that the unqualified type was actually
7451 // qualified __strong.
7452 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7453 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7454 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7455
7456 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7457 return QualType();
7458
7459 if (GC_L == Qualifiers::Strong)
7460 return LHS;
7461 if (GC_R == Qualifiers::Strong)
7462 return RHS;
7463 return QualType();
7464 }
7465
7466 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7467 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7468 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7469 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7470 if (ResQT == LHSBaseQT)
7471 return LHS;
7472 if (ResQT == RHSBaseQT)
7473 return RHS;
7474 }
7475 return QualType();
7476}
7477
Chris Lattner5426bf62008-04-07 07:01:58 +00007478//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00007479// Integer Predicates
7480//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00007481
Jay Foad4ba2a172011-01-12 09:06:06 +00007482unsigned ASTContext::getIntWidth(QualType T) const {
John McCallf4c73712011-01-19 06:33:43 +00007483 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00007484 T = ET->getDecl()->getIntegerType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00007485 if (T->isBooleanType())
7486 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00007487 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00007488 return (unsigned)getTypeSize(T);
7489}
7490
Abramo Bagnara762f1592012-09-09 10:21:24 +00007491QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregorf6094622010-07-23 15:58:24 +00007492 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00007493
7494 // Turn <4 x signed int> -> <4 x unsigned int>
7495 if (const VectorType *VTy = T->getAs<VectorType>())
7496 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsone86d78c2010-11-10 21:56:12 +00007497 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattner6a2b9262009-10-17 20:33:28 +00007498
7499 // For enums, we return the unsigned version of the base type.
7500 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00007501 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00007502
7503 const BuiltinType *BTy = T->getAs<BuiltinType>();
7504 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00007505 switch (BTy->getKind()) {
7506 case BuiltinType::Char_S:
7507 case BuiltinType::SChar:
7508 return UnsignedCharTy;
7509 case BuiltinType::Short:
7510 return UnsignedShortTy;
7511 case BuiltinType::Int:
7512 return UnsignedIntTy;
7513 case BuiltinType::Long:
7514 return UnsignedLongTy;
7515 case BuiltinType::LongLong:
7516 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00007517 case BuiltinType::Int128:
7518 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00007519 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00007520 llvm_unreachable("Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00007521 }
7522}
7523
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00007524ASTMutationListener::~ASTMutationListener() { }
7525
Richard Smith9dadfab2013-05-11 05:45:24 +00007526void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7527 QualType ReturnType) {}
Chris Lattner86df27b2009-06-14 00:45:47 +00007528
7529//===----------------------------------------------------------------------===//
7530// Builtin Type Computation
7531//===----------------------------------------------------------------------===//
7532
7533/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattner33daae62010-10-01 22:42:38 +00007534/// pointer over the consumed characters. This returns the resultant type. If
7535/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7536/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7537/// a vector of "i*".
Chris Lattner14e0e742010-10-01 22:53:11 +00007538///
7539/// RequiresICE is filled in on return to indicate whether the value is required
7540/// to be an Integer Constant Expression.
Jay Foad4ba2a172011-01-12 09:06:06 +00007541static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00007542 ASTContext::GetBuiltinTypeError &Error,
Chris Lattner14e0e742010-10-01 22:53:11 +00007543 bool &RequiresICE,
Chris Lattner33daae62010-10-01 22:42:38 +00007544 bool AllowTypeModifiers) {
Chris Lattner86df27b2009-06-14 00:45:47 +00007545 // Modifiers.
7546 int HowLong = 0;
7547 bool Signed = false, Unsigned = false;
Chris Lattner14e0e742010-10-01 22:53:11 +00007548 RequiresICE = false;
Chris Lattner393bd8e2010-10-01 07:13:18 +00007549
Chris Lattner33daae62010-10-01 22:42:38 +00007550 // Read the prefixed modifiers first.
Chris Lattner86df27b2009-06-14 00:45:47 +00007551 bool Done = false;
7552 while (!Done) {
7553 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00007554 default: Done = true; --Str; break;
Chris Lattner393bd8e2010-10-01 07:13:18 +00007555 case 'I':
Chris Lattner14e0e742010-10-01 22:53:11 +00007556 RequiresICE = true;
Chris Lattner393bd8e2010-10-01 07:13:18 +00007557 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007558 case 'S':
7559 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7560 assert(!Signed && "Can't use 'S' modifier multiple times!");
7561 Signed = true;
7562 break;
7563 case 'U':
7564 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7565 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7566 Unsigned = true;
7567 break;
7568 case 'L':
7569 assert(HowLong <= 2 && "Can't have LLLL modifier");
7570 ++HowLong;
7571 break;
7572 }
7573 }
7574
7575 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00007576
Chris Lattner86df27b2009-06-14 00:45:47 +00007577 // Read the base type.
7578 switch (*Str++) {
David Blaikieb219cfc2011-09-23 05:06:16 +00007579 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattner86df27b2009-06-14 00:45:47 +00007580 case 'v':
7581 assert(HowLong == 0 && !Signed && !Unsigned &&
7582 "Bad modifiers used with 'v'!");
7583 Type = Context.VoidTy;
7584 break;
7585 case 'f':
7586 assert(HowLong == 0 && !Signed && !Unsigned &&
7587 "Bad modifiers used with 'f'!");
7588 Type = Context.FloatTy;
7589 break;
7590 case 'd':
7591 assert(HowLong < 2 && !Signed && !Unsigned &&
7592 "Bad modifiers used with 'd'!");
7593 if (HowLong)
7594 Type = Context.LongDoubleTy;
7595 else
7596 Type = Context.DoubleTy;
7597 break;
7598 case 's':
7599 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7600 if (Unsigned)
7601 Type = Context.UnsignedShortTy;
7602 else
7603 Type = Context.ShortTy;
7604 break;
7605 case 'i':
7606 if (HowLong == 3)
7607 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7608 else if (HowLong == 2)
7609 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7610 else if (HowLong == 1)
7611 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7612 else
7613 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7614 break;
7615 case 'c':
7616 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7617 if (Signed)
7618 Type = Context.SignedCharTy;
7619 else if (Unsigned)
7620 Type = Context.UnsignedCharTy;
7621 else
7622 Type = Context.CharTy;
7623 break;
7624 case 'b': // boolean
7625 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7626 Type = Context.BoolTy;
7627 break;
7628 case 'z': // size_t.
7629 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7630 Type = Context.getSizeType();
7631 break;
7632 case 'F':
7633 Type = Context.getCFConstantStringType();
7634 break;
Fariborz Jahanianba8bda02010-11-09 21:38:20 +00007635 case 'G':
7636 Type = Context.getObjCIdType();
7637 break;
7638 case 'H':
7639 Type = Context.getObjCSelType();
7640 break;
Fariborz Jahanianf7992132013-01-04 18:45:40 +00007641 case 'M':
7642 Type = Context.getObjCSuperType();
7643 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007644 case 'a':
7645 Type = Context.getBuiltinVaListType();
7646 assert(!Type.isNull() && "builtin va list type not initialized!");
7647 break;
7648 case 'A':
7649 // This is a "reference" to a va_list; however, what exactly
7650 // this means depends on how va_list is defined. There are two
7651 // different kinds of va_list: ones passed by value, and ones
7652 // passed by reference. An example of a by-value va_list is
7653 // x86, where va_list is a char*. An example of by-ref va_list
7654 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7655 // we want this argument to be a char*&; for x86-64, we want
7656 // it to be a __va_list_tag*.
7657 Type = Context.getBuiltinVaListType();
7658 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattner14e0e742010-10-01 22:53:11 +00007659 if (Type->isArrayType())
Chris Lattner86df27b2009-06-14 00:45:47 +00007660 Type = Context.getArrayDecayedType(Type);
Chris Lattner14e0e742010-10-01 22:53:11 +00007661 else
Chris Lattner86df27b2009-06-14 00:45:47 +00007662 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00007663 break;
7664 case 'V': {
7665 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00007666 unsigned NumElements = strtoul(Str, &End, 10);
7667 assert(End != Str && "Missing vector size");
Chris Lattner86df27b2009-06-14 00:45:47 +00007668 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00007669
Chris Lattner14e0e742010-10-01 22:53:11 +00007670 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7671 RequiresICE, false);
7672 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattner33daae62010-10-01 22:42:38 +00007673
7674 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner788b0fd2010-06-23 06:00:24 +00007675 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00007676 VectorType::GenericVector);
Chris Lattner86df27b2009-06-14 00:45:47 +00007677 break;
7678 }
Douglas Gregorb4bc99b2012-06-07 18:08:25 +00007679 case 'E': {
7680 char *End;
7681
7682 unsigned NumElements = strtoul(Str, &End, 10);
7683 assert(End != Str && "Missing vector size");
7684
7685 Str = End;
7686
7687 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7688 false);
7689 Type = Context.getExtVectorType(ElementType, NumElements);
7690 break;
7691 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00007692 case 'X': {
Chris Lattner14e0e742010-10-01 22:53:11 +00007693 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7694 false);
7695 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregord3a23b22009-09-28 21:45:01 +00007696 Type = Context.getComplexType(ElementType);
7697 break;
Fariborz Jahaniancc075e42011-08-23 23:33:09 +00007698 }
7699 case 'Y' : {
7700 Type = Context.getPointerDiffType();
7701 break;
7702 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00007703 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00007704 Type = Context.getFILEType();
7705 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00007706 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00007707 return QualType();
7708 }
Mike Stumpfd612db2009-07-28 23:47:15 +00007709 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00007710 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00007711 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00007712 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00007713 else
7714 Type = Context.getjmp_bufType();
7715
Mike Stumpfd612db2009-07-28 23:47:15 +00007716 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00007717 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00007718 return QualType();
7719 }
7720 break;
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +00007721 case 'K':
7722 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7723 Type = Context.getucontext_tType();
7724
7725 if (Type.isNull()) {
7726 Error = ASTContext::GE_Missing_ucontext;
7727 return QualType();
7728 }
7729 break;
Eli Friedman6902e412012-11-27 02:58:24 +00007730 case 'p':
7731 Type = Context.getProcessIDType();
7732 break;
Mike Stump782fa302009-07-28 02:25:19 +00007733 }
Mike Stump1eb44332009-09-09 15:08:12 +00007734
Chris Lattner33daae62010-10-01 22:42:38 +00007735 // If there are modifiers and if we're allowed to parse them, go for it.
7736 Done = !AllowTypeModifiers;
Chris Lattner86df27b2009-06-14 00:45:47 +00007737 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00007738 switch (char c = *Str++) {
Chris Lattner33daae62010-10-01 22:42:38 +00007739 default: Done = true; --Str; break;
7740 case '*':
7741 case '&': {
7742 // Both pointers and references can have their pointee types
7743 // qualified with an address space.
7744 char *End;
7745 unsigned AddrSpace = strtoul(Str, &End, 10);
7746 if (End != Str && AddrSpace != 0) {
7747 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7748 Str = End;
7749 }
7750 if (c == '*')
7751 Type = Context.getPointerType(Type);
7752 else
7753 Type = Context.getLValueReferenceType(Type);
7754 break;
7755 }
7756 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7757 case 'C':
7758 Type = Type.withConst();
7759 break;
7760 case 'D':
7761 Type = Context.getVolatileType(Type);
7762 break;
Ted Kremenek18932a02012-01-20 21:40:12 +00007763 case 'R':
7764 Type = Type.withRestrict();
7765 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007766 }
7767 }
Chris Lattner393bd8e2010-10-01 07:13:18 +00007768
Chris Lattner14e0e742010-10-01 22:53:11 +00007769 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner393bd8e2010-10-01 07:13:18 +00007770 "Integer constant 'I' type must be an integer");
Mike Stump1eb44332009-09-09 15:08:12 +00007771
Chris Lattner86df27b2009-06-14 00:45:47 +00007772 return Type;
7773}
7774
7775/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattner33daae62010-10-01 22:42:38 +00007776QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattner14e0e742010-10-01 22:53:11 +00007777 GetBuiltinTypeError &Error,
Jay Foad4ba2a172011-01-12 09:06:06 +00007778 unsigned *IntegerConstantArgs) const {
Chris Lattner33daae62010-10-01 22:42:38 +00007779 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump1eb44332009-09-09 15:08:12 +00007780
Chris Lattner5f9e2722011-07-23 10:55:15 +00007781 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00007782
Chris Lattner14e0e742010-10-01 22:53:11 +00007783 bool RequiresICE = false;
Chris Lattner86df27b2009-06-14 00:45:47 +00007784 Error = GE_None;
Chris Lattner14e0e742010-10-01 22:53:11 +00007785 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7786 RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00007787 if (Error != GE_None)
7788 return QualType();
Chris Lattner14e0e742010-10-01 22:53:11 +00007789
7790 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7791
Chris Lattner86df27b2009-06-14 00:45:47 +00007792 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattner14e0e742010-10-01 22:53:11 +00007793 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00007794 if (Error != GE_None)
7795 return QualType();
7796
Chris Lattner14e0e742010-10-01 22:53:11 +00007797 // If this argument is required to be an IntegerConstantExpression and the
7798 // caller cares, fill in the bitmask we return.
7799 if (RequiresICE && IntegerConstantArgs)
7800 *IntegerConstantArgs |= 1 << ArgTypes.size();
7801
Chris Lattner86df27b2009-06-14 00:45:47 +00007802 // Do array -> pointer decay. The builtin should use the decayed type.
7803 if (Ty->isArrayType())
7804 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00007805
Chris Lattner86df27b2009-06-14 00:45:47 +00007806 ArgTypes.push_back(Ty);
7807 }
7808
7809 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7810 "'.' should only occur at end of builtin type list!");
7811
John McCall00ccbef2010-12-21 00:44:39 +00007812 FunctionType::ExtInfo EI;
7813 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7814
7815 bool Variadic = (TypeStr[0] == '.');
7816
7817 // We really shouldn't be making a no-proto type here, especially in C++.
7818 if (ArgTypes.empty() && Variadic)
7819 return getFunctionNoProtoType(ResType, EI);
Douglas Gregorce056bc2010-02-21 22:15:06 +00007820
John McCalle23cf432010-12-14 08:05:40 +00007821 FunctionProtoType::ExtProtoInfo EPI;
John McCall00ccbef2010-12-21 00:44:39 +00007822 EPI.ExtInfo = EI;
7823 EPI.Variadic = Variadic;
John McCalle23cf432010-12-14 08:05:40 +00007824
Jordan Rosebea522f2013-03-08 21:51:21 +00007825 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattner86df27b2009-06-14 00:45:47 +00007826}
Eli Friedmana95d7572009-08-19 07:44:53 +00007827
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007828GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007829 if (!FD->isExternallyVisible())
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007830 return GVA_Internal;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007831
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007832 GVALinkage External = GVA_StrongExternal;
7833 switch (FD->getTemplateSpecializationKind()) {
7834 case TSK_Undeclared:
7835 case TSK_ExplicitSpecialization:
7836 External = GVA_StrongExternal;
7837 break;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007838
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007839 case TSK_ExplicitInstantiationDefinition:
7840 return GVA_ExplicitTemplateInstantiation;
7841
7842 case TSK_ExplicitInstantiationDeclaration:
7843 case TSK_ImplicitInstantiation:
7844 External = GVA_TemplateInstantiation;
7845 break;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007846 }
7847
7848 if (!FD->isInlined())
7849 return External;
7850
David Blaikie4e4d0842012-03-11 07:00:24 +00007851 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007852 // GNU or C99 inline semantics. Determine whether this symbol should be
7853 // externally visible.
7854 if (FD->isInlineDefinitionExternallyVisible())
7855 return External;
7856
7857 // C99 inline semantics, where the symbol is not externally visible.
7858 return GVA_C99Inline;
7859 }
7860
7861 // C++0x [temp.explicit]p9:
7862 // [ Note: The intent is that an inline function that is the subject of
7863 // an explicit instantiation declaration will still be implicitly
7864 // instantiated when used so that the body can be considered for
7865 // inlining, but that no out-of-line copy of the inline function would be
7866 // generated in the translation unit. -- end note ]
7867 if (FD->getTemplateSpecializationKind()
7868 == TSK_ExplicitInstantiationDeclaration)
7869 return GVA_C99Inline;
7870
7871 return GVA_CXXInline;
7872}
7873
7874GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007875 if (!VD->isExternallyVisible())
7876 return GVA_Internal;
7877
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007878 // If this is a static data member, compute the kind of template
7879 // specialization. Otherwise, this variable is not part of a
7880 // template.
7881 TemplateSpecializationKind TSK = TSK_Undeclared;
7882 if (VD->isStaticDataMember())
7883 TSK = VD->getTemplateSpecializationKind();
7884
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007885 switch (TSK) {
7886 case TSK_Undeclared:
7887 case TSK_ExplicitSpecialization:
7888 return GVA_StrongExternal;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007889
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007890 case TSK_ExplicitInstantiationDeclaration:
7891 llvm_unreachable("Variable should not be instantiated");
7892 // Fall through to treat this like any other instantiation.
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007893
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007894 case TSK_ExplicitInstantiationDefinition:
7895 return GVA_ExplicitTemplateInstantiation;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007896
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007897 case TSK_ImplicitInstantiation:
7898 return GVA_TemplateInstantiation;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007899 }
Rafael Espindola77b50252013-05-13 14:05:53 +00007900
7901 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007902}
7903
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +00007904bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007905 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7906 if (!VD->isFileVarDecl())
7907 return false;
Richard Smithf396ad92013-04-01 20:22:16 +00007908 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7909 // We never need to emit an uninstantiated function template.
7910 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
7911 return false;
7912 } else
7913 return false;
7914
7915 // If this is a member of a class template, we do not need to emit it.
7916 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007917 return false;
7918
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00007919 // Weak references don't produce any output by themselves.
7920 if (D->hasAttr<WeakRefAttr>())
7921 return false;
7922
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007923 // Aliases and used decls are required.
7924 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7925 return true;
7926
7927 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7928 // Forward declarations aren't required.
Sean Hunt10620eb2011-05-06 20:44:56 +00007929 if (!FD->doesThisDeclarationHaveABody())
Nick Lewyckydce67a72011-07-18 05:26:13 +00007930 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007931
7932 // Constructors and destructors are required.
7933 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7934 return true;
7935
John McCalld5617ee2013-01-25 22:31:03 +00007936 // The key function for a class is required. This rule only comes
7937 // into play when inline functions can be key functions, though.
7938 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7939 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7940 const CXXRecordDecl *RD = MD->getParent();
7941 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7942 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
7943 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7944 return true;
7945 }
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007946 }
7947 }
7948
7949 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7950
7951 // static, static inline, always_inline, and extern inline functions can
7952 // always be deferred. Normal inline functions can be deferred in C99/C++.
7953 // Implicit template instantiations can also be deferred in C++.
7954 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev3a5aca82012-02-02 06:06:34 +00007955 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007956 return false;
7957 return true;
7958 }
Douglas Gregor94da1582011-09-10 00:22:34 +00007959
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007960 const VarDecl *VD = cast<VarDecl>(D);
7961 assert(VD->isFileVarDecl() && "Expected file scoped var");
7962
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00007963 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7964 return false;
7965
Richard Smith5f9a7e32012-11-12 21:38:00 +00007966 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007967 GVALinkage L = GetGVALinkageForVariable(VD);
Richard Smith5f9a7e32012-11-12 21:38:00 +00007968 if (L != GVA_Internal && L != GVA_TemplateInstantiation)
7969 return true;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007970
Richard Smith5f9a7e32012-11-12 21:38:00 +00007971 // Variables that have destruction with side-effects are required.
7972 if (VD->getType().isDestructedType())
7973 return true;
7974
7975 // Variables that have initialization with side-effects are required.
7976 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
7977 return true;
7978
7979 return false;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007980}
Charles Davis071cc7d2010-08-16 03:33:14 +00007981
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007982CallingConv ASTContext::getDefaultCXXMethodCallConv(bool isVariadic) {
Charles Davisee743f92010-11-09 18:04:24 +00007983 // Pass through to the C++ ABI object
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007984 return ABI->getDefaultMethodCallConv(isVariadic);
7985}
7986
7987CallingConv ASTContext::getCanonicalCallConv(CallingConv CC) const {
John McCallb8b2c9d2013-01-25 22:30:49 +00007988 if (CC == CC_C && !LangOpts.MRTD &&
7989 getTargetInfo().getCXXABI().isMemberFunctionCCDefault())
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007990 return CC_Default;
7991 return CC;
Charles Davisee743f92010-11-09 18:04:24 +00007992}
7993
Jay Foad4ba2a172011-01-12 09:06:06 +00007994bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlssondae0cb52010-11-25 01:51:53 +00007995 // Pass through to the C++ ABI object
7996 return ABI->isNearlyEmpty(RD);
7997}
7998
Peter Collingbourne14110472011-01-13 18:57:25 +00007999MangleContext *ASTContext::createMangleContext() {
John McCallb8b2c9d2013-01-25 22:30:49 +00008000 switch (Target->getCXXABI().getKind()) {
Tim Northoverc264e162013-01-31 12:13:10 +00008001 case TargetCXXABI::GenericAArch64:
John McCallb8b2c9d2013-01-25 22:30:49 +00008002 case TargetCXXABI::GenericItanium:
8003 case TargetCXXABI::GenericARM:
8004 case TargetCXXABI::iOS:
Peter Collingbourne14110472011-01-13 18:57:25 +00008005 return createItaniumMangleContext(*this, getDiagnostics());
John McCallb8b2c9d2013-01-25 22:30:49 +00008006 case TargetCXXABI::Microsoft:
Peter Collingbourne14110472011-01-13 18:57:25 +00008007 return createMicrosoftMangleContext(*this, getDiagnostics());
8008 }
David Blaikieb219cfc2011-09-23 05:06:16 +00008009 llvm_unreachable("Unsupported ABI");
Peter Collingbourne14110472011-01-13 18:57:25 +00008010}
8011
Charles Davis071cc7d2010-08-16 03:33:14 +00008012CXXABI::~CXXABI() {}
Ted Kremenekba29bd22011-04-28 04:53:38 +00008013
8014size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek0c8cd1a2011-07-27 18:41:12 +00008015 return ASTRecordLayouts.getMemorySize()
8016 + llvm::capacity_in_bytes(ObjCLayouts)
8017 + llvm::capacity_in_bytes(KeyFunctions)
8018 + llvm::capacity_in_bytes(ObjCImpls)
8019 + llvm::capacity_in_bytes(BlockVarCopyInits)
8020 + llvm::capacity_in_bytes(DeclAttrs)
8021 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
8022 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
8023 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
8024 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
8025 + llvm::capacity_in_bytes(OverriddenMethods)
8026 + llvm::capacity_in_bytes(Types)
Francois Pichetaf0f4d02011-08-14 03:52:19 +00008027 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet0d95f0d2011-08-14 14:28:49 +00008028 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekba29bd22011-04-28 04:53:38 +00008029}
Ted Kremenekd211cb72011-10-06 05:00:56 +00008030
David Blaikie66cff722012-11-14 01:52:05 +00008031void ASTContext::addUnnamedTag(const TagDecl *Tag) {
8032 // FIXME: This mangling should be applied to function local classes too
8033 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl() ||
Rafael Espindola5bbb0582013-05-28 14:09:46 +00008034 !isa<CXXRecordDecl>(Tag->getParent()))
David Blaikie66cff722012-11-14 01:52:05 +00008035 return;
8036
8037 std::pair<llvm::DenseMap<const DeclContext *, unsigned>::iterator, bool> P =
8038 UnnamedMangleContexts.insert(std::make_pair(Tag->getParent(), 0));
8039 UnnamedMangleNumbers.insert(std::make_pair(Tag, P.first->second++));
8040}
8041
8042int ASTContext::getUnnamedTagManglingNumber(const TagDecl *Tag) const {
8043 llvm::DenseMap<const TagDecl *, unsigned>::const_iterator I =
8044 UnnamedMangleNumbers.find(Tag);
8045 return I != UnnamedMangleNumbers.end() ? I->second : -1;
8046}
8047
Douglas Gregor9e8c92a2012-02-20 19:44:39 +00008048unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
8049 CXXRecordDecl *Lambda = CallOperator->getParent();
8050 return LambdaMangleContexts[Lambda->getDeclContext()]
8051 .getManglingNumber(CallOperator);
8052}
8053
8054
Ted Kremenekd211cb72011-10-06 05:00:56 +00008055void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8056 ParamIndices[D] = index;
8057}
8058
8059unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8060 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8061 assert(I != ParamIndices.end() &&
8062 "ParmIndices lacks entry set by ParmVarDecl");
8063 return I->second;
8064}
Fariborz Jahanian538bbe52013-05-28 17:37:39 +00008065
Richard Smith211c8dd2013-06-05 00:46:14 +00008066APValue *
8067ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8068 bool MayCreate) {
8069 assert(E && E->getStorageDuration() == SD_Static &&
8070 "don't need to cache the computed value for this temporary");
8071 if (MayCreate)
8072 return &MaterializedTemporaryValues[E];
8073
8074 llvm::DenseMap<const MaterializeTemporaryExpr *, APValue>::iterator I =
8075 MaterializedTemporaryValues.find(E);
8076 return I == MaterializedTemporaryValues.end() ? 0 : &I->second;
8077}
8078
Fariborz Jahanian538bbe52013-05-28 17:37:39 +00008079bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8080 const llvm::Triple &T = getTargetInfo().getTriple();
8081 if (!T.isOSDarwin())
8082 return false;
8083
8084 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8085 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8086 uint64_t Size = sizeChars.getQuantity();
8087 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8088 unsigned Align = alignChars.getQuantity();
8089 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8090 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8091}
Reid Klecknercff15122013-06-17 12:56:08 +00008092
8093namespace {
8094
8095 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8096 /// parents as defined by the \c RecursiveASTVisitor.
8097 ///
8098 /// Note that the relationship described here is purely in terms of AST
8099 /// traversal - there are other relationships (for example declaration context)
8100 /// in the AST that are better modeled by special matchers.
8101 ///
8102 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
8103 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
8104
8105 public:
8106 /// \brief Builds and returns the translation unit's parent map.
8107 ///
8108 /// The caller takes ownership of the returned \c ParentMap.
8109 static ASTContext::ParentMap *buildMap(TranslationUnitDecl &TU) {
8110 ParentMapASTVisitor Visitor(new ASTContext::ParentMap);
8111 Visitor.TraverseDecl(&TU);
8112 return Visitor.Parents;
8113 }
8114
8115 private:
8116 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8117
8118 ParentMapASTVisitor(ASTContext::ParentMap *Parents) : Parents(Parents) {
8119 }
8120
8121 bool shouldVisitTemplateInstantiations() const {
8122 return true;
8123 }
8124 bool shouldVisitImplicitCode() const {
8125 return true;
8126 }
8127 // Disables data recursion. We intercept Traverse* methods in the RAV, which
8128 // are not triggered during data recursion.
8129 bool shouldUseDataRecursionFor(clang::Stmt *S) const {
8130 return false;
8131 }
8132
8133 template <typename T>
8134 bool TraverseNode(T *Node, bool(VisitorBase:: *traverse) (T *)) {
8135 if (Node == NULL)
8136 return true;
8137 if (ParentStack.size() > 0)
8138 // FIXME: Currently we add the same parent multiple times, for example
8139 // when we visit all subexpressions of template instantiations; this is
8140 // suboptimal, bug benign: the only way to visit those is with
8141 // hasAncestor / hasParent, and those do not create new matches.
8142 // The plan is to enable DynTypedNode to be storable in a map or hash
8143 // map. The main problem there is to implement hash functions /
8144 // comparison operators for all types that DynTypedNode supports that
8145 // do not have pointer identity.
8146 (*Parents)[Node].push_back(ParentStack.back());
8147 ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node));
8148 bool Result = (this ->* traverse) (Node);
8149 ParentStack.pop_back();
8150 return Result;
8151 }
8152
8153 bool TraverseDecl(Decl *DeclNode) {
8154 return TraverseNode(DeclNode, &VisitorBase::TraverseDecl);
8155 }
8156
8157 bool TraverseStmt(Stmt *StmtNode) {
8158 return TraverseNode(StmtNode, &VisitorBase::TraverseStmt);
8159 }
8160
8161 ASTContext::ParentMap *Parents;
8162 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8163
8164 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8165 };
8166
8167} // end namespace
8168
8169ASTContext::ParentVector
8170ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
8171 assert(Node.getMemoizationData() &&
8172 "Invariant broken: only nodes that support memoization may be "
8173 "used in the parent map.");
8174 if (!AllParents) {
8175 // We always need to run over the whole translation unit, as
8176 // hasAncestor can escape any subtree.
8177 AllParents.reset(
8178 ParentMapASTVisitor::buildMap(*getTranslationUnitDecl()));
8179 }
8180 ParentMap::const_iterator I = AllParents->find(Node.getMemoizationData());
8181 if (I == AllParents->end()) {
8182 return ParentVector();
8183 }
8184 return I->second;
8185}