blob: 5d155730384f222bf60d0dd250624e5748afeafe [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"
29#include "clang/AST/TypeLoc.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000030#include "clang/Basic/Builtins.h"
Chris Lattnera9376d42009-03-28 03:45:20 +000031#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000032#include "clang/Basic/TargetInfo.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000033#include "llvm/ADT/SmallString.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000034#include "llvm/ADT/StringExtras.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000035#include "llvm/Support/Capacity.h"
Nate Begeman6fe7c8a2009-01-18 06:42:49 +000036#include "llvm/Support/MathExtras.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000037#include "llvm/Support/raw_ostream.h"
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +000038#include <map>
Anders Carlsson29445a02009-07-18 21:19:52 +000039
Reid Spencer5f016e22007-07-11 17:01:13 +000040using namespace clang;
41
Douglas Gregor18274032010-07-03 00:47:00 +000042unsigned ASTContext::NumImplicitDefaultConstructors;
43unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregor22584312010-07-02 23:41:54 +000044unsigned ASTContext::NumImplicitCopyConstructors;
45unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Sean Huntffe37fd2011-05-25 20:50:04 +000046unsigned ASTContext::NumImplicitMoveConstructors;
47unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregora376d102010-07-02 21:50:04 +000048unsigned ASTContext::NumImplicitCopyAssignmentOperators;
49unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Huntffe37fd2011-05-25 20:50:04 +000050unsigned ASTContext::NumImplicitMoveAssignmentOperators;
51unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor4923aa22010-07-02 20:37:36 +000052unsigned ASTContext::NumImplicitDestructors;
53unsigned ASTContext::NumImplicitDestructorsDeclared;
54
Reid Spencer5f016e22007-07-11 17:01:13 +000055enum FloatingRank {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +000056 HalfRank, FloatRank, DoubleRank, LongDoubleRank
Reid Spencer5f016e22007-07-11 17:01:13 +000057};
58
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +000059RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +000060 if (!CommentsLoaded && ExternalSource) {
61 ExternalSource->ReadComments();
62 CommentsLoaded = true;
63 }
64
65 assert(D);
66
Dmitri Gribenkoc3fee352012-06-28 16:19:39 +000067 // User can not attach documentation to implicit declarations.
68 if (D->isImplicit())
69 return NULL;
70
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +000071 // User can not attach documentation to implicit instantiations.
72 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
73 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
74 return NULL;
75 }
76
Dmitri Gribenkodce750b2012-08-20 22:36:31 +000077 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
78 if (VD->isStaticDataMember() &&
79 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
80 return NULL;
81 }
82
83 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
84 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
85 return NULL;
86 }
87
Dmitri Gribenkod1e5c0d2013-01-27 21:18:39 +000088 if (const ClassTemplateSpecializationDecl *CTSD =
89 dyn_cast<ClassTemplateSpecializationDecl>(D)) {
90 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
91 if (TSK == TSK_ImplicitInstantiation ||
92 TSK == TSK_Undeclared)
93 return NULL;
94 }
95
Dmitri Gribenkodce750b2012-08-20 22:36:31 +000096 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
97 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
98 return NULL;
99 }
100
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000101 // TODO: handle comments for function parameters properly.
102 if (isa<ParmVarDecl>(D))
103 return NULL;
104
Dmitri Gribenko96b09862012-07-31 22:37:06 +0000105 // TODO: we could look up template parameter documentation in the template
106 // documentation.
107 if (isa<TemplateTypeParmDecl>(D) ||
108 isa<NonTypeTemplateParmDecl>(D) ||
109 isa<TemplateTemplateParmDecl>(D))
110 return NULL;
111
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000112 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000113
114 // If there are no comments anywhere, we won't find anything.
115 if (RawComments.empty())
116 return NULL;
117
Dmitri Gribenkoabd56c82012-07-13 01:06:46 +0000118 // Find declaration location.
119 // For Objective-C declarations we generally don't expect to have multiple
120 // declarators, thus use declaration starting location as the "declaration
121 // location".
122 // For all other declarations multiple declarators are used quite frequently,
123 // so we use the location of the identifier as the "declaration location".
124 SourceLocation DeclLoc;
125 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko96b09862012-07-31 22:37:06 +0000126 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +0000127 isa<RedeclarableTemplateDecl>(D) ||
128 isa<ClassTemplateSpecializationDecl>(D))
Dmitri Gribenkoabd56c82012-07-13 01:06:46 +0000129 DeclLoc = D->getLocStart();
130 else
131 DeclLoc = D->getLocation();
132
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000133 // If the declaration doesn't map directly to a location in a file, we
134 // can't find the comment.
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000135 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
136 return NULL;
137
138 // Find the comment that occurs just after this declaration.
Dmitri Gribenkoa444f182012-07-17 22:01:09 +0000139 ArrayRef<RawComment *>::iterator Comment;
140 {
141 // When searching for comments during parsing, the comment we are looking
142 // for is usually among the last two comments we parsed -- check them
143 // first.
144 RawComment CommentAtDeclLoc(SourceMgr, SourceRange(DeclLoc));
145 BeforeThanCompare<RawComment> Compare(SourceMgr);
146 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
147 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
148 if (!Found && RawComments.size() >= 2) {
149 MaybeBeforeDecl--;
150 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
151 }
152
153 if (Found) {
154 Comment = MaybeBeforeDecl + 1;
155 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
156 &CommentAtDeclLoc, Compare));
157 } else {
158 // Slow path.
159 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
160 &CommentAtDeclLoc, Compare);
161 }
162 }
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000163
164 // Decompose the location for the declaration and find the beginning of the
165 // file buffer.
166 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
167
168 // First check whether we have a trailing comment.
169 if (Comment != RawComments.end() &&
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000170 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
Dmitri Gribenko9c006762012-07-06 23:27:33 +0000171 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D))) {
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000172 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000173 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000174 // Check that Doxygen trailing comment comes after the declaration, starts
175 // on the same line and in the same file as the declaration.
176 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
177 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
178 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
179 CommentBeginDecomp.second)) {
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000180 return *Comment;
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000181 }
182 }
183
184 // The comment just after the declaration was not a trailing comment.
185 // Let's look at the previous comment.
186 if (Comment == RawComments.begin())
187 return NULL;
188 --Comment;
189
190 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000191 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000192 return NULL;
193
194 // Decompose the end of the comment.
195 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000196 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000197
198 // If the comment and the declaration aren't in the same file, then they
199 // aren't related.
200 if (DeclLocDecomp.first != CommentEndDecomp.first)
201 return NULL;
202
203 // Get the corresponding buffer.
204 bool Invalid = false;
205 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
206 &Invalid).data();
207 if (Invalid)
208 return NULL;
209
210 // Extract text between the comment and declaration.
211 StringRef Text(Buffer + CommentEndDecomp.second,
212 DeclLocDecomp.second - CommentEndDecomp.second);
213
Dmitri Gribenko8bdb58a2012-06-27 23:43:37 +0000214 // There should be no other declarations or preprocessor directives between
215 // comment and declaration.
Dmitri Gribenkoabd56c82012-07-13 01:06:46 +0000216 if (Text.find_first_of(",;{}#@") != StringRef::npos)
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000217 return NULL;
218
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000219 return *Comment;
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000220}
221
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000222namespace {
223/// If we have a 'templated' declaration for a template, adjust 'D' to
224/// refer to the actual template.
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000225/// If we have an implicit instantiation, adjust 'D' to refer to template.
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000226const Decl *adjustDeclToTemplate(const Decl *D) {
Douglas Gregorcd81df22012-08-13 16:37:30 +0000227 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000228 // Is this function declaration part of a function template?
Douglas Gregorcd81df22012-08-13 16:37:30 +0000229 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000230 return FTD;
231
232 // Nothing to do if function is not an implicit instantiation.
233 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
234 return D;
235
236 // Function is an implicit instantiation of a function template?
237 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
238 return FTD;
239
240 // Function is instantiated from a member definition of a class template?
241 if (const FunctionDecl *MemberDecl =
242 FD->getInstantiatedFromMemberFunction())
243 return MemberDecl;
244
245 return D;
Douglas Gregorcd81df22012-08-13 16:37:30 +0000246 }
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000247 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
248 // Static data member is instantiated from a member definition of a class
249 // template?
250 if (VD->isStaticDataMember())
251 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
252 return MemberDecl;
253
254 return D;
255 }
256 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
257 // Is this class declaration part of a class template?
258 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
259 return CTD;
260
261 // Class is an implicit instantiation of a class template or partial
262 // specialization?
263 if (const ClassTemplateSpecializationDecl *CTSD =
264 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
265 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
266 return D;
267 llvm::PointerUnion<ClassTemplateDecl *,
268 ClassTemplatePartialSpecializationDecl *>
269 PU = CTSD->getSpecializedTemplateOrPartial();
270 return PU.is<ClassTemplateDecl*>() ?
271 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
272 static_cast<const Decl*>(
273 PU.get<ClassTemplatePartialSpecializationDecl *>());
274 }
275
276 // Class is instantiated from a member definition of a class template?
277 if (const MemberSpecializationInfo *Info =
278 CRD->getMemberSpecializationInfo())
279 return Info->getInstantiatedFrom();
280
281 return D;
282 }
283 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
284 // Enum is instantiated from a member definition of a class template?
285 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
286 return MemberDecl;
287
288 return D;
289 }
290 // FIXME: Adjust alias templates?
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000291 return D;
292}
293} // unnamed namespace
294
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000295const RawComment *ASTContext::getRawCommentForAnyRedecl(
296 const Decl *D,
297 const Decl **OriginalDecl) const {
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000298 D = adjustDeclToTemplate(D);
Douglas Gregorcd81df22012-08-13 16:37:30 +0000299
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000300 // Check whether we have cached a comment for this declaration already.
301 {
302 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
303 RedeclComments.find(D);
304 if (Pos != RedeclComments.end()) {
305 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000306 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
307 if (OriginalDecl)
308 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000309 return Raw.getRaw();
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000310 }
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000311 }
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000312 }
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000313
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000314 // Search for comments attached to declarations in the redeclaration chain.
315 const RawComment *RC = NULL;
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000316 const Decl *OriginalDeclForRC = NULL;
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000317 for (Decl::redecl_iterator I = D->redecls_begin(),
318 E = D->redecls_end();
319 I != E; ++I) {
320 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
321 RedeclComments.find(*I);
322 if (Pos != RedeclComments.end()) {
323 const RawCommentAndCacheFlags &Raw = Pos->second;
324 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
325 RC = Raw.getRaw();
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000326 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000327 break;
328 }
329 } else {
330 RC = getRawCommentForDeclNoCache(*I);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000331 OriginalDeclForRC = *I;
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000332 RawCommentAndCacheFlags Raw;
333 if (RC) {
334 Raw.setRaw(RC);
335 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
336 } else
337 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000338 Raw.setOriginalDecl(*I);
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000339 RedeclComments[*I] = Raw;
340 if (RC)
341 break;
342 }
343 }
344
Dmitri Gribenko8376f592012-06-28 16:25:36 +0000345 // If we found a comment, it should be a documentation comment.
346 assert(!RC || RC->isDocumentation());
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000347
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000348 if (OriginalDecl)
349 *OriginalDecl = OriginalDeclForRC;
350
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000351 // Update cache for every declaration in the redeclaration chain.
352 RawCommentAndCacheFlags Raw;
353 Raw.setRaw(RC);
354 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000355 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000356
357 for (Decl::redecl_iterator I = D->redecls_begin(),
358 E = D->redecls_end();
359 I != E; ++I) {
360 RawCommentAndCacheFlags &R = RedeclComments[*I];
361 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
362 R = Raw;
363 }
364
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000365 return RC;
366}
367
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000368static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
369 SmallVectorImpl<const NamedDecl *> &Redeclared) {
370 const DeclContext *DC = ObjCMethod->getDeclContext();
371 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
372 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
373 if (!ID)
374 return;
375 // Add redeclared method here.
Douglas Gregord3297242013-01-16 23:00:23 +0000376 for (ObjCInterfaceDecl::known_extensions_iterator
377 Ext = ID->known_extensions_begin(),
378 ExtEnd = ID->known_extensions_end();
379 Ext != ExtEnd; ++Ext) {
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000380 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregord3297242013-01-16 23:00:23 +0000381 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000382 ObjCMethod->isInstanceMethod()))
383 Redeclared.push_back(RedeclaredMethod);
384 }
385 }
386}
387
Fariborz Jahanian749ace62012-10-11 23:52:50 +0000388comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
389 const Decl *D) const {
390 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
391 ThisDeclInfo->CommentDecl = D;
392 ThisDeclInfo->IsFilled = false;
393 ThisDeclInfo->fill();
394 ThisDeclInfo->CommentDecl = FC->getDecl();
395 comments::FullComment *CFC =
396 new (*this) comments::FullComment(FC->getBlocks(),
397 ThisDeclInfo);
398 return CFC;
399
400}
401
Dmitri Gribenko19523542012-09-29 11:40:46 +0000402comments::FullComment *ASTContext::getCommentForDecl(
403 const Decl *D,
404 const Preprocessor *PP) const {
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000405 D = adjustDeclToTemplate(D);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000406
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000407 const Decl *Canonical = D->getCanonicalDecl();
408 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
409 ParsedComments.find(Canonical);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000410
411 if (Pos != ParsedComments.end()) {
Fariborz Jahanian749ace62012-10-11 23:52:50 +0000412 if (Canonical != D) {
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000413 comments::FullComment *FC = Pos->second;
Fariborz Jahanian749ace62012-10-11 23:52:50 +0000414 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000415 return CFC;
416 }
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000417 return Pos->second;
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000418 }
419
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000420 const Decl *OriginalDecl;
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000421
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000422 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000423 if (!RC) {
424 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko1e905da2012-11-03 14:24:57 +0000425 SmallVector<const NamedDecl*, 8> Overridden;
Fariborz Jahanianc328d9c2013-01-12 00:28:34 +0000426 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian23799e32013-01-25 23:08:39 +0000427 if (OMD && OMD->isPropertyAccessor())
428 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
429 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
430 return cloneFullComment(FC, D);
Fariborz Jahanianc328d9c2013-01-12 00:28:34 +0000431 if (OMD)
Dmitri Gribenko1e905da2012-11-03 14:24:57 +0000432 addRedeclaredMethods(OMD, Overridden);
433 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian23799e32013-01-25 23:08:39 +0000434 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
435 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
436 return cloneFullComment(FC, D);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000437 }
Fariborz Jahanian41170b52013-01-25 22:48:32 +0000438 else if (const TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Dmitri Gribenkod1e5c0d2013-01-27 21:18:39 +0000439 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian23799e32013-01-25 23:08:39 +0000440 // does not have one of its own.
Fariborz Jahanian41170b52013-01-25 22:48:32 +0000441 QualType QT = TD->getUnderlyingType();
Dmitri Gribenkod1e5c0d2013-01-27 21:18:39 +0000442 if (const TagType *TT = QT->getAs<TagType>())
443 if (const Decl *TD = TT->getDecl())
444 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian23799e32013-01-25 23:08:39 +0000445 return cloneFullComment(FC, D);
Fariborz Jahanian41170b52013-01-25 22:48:32 +0000446 }
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000447 return NULL;
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000448 }
449
Dmitri Gribenko4b41c652012-08-22 18:12:19 +0000450 // If the RawComment was attached to other redeclaration of this Decl, we
451 // should parse the comment in context of that other Decl. This is important
452 // because comments can contain references to parameter names which can be
453 // different across redeclarations.
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000454 if (D != OriginalDecl)
Dmitri Gribenko19523542012-09-29 11:40:46 +0000455 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000456
Dmitri Gribenko19523542012-09-29 11:40:46 +0000457 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000458 ParsedComments[Canonical] = FC;
459 return FC;
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000460}
461
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000462void
463ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
464 TemplateTemplateParmDecl *Parm) {
465 ID.AddInteger(Parm->getDepth());
466 ID.AddInteger(Parm->getPosition());
Douglas Gregor61c4d282011-01-05 15:48:55 +0000467 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000468
469 TemplateParameterList *Params = Parm->getTemplateParameters();
470 ID.AddInteger(Params->size());
471 for (TemplateParameterList::const_iterator P = Params->begin(),
472 PEnd = Params->end();
473 P != PEnd; ++P) {
474 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
475 ID.AddInteger(0);
476 ID.AddBoolean(TTP->isParameterPack());
477 continue;
478 }
479
480 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
481 ID.AddInteger(1);
Douglas Gregor61c4d282011-01-05 15:48:55 +0000482 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman9e9c4542012-03-07 01:09:33 +0000483 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000484 if (NTTP->isExpandedParameterPack()) {
485 ID.AddBoolean(true);
486 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman9e9c4542012-03-07 01:09:33 +0000487 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
488 QualType T = NTTP->getExpansionType(I);
489 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
490 }
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000491 } else
492 ID.AddBoolean(false);
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000493 continue;
494 }
495
496 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
497 ID.AddInteger(2);
498 Profile(ID, TTP);
499 }
500}
501
502TemplateTemplateParmDecl *
503ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad4ba2a172011-01-12 09:06:06 +0000504 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000505 // Check if we already have a canonical template template parameter.
506 llvm::FoldingSetNodeID ID;
507 CanonicalTemplateTemplateParm::Profile(ID, TTP);
508 void *InsertPos = 0;
509 CanonicalTemplateTemplateParm *Canonical
510 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
511 if (Canonical)
512 return Canonical->getParam();
513
514 // Build a canonical template parameter list.
515 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000516 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000517 CanonParams.reserve(Params->size());
518 for (TemplateParameterList::const_iterator P = Params->begin(),
519 PEnd = Params->end();
520 P != PEnd; ++P) {
521 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
522 CanonParams.push_back(
523 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnara344577e2011-03-06 15:48:19 +0000524 SourceLocation(),
525 SourceLocation(),
526 TTP->getDepth(),
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000527 TTP->getIndex(), 0, false,
528 TTP->isParameterPack()));
529 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000530 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
531 QualType T = getCanonicalType(NTTP->getType());
532 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
533 NonTypeTemplateParmDecl *Param;
534 if (NTTP->isExpandedParameterPack()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000535 SmallVector<QualType, 2> ExpandedTypes;
536 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000537 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
538 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
539 ExpandedTInfos.push_back(
540 getTrivialTypeSourceInfo(ExpandedTypes.back()));
541 }
542
543 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000544 SourceLocation(),
545 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000546 NTTP->getDepth(),
547 NTTP->getPosition(), 0,
548 T,
549 TInfo,
550 ExpandedTypes.data(),
551 ExpandedTypes.size(),
552 ExpandedTInfos.data());
553 } else {
554 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000555 SourceLocation(),
556 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000557 NTTP->getDepth(),
558 NTTP->getPosition(), 0,
559 T,
560 NTTP->isParameterPack(),
561 TInfo);
562 }
563 CanonParams.push_back(Param);
564
565 } else
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000566 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
567 cast<TemplateTemplateParmDecl>(*P)));
568 }
569
570 TemplateTemplateParmDecl *CanonTTP
571 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
572 SourceLocation(), TTP->getDepth(),
Douglas Gregor61c4d282011-01-05 15:48:55 +0000573 TTP->getPosition(),
574 TTP->isParameterPack(),
575 0,
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000576 TemplateParameterList::Create(*this, SourceLocation(),
577 SourceLocation(),
578 CanonParams.data(),
579 CanonParams.size(),
580 SourceLocation()));
581
582 // Get the new insert position for the node we care about.
583 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
584 assert(Canonical == 0 && "Shouldn't be in the map!");
585 (void)Canonical;
586
587 // Create the canonical template template parameter entry.
588 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
589 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
590 return CanonTTP;
591}
592
Charles Davis071cc7d2010-08-16 03:33:14 +0000593CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCallee79a4c2010-08-21 22:46:04 +0000594 if (!LangOpts.CPlusPlus) return 0;
595
John McCallb8b2c9d2013-01-25 22:30:49 +0000596 switch (T.getCXXABI().getKind()) {
597 case TargetCXXABI::GenericARM:
598 case TargetCXXABI::iOS:
John McCallee79a4c2010-08-21 22:46:04 +0000599 return CreateARMCXXABI(*this);
Tim Northoverc264e162013-01-31 12:13:10 +0000600 case TargetCXXABI::GenericAArch64: // Same as Itanium at this level
John McCallb8b2c9d2013-01-25 22:30:49 +0000601 case TargetCXXABI::GenericItanium:
Charles Davis071cc7d2010-08-16 03:33:14 +0000602 return CreateItaniumCXXABI(*this);
John McCallb8b2c9d2013-01-25 22:30:49 +0000603 case TargetCXXABI::Microsoft:
Charles Davis20cf7172010-08-19 02:18:14 +0000604 return CreateMicrosoftCXXABI(*this);
605 }
David Blaikie7530c032012-01-17 06:56:22 +0000606 llvm_unreachable("Invalid CXXABI type!");
Charles Davis071cc7d2010-08-16 03:33:14 +0000607}
608
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000609static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000610 const LangOptions &LOpts) {
611 if (LOpts.FakeAddressSpaceMap) {
612 // The fake address space map must have a distinct entry for each
613 // language-specific address space.
614 static const unsigned FakeAddrSpaceMap[] = {
615 1, // opencl_global
616 2, // opencl_local
Peter Collingbourne4dc34eb2012-05-20 21:08:35 +0000617 3, // opencl_constant
618 4, // cuda_device
619 5, // cuda_constant
620 6 // cuda_shared
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000621 };
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000622 return &FakeAddrSpaceMap;
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000623 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000624 return &T.getAddressSpaceMap();
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000625 }
626}
627
Douglas Gregor3e3cd932011-09-01 20:23:19 +0000628ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000629 const TargetInfo *t,
Daniel Dunbare91593e2008-08-11 04:54:23 +0000630 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000631 Builtin::Context &builtins,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000632 unsigned size_reserve,
633 bool DelayInitialization)
634 : FunctionProtoTypes(this_()),
635 TemplateSpecializationTypes(this_()),
636 DependentTemplateSpecializationTypes(this_()),
637 SubstTemplateTemplateParmPacks(this_()),
638 GlobalNestedNameSpecifier(0),
639 Int128Decl(0), UInt128Decl(0),
Meador Ingec5613b22012-06-16 03:34:49 +0000640 BuiltinVaListDecl(0),
Douglas Gregora6ea10e2012-01-17 18:09:05 +0000641 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Fariborz Jahanian96171302012-08-30 18:49:41 +0000642 BOOLDecl(0),
Douglas Gregore97179c2011-09-08 01:46:34 +0000643 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000644 FILEDecl(0),
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +0000645 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
646 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
647 cudaConfigureCallDecl(0),
Douglas Gregore6649772011-12-03 00:30:27 +0000648 NullTypeSourceInfo(QualType()),
649 FirstLocalImport(), LastLocalImport(),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000650 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregor30c42402011-09-27 22:38:19 +0000651 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000652 Idents(idents), Selectors(sels),
653 BuiltinInfo(builtins),
654 DeclarationNames(*this),
Douglas Gregor30c42402011-09-27 22:38:19 +0000655 ExternalSource(0), Listener(0),
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000656 Comments(SM), CommentsLoaded(false),
Dmitri Gribenkoe4330a32012-09-10 20:32:42 +0000657 CommentCommandTraits(BumpAlloc),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000658 LastSDM(0, 0),
Fariborz Jahanianf7992132013-01-04 18:45:40 +0000659 UniqueBlockByRefTypeID(0)
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000660{
Mike Stump1eb44332009-09-09 15:08:12 +0000661 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +0000662 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000663
664 if (!DelayInitialization) {
665 assert(t && "No target supplied for ASTContext initialization");
666 InitBuiltinTypes(*t);
667 }
Daniel Dunbare91593e2008-08-11 04:54:23 +0000668}
669
Reid Spencer5f016e22007-07-11 17:01:13 +0000670ASTContext::~ASTContext() {
Ted Kremenek3478eb62010-02-11 07:12:28 +0000671 // Release the DenseMaps associated with DeclContext objects.
672 // FIXME: Is this the ideal solution?
673 ReleaseDeclContextMaps();
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000674
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000675 // Call all of the deallocation functions.
676 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
677 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor00545312010-05-23 18:26:36 +0000678
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000679 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000680 // because they can contain DenseMaps.
681 for (llvm::DenseMap<const ObjCContainerDecl*,
682 const ASTRecordLayout*>::iterator
683 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
684 // Increment in loop to prevent using deallocated memory.
685 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
686 R->Destroy(*this);
687
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000688 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
689 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
690 // Increment in loop to prevent using deallocated memory.
691 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
692 R->Destroy(*this);
693 }
Douglas Gregor63200642010-08-30 16:49:28 +0000694
695 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
696 AEnd = DeclAttrs.end();
697 A != AEnd; ++A)
698 A->second->~AttrVec();
699}
Douglas Gregorab452ba2009-03-26 23:50:42 +0000700
Douglas Gregor00545312010-05-23 18:26:36 +0000701void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
702 Deallocations.push_back(std::make_pair(Callback, Data));
703}
704
Mike Stump1eb44332009-09-09 15:08:12 +0000705void
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000706ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregor2cf26342009-04-09 22:27:44 +0000707 ExternalSource.reset(Source.take());
708}
709
Reid Spencer5f016e22007-07-11 17:01:13 +0000710void ASTContext::PrintStats() const {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000711 llvm::errs() << "\n*** AST Context Stats:\n";
712 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000713
Douglas Gregordbe833d2009-05-26 14:40:08 +0000714 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000715#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000716#define ABSTRACT_TYPE(Name, Parent)
717#include "clang/AST/TypeNodes.def"
718 0 // Extra
719 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000720
Reid Spencer5f016e22007-07-11 17:01:13 +0000721 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
722 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000723 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000724 }
725
Douglas Gregordbe833d2009-05-26 14:40:08 +0000726 unsigned Idx = 0;
727 unsigned TotalBytes = 0;
728#define TYPE(Name, Parent) \
729 if (counts[Idx]) \
Chandler Carruthcd92a652011-07-04 05:32:14 +0000730 llvm::errs() << " " << counts[Idx] << " " << #Name \
731 << " types\n"; \
Douglas Gregordbe833d2009-05-26 14:40:08 +0000732 TotalBytes += counts[Idx] * sizeof(Name##Type); \
733 ++Idx;
734#define ABSTRACT_TYPE(Name, Parent)
735#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000736
Chandler Carruthcd92a652011-07-04 05:32:14 +0000737 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
738
Douglas Gregor4923aa22010-07-02 20:37:36 +0000739 // Implicit special member functions.
Chandler Carruthcd92a652011-07-04 05:32:14 +0000740 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
741 << NumImplicitDefaultConstructors
742 << " implicit default constructors created\n";
743 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
744 << NumImplicitCopyConstructors
745 << " implicit copy constructors created\n";
David Blaikie4e4d0842012-03-11 07:00:24 +0000746 if (getLangOpts().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000747 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
748 << NumImplicitMoveConstructors
749 << " implicit move constructors created\n";
750 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
751 << NumImplicitCopyAssignmentOperators
752 << " implicit copy assignment operators created\n";
David Blaikie4e4d0842012-03-11 07:00:24 +0000753 if (getLangOpts().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000754 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
755 << NumImplicitMoveAssignmentOperators
756 << " implicit move assignment operators created\n";
757 llvm::errs() << NumImplicitDestructorsDeclared << "/"
758 << NumImplicitDestructors
759 << " implicit destructors created\n";
760
Douglas Gregor2cf26342009-04-09 22:27:44 +0000761 if (ExternalSource.get()) {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000762 llvm::errs() << "\n";
Douglas Gregor2cf26342009-04-09 22:27:44 +0000763 ExternalSource->PrintStats();
764 }
Chandler Carruthcd92a652011-07-04 05:32:14 +0000765
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000766 BumpAlloc.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000767}
768
Douglas Gregor772eeae2011-08-12 06:49:56 +0000769TypedefDecl *ASTContext::getInt128Decl() const {
770 if (!Int128Decl) {
771 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
772 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
773 getTranslationUnitDecl(),
774 SourceLocation(),
775 SourceLocation(),
776 &Idents.get("__int128_t"),
777 TInfo);
778 }
779
780 return Int128Decl;
781}
782
783TypedefDecl *ASTContext::getUInt128Decl() const {
784 if (!UInt128Decl) {
785 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
786 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
787 getTranslationUnitDecl(),
788 SourceLocation(),
789 SourceLocation(),
790 &Idents.get("__uint128_t"),
791 TInfo);
792 }
793
794 return UInt128Decl;
795}
Reid Spencer5f016e22007-07-11 17:01:13 +0000796
John McCalle27ec8a2009-10-23 23:03:21 +0000797void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000798 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000799 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000800 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000801}
802
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000803void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
804 assert((!this->Target || this->Target == &Target) &&
805 "Incorrect target reinitialization");
Reid Spencer5f016e22007-07-11 17:01:13 +0000806 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000807
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000808 this->Target = &Target;
809
810 ABI.reset(createCXXABI(Target));
811 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
812
Reid Spencer5f016e22007-07-11 17:01:13 +0000813 // C99 6.2.5p19.
814 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000815
Reid Spencer5f016e22007-07-11 17:01:13 +0000816 // C99 6.2.5p2.
817 InitBuiltinType(BoolTy, BuiltinType::Bool);
818 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000819 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000820 InitBuiltinType(CharTy, BuiltinType::Char_S);
821 else
822 InitBuiltinType(CharTy, BuiltinType::Char_U);
823 // C99 6.2.5p4.
824 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
825 InitBuiltinType(ShortTy, BuiltinType::Short);
826 InitBuiltinType(IntTy, BuiltinType::Int);
827 InitBuiltinType(LongTy, BuiltinType::Long);
828 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000829
Reid Spencer5f016e22007-07-11 17:01:13 +0000830 // C99 6.2.5p6.
831 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
832 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
833 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
834 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
835 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000836
Reid Spencer5f016e22007-07-11 17:01:13 +0000837 // C99 6.2.5p10.
838 InitBuiltinType(FloatTy, BuiltinType::Float);
839 InitBuiltinType(DoubleTy, BuiltinType::Double);
840 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000841
Chris Lattner2df9ced2009-04-30 02:43:43 +0000842 // GNU extension, 128-bit integers.
843 InitBuiltinType(Int128Ty, BuiltinType::Int128);
844 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
845
Abramo Bagnarae75bb612012-09-09 10:13:32 +0000846 if (LangOpts.CPlusPlus && LangOpts.WChar) { // C++ 3.9.1p5
Eli Friedmand3d77cd2011-04-30 19:24:24 +0000847 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattner3f59c972010-12-25 23:25:43 +0000848 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
849 else // -fshort-wchar makes wchar_t be unsigned.
850 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
Abramo Bagnarae75bb612012-09-09 10:13:32 +0000851 } else // C99 (or C++ using -fno-wchar)
Chris Lattner3a250322009-02-26 23:43:47 +0000852 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000853
James Molloy392da482012-05-04 10:55:22 +0000854 WIntTy = getFromTargetType(Target.getWIntType());
855
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000856 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
857 InitBuiltinType(Char16Ty, BuiltinType::Char16);
858 else // C99
859 Char16Ty = getFromTargetType(Target.getChar16Type());
860
861 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
862 InitBuiltinType(Char32Ty, BuiltinType::Char32);
863 else // C99
864 Char32Ty = getFromTargetType(Target.getChar32Type());
865
Douglas Gregor898574e2008-12-05 23:32:09 +0000866 // Placeholder type for type-dependent expressions whose type is
867 // completely unknown. No code should ever check a type against
868 // DependentTy and users should never see it; however, it is here to
869 // help diagnose failures to properly check for type-dependent
870 // expressions.
871 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000872
John McCall2a984ca2010-10-12 00:20:44 +0000873 // Placeholder type for functions.
874 InitBuiltinType(OverloadTy, BuiltinType::Overload);
875
John McCall864c0412011-04-26 20:42:42 +0000876 // Placeholder type for bound members.
877 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
878
John McCall3c3b7f92011-10-25 17:37:35 +0000879 // Placeholder type for pseudo-objects.
880 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
881
John McCall1de4d4e2011-04-07 08:22:57 +0000882 // "any" type; useful for debugger-like clients.
883 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
884
John McCall0ddaeb92011-10-17 18:09:15 +0000885 // Placeholder type for unbridged ARC casts.
886 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
887
Eli Friedmana6c66ce2012-08-31 00:14:07 +0000888 // Placeholder type for builtin functions.
889 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
890
Reid Spencer5f016e22007-07-11 17:01:13 +0000891 // C99 6.2.5p11.
892 FloatComplexTy = getComplexType(FloatTy);
893 DoubleComplexTy = getComplexType(DoubleTy);
894 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000895
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000896 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000897 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
898 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000899 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeib13621d2012-12-18 14:38:23 +0000900
901 if (LangOpts.OpenCL) {
902 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
903 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
904 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
905 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
906 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
907 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
Guy Benyeie6b9d802013-01-20 12:31:11 +0000908
909 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Guy Benyeib13621d2012-12-18 14:38:23 +0000910 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000911
912 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian93a49942012-04-16 21:03:30 +0000913 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
914 SignedCharTy : BoolTy);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000915
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000916 ObjCConstantStringType = QualType();
Fariborz Jahanianf7992132013-01-04 18:45:40 +0000917
918 ObjCSuperType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000919
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000920 // void * type
921 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000922
923 // nullptr type (C++0x 2.14.7)
924 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000925
926 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
927 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingefb40e3f2012-07-01 15:57:25 +0000928
929 // Builtin type used to help define __builtin_va_list.
930 VaListTagTy = QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000931}
932
David Blaikied6471f72011-09-25 23:23:43 +0000933DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +0000934 return SourceMgr.getDiagnostics();
935}
936
Douglas Gregor63200642010-08-30 16:49:28 +0000937AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
938 AttrVec *&Result = DeclAttrs[D];
939 if (!Result) {
940 void *Mem = Allocate(sizeof(AttrVec));
941 Result = new (Mem) AttrVec;
942 }
943
944 return *Result;
945}
946
947/// \brief Erase the attributes corresponding to the given declaration.
948void ASTContext::eraseDeclAttrs(const Decl *D) {
949 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
950 if (Pos != DeclAttrs.end()) {
951 Pos->second->~AttrVec();
952 DeclAttrs.erase(Pos);
953 }
954}
955
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000956MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000957ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000958 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000959 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000960 = InstantiatedFromStaticDataMember.find(Var);
961 if (Pos == InstantiatedFromStaticDataMember.end())
962 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000963
Douglas Gregor7caa6822009-07-24 20:34:43 +0000964 return Pos->second;
965}
966
Mike Stump1eb44332009-09-09 15:08:12 +0000967void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000968ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000969 TemplateSpecializationKind TSK,
970 SourceLocation PointOfInstantiation) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000971 assert(Inst->isStaticDataMember() && "Not a static data member");
972 assert(Tmpl->isStaticDataMember() && "Not a static data member");
973 assert(!InstantiatedFromStaticDataMember[Inst] &&
974 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000975 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000976 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000977}
978
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000979FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
980 const FunctionDecl *FD){
981 assert(FD && "Specialization is 0");
982 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet0d95f0d2011-08-14 14:28:49 +0000983 = ClassScopeSpecializationPattern.find(FD);
984 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000985 return 0;
986
987 return Pos->second;
988}
989
990void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
991 FunctionDecl *Pattern) {
992 assert(FD && "Specialization is 0");
993 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet0d95f0d2011-08-14 14:28:49 +0000994 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000995}
996
John McCall7ba107a2009-11-18 02:36:19 +0000997NamedDecl *
John McCalled976492009-12-04 22:46:56 +0000998ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +0000999 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +00001000 = InstantiatedFromUsingDecl.find(UUD);
1001 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +00001002 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001003
Anders Carlsson0d8df782009-08-29 19:37:28 +00001004 return Pos->second;
1005}
1006
1007void
John McCalled976492009-12-04 22:46:56 +00001008ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1009 assert((isa<UsingDecl>(Pattern) ||
1010 isa<UnresolvedUsingValueDecl>(Pattern) ||
1011 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1012 "pattern decl is not a using decl");
1013 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1014 InstantiatedFromUsingDecl[Inst] = Pattern;
1015}
1016
1017UsingShadowDecl *
1018ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1019 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1020 = InstantiatedFromUsingShadowDecl.find(Inst);
1021 if (Pos == InstantiatedFromUsingShadowDecl.end())
1022 return 0;
1023
1024 return Pos->second;
1025}
1026
1027void
1028ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1029 UsingShadowDecl *Pattern) {
1030 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1031 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00001032}
1033
Anders Carlssond8b285f2009-09-01 04:26:58 +00001034FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1035 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1036 = InstantiatedFromUnnamedFieldDecl.find(Field);
1037 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1038 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001039
Anders Carlssond8b285f2009-09-01 04:26:58 +00001040 return Pos->second;
1041}
1042
1043void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1044 FieldDecl *Tmpl) {
1045 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1046 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1047 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1048 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +00001049
Anders Carlssond8b285f2009-09-01 04:26:58 +00001050 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1051}
1052
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +00001053bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
1054 const FieldDecl *LastFD) const {
1055 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001056 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +00001057}
1058
Fariborz Jahanian340fa242011-05-02 17:20:56 +00001059bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
1060 const FieldDecl *LastFD) const {
1061 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001062 FD->getBitWidthValue(*this) == 0 &&
1063 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanian340fa242011-05-02 17:20:56 +00001064}
1065
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +00001066bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
1067 const FieldDecl *LastFD) const {
1068 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001069 FD->getBitWidthValue(*this) &&
1070 LastFD->getBitWidthValue(*this));
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +00001071}
1072
Chad Rosierdd7fddb2011-08-04 23:34:15 +00001073bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +00001074 const FieldDecl *LastFD) const {
1075 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001076 LastFD->getBitWidthValue(*this));
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +00001077}
1078
Chad Rosierdd7fddb2011-08-04 23:34:15 +00001079bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +00001080 const FieldDecl *LastFD) const {
1081 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001082 FD->getBitWidthValue(*this));
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +00001083}
1084
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001085ASTContext::overridden_cxx_method_iterator
1086ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1087 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001088 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001089 if (Pos == OverriddenMethods.end())
1090 return 0;
1091
1092 return Pos->second.begin();
1093}
1094
1095ASTContext::overridden_cxx_method_iterator
1096ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1097 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001098 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001099 if (Pos == OverriddenMethods.end())
1100 return 0;
1101
1102 return Pos->second.end();
1103}
1104
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +00001105unsigned
1106ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1107 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001108 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +00001109 if (Pos == OverriddenMethods.end())
1110 return 0;
1111
1112 return Pos->second.size();
1113}
1114
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001115void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1116 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001117 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001118 OverriddenMethods[Method].push_back(Overridden);
1119}
1120
Dmitri Gribenko1e905da2012-11-03 14:24:57 +00001121void ASTContext::getOverriddenMethods(
1122 const NamedDecl *D,
1123 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001124 assert(D);
1125
1126 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisbc0a2bb2012-10-09 20:08:43 +00001127 Overridden.append(CXXMethod->begin_overridden_methods(),
1128 CXXMethod->end_overridden_methods());
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001129 return;
1130 }
1131
1132 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1133 if (!Method)
1134 return;
1135
Argyrios Kyrtzidis740ae672012-10-09 18:19:01 +00001136 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1137 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisbc0a2bb2012-10-09 20:08:43 +00001138 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001139}
1140
Douglas Gregore6649772011-12-03 00:30:27 +00001141void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1142 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1143 assert(!Import->isFromASTFile() && "Non-local import declaration");
1144 if (!FirstLocalImport) {
1145 FirstLocalImport = Import;
1146 LastLocalImport = Import;
1147 return;
1148 }
1149
1150 LastLocalImport->NextLocalImport = Import;
1151 LastLocalImport = Import;
1152}
1153
Chris Lattner464175b2007-07-18 17:52:12 +00001154//===----------------------------------------------------------------------===//
1155// Type Sizing and Analysis
1156//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +00001157
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001158/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1159/// scalar floating point type.
1160const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +00001161 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001162 assert(BT && "Not a floating point type!");
1163 switch (BT->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001164 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001165 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001166 case BuiltinType::Float: return Target->getFloatFormat();
1167 case BuiltinType::Double: return Target->getDoubleFormat();
1168 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001169 }
1170}
1171
Ken Dyck8b752f12010-01-27 17:10:57 +00001172/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +00001173/// specified decl. Note that bitfields do not have a valid alignment, so
1174/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +00001175/// If @p RefAsPointee, references are treated like their underlying type
1176/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad4ba2a172011-01-12 09:06:06 +00001177CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001178 unsigned Align = Target->getCharWidth();
Eli Friedmandcdafb62009-02-22 02:56:25 +00001179
John McCall4081a5c2010-10-08 18:24:19 +00001180 bool UseAlignAttrOnly = false;
1181 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1182 Align = AlignFromAttr;
Eli Friedmandcdafb62009-02-22 02:56:25 +00001183
John McCall4081a5c2010-10-08 18:24:19 +00001184 // __attribute__((aligned)) can increase or decrease alignment
1185 // *except* on a struct or struct member, where it only increases
1186 // alignment unless 'packed' is also specified.
1187 //
Peter Collingbourne82d0b0a2011-09-29 18:04:28 +00001188 // It is an error for alignas to decrease alignment, so we can
John McCall4081a5c2010-10-08 18:24:19 +00001189 // ignore that possibility; Sema should diagnose it.
1190 if (isa<FieldDecl>(D)) {
1191 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1192 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1193 } else {
1194 UseAlignAttrOnly = true;
1195 }
1196 }
Fariborz Jahanian78a7d7d2011-05-05 21:19:14 +00001197 else if (isa<FieldDecl>(D))
1198 UseAlignAttrOnly =
1199 D->hasAttr<PackedAttr>() ||
1200 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall4081a5c2010-10-08 18:24:19 +00001201
John McCallba4f5d52011-01-20 07:57:12 +00001202 // If we're using the align attribute only, just ignore everything
1203 // else about the declaration and its type.
John McCall4081a5c2010-10-08 18:24:19 +00001204 if (UseAlignAttrOnly) {
John McCallba4f5d52011-01-20 07:57:12 +00001205 // do nothing
1206
John McCall4081a5c2010-10-08 18:24:19 +00001207 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00001208 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001209 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00001210 if (RefAsPointee)
1211 T = RT->getPointeeType();
1212 else
1213 T = getPointerType(RT->getPointeeType());
1214 }
1215 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall3b657512011-01-19 10:06:00 +00001216 // Adjust alignments of declarations with array type by the
1217 // large-array alignment on the target.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001218 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall3b657512011-01-19 10:06:00 +00001219 const ArrayType *arrayType;
1220 if (MinWidth && (arrayType = getAsArrayType(T))) {
1221 if (isa<VariableArrayType>(arrayType))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001222 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall3b657512011-01-19 10:06:00 +00001223 else if (isa<ConstantArrayType>(arrayType) &&
1224 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001225 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedmandcdafb62009-02-22 02:56:25 +00001226
John McCall3b657512011-01-19 10:06:00 +00001227 // Walk through any array types while we're at it.
1228 T = getBaseElementType(arrayType);
1229 }
Chad Rosier9f1210c2011-07-26 07:03:04 +00001230 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedmandcdafb62009-02-22 02:56:25 +00001231 }
John McCallba4f5d52011-01-20 07:57:12 +00001232
1233 // Fields can be subject to extra alignment constraints, like if
1234 // the field is packed, the struct is packed, or the struct has a
1235 // a max-field-alignment constraint (#pragma pack). So calculate
1236 // the actual alignment of the field within the struct, and then
1237 // (as we're expected to) constrain that by the alignment of the type.
1238 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
1239 // So calculate the alignment of the field.
1240 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
1241
1242 // Start with the record's overall alignment.
Ken Dyckdac54c12011-02-15 02:32:40 +00001243 unsigned fieldAlign = toBits(layout.getAlignment());
John McCallba4f5d52011-01-20 07:57:12 +00001244
1245 // Use the GCD of that and the offset within the record.
1246 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
1247 if (offset > 0) {
1248 // Alignment is always a power of 2, so the GCD will be a power of 2,
1249 // which means we get to do this crazy thing instead of Euclid's.
1250 uint64_t lowBitOfOffset = offset & (~offset + 1);
1251 if (lowBitOfOffset < fieldAlign)
1252 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
1253 }
1254
1255 Align = std::min(Align, fieldAlign);
Charles Davis05f62472010-02-23 04:52:00 +00001256 }
Chris Lattneraf707ab2009-01-24 21:53:27 +00001257 }
Eli Friedmandcdafb62009-02-22 02:56:25 +00001258
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001259 return toCharUnitsFromBits(Align);
Chris Lattneraf707ab2009-01-24 21:53:27 +00001260}
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001261
John McCall929bbfb2012-08-21 04:10:00 +00001262// getTypeInfoDataSizeInChars - Return the size of a type, in
1263// chars. If the type is a record, its data size is returned. This is
1264// the size of the memcpy that's performed when assigning this type
1265// using a trivial copy/move assignment operator.
1266std::pair<CharUnits, CharUnits>
1267ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1268 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1269
1270 // In C++, objects can sometimes be allocated into the tail padding
1271 // of a base-class subobject. We decide whether that's possible
1272 // during class layout, so here we can just trust the layout results.
1273 if (getLangOpts().CPlusPlus) {
1274 if (const RecordType *RT = T->getAs<RecordType>()) {
1275 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1276 sizeAndAlign.first = layout.getDataSize();
1277 }
1278 }
1279
1280 return sizeAndAlign;
1281}
1282
John McCallea1471e2010-05-20 01:18:31 +00001283std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +00001284ASTContext::getTypeInfoInChars(const Type *T) const {
John McCallea1471e2010-05-20 01:18:31 +00001285 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001286 return std::make_pair(toCharUnitsFromBits(Info.first),
1287 toCharUnitsFromBits(Info.second));
John McCallea1471e2010-05-20 01:18:31 +00001288}
1289
1290std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +00001291ASTContext::getTypeInfoInChars(QualType T) const {
John McCallea1471e2010-05-20 01:18:31 +00001292 return getTypeInfoInChars(T.getTypePtr());
1293}
1294
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001295std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1296 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1297 if (it != MemoizedTypeInfo.end())
1298 return it->second;
1299
1300 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1301 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1302 return Info;
1303}
1304
1305/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1306/// method does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +00001307///
1308/// FIXME: Pointers into different addr spaces could have different sizes and
1309/// alignment requirements: getPointerInfo should take an AddrSpace, this
1310/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +00001311std::pair<uint64_t, unsigned>
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001312ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5e301002009-02-27 18:32:39 +00001313 uint64_t Width=0;
1314 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +00001315 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +00001316#define TYPE(Class, Base)
1317#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +00001318#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +00001319#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1320#include "clang/AST/TypeNodes.def"
John McCalld3d49bb2011-06-28 16:49:23 +00001321 llvm_unreachable("Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +00001322
Chris Lattner692233e2007-07-13 22:27:08 +00001323 case Type::FunctionNoProto:
1324 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +00001325 // GCC extension: alignof(function) = 32 bits
1326 Width = 0;
1327 Align = 32;
1328 break;
1329
Douglas Gregor72564e72009-02-26 23:50:07 +00001330 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +00001331 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +00001332 Width = 0;
1333 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1334 break;
1335
Steve Narofffb22d962007-08-30 01:06:46 +00001336 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001337 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001338
Chris Lattner98be4942008-03-05 18:54:05 +00001339 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarafea966a2011-12-13 11:23:52 +00001340 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001341 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1342 "Overflow in array type bit size evaluation");
Abramo Bagnarafea966a2011-12-13 11:23:52 +00001343 Width = EltInfo.first*Size;
Chris Lattner030d8842007-07-19 22:06:24 +00001344 Align = EltInfo.second;
Argyrios Kyrtzidiscd88b412011-04-26 21:05:39 +00001345 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattner030d8842007-07-19 22:06:24 +00001346 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +00001347 }
Nate Begeman213541a2008-04-18 23:10:10 +00001348 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +00001349 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +00001350 const VectorType *VT = cast<VectorType>(T);
1351 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1352 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +00001353 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +00001354 // If the alignment is not a power of 2, round up to the next power of 2.
1355 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +00001356 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +00001357 Align = llvm::NextPowerOf2(Align);
1358 Width = llvm::RoundUpToAlignment(Width, Align);
1359 }
Chad Rosierf9e9af72012-07-13 23:57:43 +00001360 // Adjust the alignment based on the target max.
1361 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1362 if (TargetVectorAlign && TargetVectorAlign < Align)
1363 Align = TargetVectorAlign;
Chris Lattner030d8842007-07-19 22:06:24 +00001364 break;
1365 }
Chris Lattner5d2a6302007-07-18 18:26:58 +00001366
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001367 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +00001368 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001369 default: llvm_unreachable("Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +00001370 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +00001371 // GCC extension: alignof(void) = 8 bits.
1372 Width = 0;
1373 Align = 8;
1374 break;
1375
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001376 case BuiltinType::Bool:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001377 Width = Target->getBoolWidth();
1378 Align = Target->getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001379 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001380 case BuiltinType::Char_S:
1381 case BuiltinType::Char_U:
1382 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001383 case BuiltinType::SChar:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001384 Width = Target->getCharWidth();
1385 Align = Target->getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001386 break;
Chris Lattner3f59c972010-12-25 23:25:43 +00001387 case BuiltinType::WChar_S:
1388 case BuiltinType::WChar_U:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001389 Width = Target->getWCharWidth();
1390 Align = Target->getWCharAlign();
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00001391 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001392 case BuiltinType::Char16:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001393 Width = Target->getChar16Width();
1394 Align = Target->getChar16Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001395 break;
1396 case BuiltinType::Char32:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001397 Width = Target->getChar32Width();
1398 Align = Target->getChar32Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001399 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001400 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001401 case BuiltinType::Short:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001402 Width = Target->getShortWidth();
1403 Align = Target->getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001404 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001405 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001406 case BuiltinType::Int:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001407 Width = Target->getIntWidth();
1408 Align = Target->getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001409 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001410 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001411 case BuiltinType::Long:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001412 Width = Target->getLongWidth();
1413 Align = Target->getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001414 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001415 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001416 case BuiltinType::LongLong:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001417 Width = Target->getLongLongWidth();
1418 Align = Target->getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001419 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +00001420 case BuiltinType::Int128:
1421 case BuiltinType::UInt128:
1422 Width = 128;
1423 Align = 128; // int128_t is 128-bit aligned on all targets.
1424 break;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001425 case BuiltinType::Half:
1426 Width = Target->getHalfWidth();
1427 Align = Target->getHalfAlign();
1428 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001429 case BuiltinType::Float:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001430 Width = Target->getFloatWidth();
1431 Align = Target->getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001432 break;
1433 case BuiltinType::Double:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001434 Width = Target->getDoubleWidth();
1435 Align = Target->getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001436 break;
1437 case BuiltinType::LongDouble:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001438 Width = Target->getLongDoubleWidth();
1439 Align = Target->getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001440 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001441 case BuiltinType::NullPtr:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001442 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1443 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +00001444 break;
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +00001445 case BuiltinType::ObjCId:
1446 case BuiltinType::ObjCClass:
1447 case BuiltinType::ObjCSel:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001448 Width = Target->getPointerWidth(0);
1449 Align = Target->getPointerAlign(0);
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +00001450 break;
Guy Benyeie6b9d802013-01-20 12:31:11 +00001451 case BuiltinType::OCLEvent:
Guy Benyeib13621d2012-12-18 14:38:23 +00001452 case BuiltinType::OCLImage1d:
1453 case BuiltinType::OCLImage1dArray:
1454 case BuiltinType::OCLImage1dBuffer:
1455 case BuiltinType::OCLImage2d:
1456 case BuiltinType::OCLImage2dArray:
1457 case BuiltinType::OCLImage3d:
1458 // Currently these types are pointers to opaque types.
1459 Width = Target->getPointerWidth(0);
1460 Align = Target->getPointerAlign(0);
1461 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001462 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +00001463 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001464 case Type::ObjCObjectPointer:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001465 Width = Target->getPointerWidth(0);
1466 Align = Target->getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001467 break;
Steve Naroff485eeff2008-09-24 15:05:44 +00001468 case Type::BlockPointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001469 unsigned AS = getTargetAddressSpace(
1470 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001471 Width = Target->getPointerWidth(AS);
1472 Align = Target->getPointerAlign(AS);
Steve Naroff485eeff2008-09-24 15:05:44 +00001473 break;
1474 }
Sebastian Redl5d484e82009-11-23 17:18:46 +00001475 case Type::LValueReference:
1476 case Type::RValueReference: {
1477 // alignof and sizeof should never enter this code path here, so we go
1478 // the pointer route.
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001479 unsigned AS = getTargetAddressSpace(
1480 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001481 Width = Target->getPointerWidth(AS);
1482 Align = Target->getPointerAlign(AS);
Sebastian Redl5d484e82009-11-23 17:18:46 +00001483 break;
1484 }
Chris Lattnerf72a4432008-03-08 08:34:58 +00001485 case Type::Pointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001486 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001487 Width = Target->getPointerWidth(AS);
1488 Align = Target->getPointerAlign(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +00001489 break;
1490 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00001491 case Type::MemberPointer: {
Charles Davis071cc7d2010-08-16 03:33:14 +00001492 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001493 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +00001494 getTypeInfo(getPointerDiffType());
Charles Davis071cc7d2010-08-16 03:33:14 +00001495 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson1cca74e2009-05-17 02:06:04 +00001496 Align = PtrDiffInfo.second;
1497 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +00001498 }
Chris Lattner5d2a6302007-07-18 18:26:58 +00001499 case Type::Complex: {
1500 // Complex types have the same alignment as their elements, but twice the
1501 // size.
Mike Stump1eb44332009-09-09 15:08:12 +00001502 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +00001503 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001504 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +00001505 Align = EltInfo.second;
1506 break;
1507 }
John McCallc12c5bb2010-05-15 11:32:37 +00001508 case Type::ObjCObject:
1509 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +00001510 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001511 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +00001512 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001513 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001514 Align = toBits(Layout.getAlignment());
Devang Patel44a3dde2008-06-04 21:54:36 +00001515 break;
1516 }
Douglas Gregor72564e72009-02-26 23:50:07 +00001517 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00001518 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001519 const TagType *TT = cast<TagType>(T);
1520
1521 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor22ce41d2011-04-20 17:29:44 +00001522 Width = 8;
1523 Align = 8;
Chris Lattner8389eab2008-08-09 21:35:13 +00001524 break;
1525 }
Mike Stump1eb44332009-09-09 15:08:12 +00001526
Daniel Dunbar1d751182008-11-08 05:48:37 +00001527 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +00001528 return getTypeInfo(ET->getDecl()->getIntegerType());
1529
Daniel Dunbar1d751182008-11-08 05:48:37 +00001530 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +00001531 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001532 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001533 Align = toBits(Layout.getAlignment());
Chris Lattnerdc0d73e2007-07-23 22:46:22 +00001534 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001535 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001536
Chris Lattner9fcfe922009-10-22 05:17:15 +00001537 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +00001538 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1539 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +00001540
Richard Smith34b41d92011-02-20 03:19:35 +00001541 case Type::Auto: {
1542 const AutoType *A = cast<AutoType>(T);
1543 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gaydc856af2011-02-22 20:00:16 +00001544 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith34b41d92011-02-20 03:19:35 +00001545 }
1546
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001547 case Type::Paren:
1548 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1549
Douglas Gregor18857642009-04-30 17:32:17 +00001550 case Type::Typedef: {
Richard Smith162e1c12011-04-15 14:24:37 +00001551 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregordf1367a2010-08-27 00:11:28 +00001552 std::pair<uint64_t, unsigned> Info
1553 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattnerc1de52d2011-02-19 22:55:41 +00001554 // If the typedef has an aligned attribute on it, it overrides any computed
1555 // alignment we have. This violates the GCC documentation (which says that
1556 // attribute(aligned) can only round up) but matches its implementation.
1557 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1558 Align = AttrAlign;
1559 else
1560 Align = Info.second;
Douglas Gregordf1367a2010-08-27 00:11:28 +00001561 Width = Info.first;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001562 break;
Chris Lattner71763312008-04-06 22:05:18 +00001563 }
Douglas Gregor18857642009-04-30 17:32:17 +00001564
1565 case Type::TypeOfExpr:
1566 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1567 .getTypePtr());
1568
1569 case Type::TypeOf:
1570 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1571
Anders Carlsson395b4752009-06-24 19:06:50 +00001572 case Type::Decltype:
1573 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1574 .getTypePtr());
1575
Sean Huntca63c202011-05-24 22:41:36 +00001576 case Type::UnaryTransform:
1577 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1578
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001579 case Type::Elaborated:
1580 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +00001581
John McCall9d156a72011-01-06 01:58:22 +00001582 case Type::Attributed:
1583 return getTypeInfo(
1584 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1585
Richard Smith3e4c6c42011-05-05 21:57:07 +00001586 case Type::TemplateSpecialization: {
Mike Stump1eb44332009-09-09 15:08:12 +00001587 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +00001588 "Cannot request the size of a dependent type");
Richard Smith3e4c6c42011-05-05 21:57:07 +00001589 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1590 // A type alias template specialization may refer to a typedef with the
1591 // aligned attribute on it.
1592 if (TST->isTypeAlias())
1593 return getTypeInfo(TST->getAliasedType().getTypePtr());
1594 else
1595 return getTypeInfo(getCanonicalType(T));
1596 }
1597
Eli Friedmanb001de72011-10-06 23:00:33 +00001598 case Type::Atomic: {
Eli Friedman2be46072011-10-14 20:59:01 +00001599 std::pair<uint64_t, unsigned> Info
1600 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1601 Width = Info.first;
1602 Align = Info.second;
1603 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1604 llvm::isPowerOf2_64(Width)) {
1605 // We can potentially perform lock-free atomic operations for this
1606 // type; promote the alignment appropriately.
1607 // FIXME: We could potentially promote the width here as well...
1608 // is that worthwhile? (Non-struct atomic types generally have
1609 // power-of-two size anyway, but structs might not. Requires a bit
1610 // of implementation work to make sure we zero out the extra bits.)
1611 Align = static_cast<unsigned>(Width);
1612 }
Eli Friedmanb001de72011-10-06 23:00:33 +00001613 }
1614
Douglas Gregor18857642009-04-30 17:32:17 +00001615 }
Mike Stump1eb44332009-09-09 15:08:12 +00001616
Eli Friedman2be46072011-10-14 20:59:01 +00001617 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001618 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +00001619}
1620
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001621/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1622CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1623 return CharUnits::fromQuantity(BitSize / getCharWidth());
1624}
1625
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001626/// toBits - Convert a size in characters to a size in characters.
1627int64_t ASTContext::toBits(CharUnits CharSize) const {
1628 return CharSize.getQuantity() * getCharWidth();
1629}
1630
Ken Dyckbdc601b2009-12-22 14:23:30 +00001631/// getTypeSizeInChars - Return the size of the specified type, in characters.
1632/// This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001633CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001634 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +00001635}
Jay Foad4ba2a172011-01-12 09:06:06 +00001636CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001637 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +00001638}
1639
Ken Dyck16e20cc2010-01-26 17:25:18 +00001640/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +00001641/// characters. This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001642CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001643 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001644}
Jay Foad4ba2a172011-01-12 09:06:06 +00001645CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001646 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001647}
1648
Chris Lattner34ebde42009-01-27 18:08:34 +00001649/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1650/// type for the current target in bits. This can be different than the ABI
1651/// alignment in cases where it is beneficial for performance to overalign
1652/// a data type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001653unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattner34ebde42009-01-27 18:08:34 +00001654 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +00001655
1656 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +00001657 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +00001658 T = CT->getElementType().getTypePtr();
1659 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosiercde7a1d2012-03-21 20:20:47 +00001660 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1661 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman1eed6022009-05-25 21:27:19 +00001662 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1663
Chris Lattner34ebde42009-01-27 18:08:34 +00001664 return ABIAlign;
1665}
1666
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001667/// DeepCollectObjCIvars -
1668/// This routine first collects all declared, but not synthesized, ivars in
1669/// super class and then collects all ivars, including those synthesized for
1670/// current class. This routine is used for implementation of current class
1671/// when all ivars, declared and synthesized are known.
Fariborz Jahanian98200742009-05-12 18:14:29 +00001672///
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001673void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1674 bool leafClass,
Jordy Rosedb8264e2011-07-22 02:08:32 +00001675 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001676 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1677 DeepCollectObjCIvars(SuperClass, false, Ivars);
1678 if (!leafClass) {
1679 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1680 E = OI->ivar_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001681 Ivars.push_back(*I);
Chad Rosier30601782011-08-17 23:08:45 +00001682 } else {
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001683 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosedb8264e2011-07-22 02:08:32 +00001684 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001685 Iv= Iv->getNextIvar())
1686 Ivars.push_back(Iv);
1687 }
Fariborz Jahanian98200742009-05-12 18:14:29 +00001688}
1689
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001690/// CollectInheritedProtocols - Collect all protocols in current class and
1691/// those inherited by it.
1692void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001693 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001694 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001695 // We can use protocol_iterator here instead of
1696 // all_referenced_protocol_iterator since we are walking all categories.
1697 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1698 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001699 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001700 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001701 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001702 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001703 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001704 CollectInheritedProtocols(*P, Protocols);
1705 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001706 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001707
1708 // Categories of this Interface.
Douglas Gregord3297242013-01-16 23:00:23 +00001709 for (ObjCInterfaceDecl::visible_categories_iterator
1710 Cat = OI->visible_categories_begin(),
1711 CatEnd = OI->visible_categories_end();
1712 Cat != CatEnd; ++Cat) {
1713 CollectInheritedProtocols(*Cat, Protocols);
1714 }
1715
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001716 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1717 while (SD) {
1718 CollectInheritedProtocols(SD, Protocols);
1719 SD = SD->getSuperClass();
1720 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001721 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001722 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001723 PE = OC->protocol_end(); P != PE; ++P) {
1724 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001725 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001726 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1727 PE = Proto->protocol_end(); P != PE; ++P)
1728 CollectInheritedProtocols(*P, Protocols);
1729 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001730 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001731 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1732 PE = OP->protocol_end(); P != PE; ++P) {
1733 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001734 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001735 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1736 PE = Proto->protocol_end(); P != PE; ++P)
1737 CollectInheritedProtocols(*P, Protocols);
1738 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001739 }
1740}
1741
Jay Foad4ba2a172011-01-12 09:06:06 +00001742unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001743 unsigned count = 0;
1744 // Count ivars declared in class extension.
Douglas Gregord3297242013-01-16 23:00:23 +00001745 for (ObjCInterfaceDecl::known_extensions_iterator
1746 Ext = OI->known_extensions_begin(),
1747 ExtEnd = OI->known_extensions_end();
1748 Ext != ExtEnd; ++Ext) {
1749 count += Ext->ivar_size();
1750 }
1751
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001752 // Count ivar defined in this class's implementation. This
1753 // includes synthesized ivars.
1754 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001755 count += ImplDecl->ivar_size();
1756
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001757 return count;
1758}
1759
Argyrios Kyrtzidis8deabc12012-02-03 05:58:16 +00001760bool ASTContext::isSentinelNullExpr(const Expr *E) {
1761 if (!E)
1762 return false;
1763
1764 // nullptr_t is always treated as null.
1765 if (E->getType()->isNullPtrType()) return true;
1766
1767 if (E->getType()->isAnyPointerType() &&
1768 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1769 Expr::NPC_ValueDependentIsNull))
1770 return true;
1771
1772 // Unfortunately, __null has type 'int'.
1773 if (isa<GNUNullExpr>(E)) return true;
1774
1775 return false;
1776}
1777
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +00001778/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1779ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1780 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1781 I = ObjCImpls.find(D);
1782 if (I != ObjCImpls.end())
1783 return cast<ObjCImplementationDecl>(I->second);
1784 return 0;
1785}
1786/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1787ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1788 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1789 I = ObjCImpls.find(D);
1790 if (I != ObjCImpls.end())
1791 return cast<ObjCCategoryImplDecl>(I->second);
1792 return 0;
1793}
1794
1795/// \brief Set the implementation of ObjCInterfaceDecl.
1796void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1797 ObjCImplementationDecl *ImplD) {
1798 assert(IFaceD && ImplD && "Passed null params");
1799 ObjCImpls[IFaceD] = ImplD;
1800}
1801/// \brief Set the implementation of ObjCCategoryDecl.
1802void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1803 ObjCCategoryImplDecl *ImplD) {
1804 assert(CatD && ImplD && "Passed null params");
1805 ObjCImpls[CatD] = ImplD;
1806}
1807
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001808ObjCInterfaceDecl *ASTContext::getObjContainingInterface(NamedDecl *ND) const {
1809 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1810 return ID;
1811 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1812 return CD->getClassInterface();
1813 if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1814 return IMD->getClassInterface();
1815
1816 return 0;
1817}
1818
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001819/// \brief Get the copy initialization expression of VarDecl,or NULL if
1820/// none exists.
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001821Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001822 assert(VD && "Passed null params");
1823 assert(VD->hasAttr<BlocksAttr>() &&
1824 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001825 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001826 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001827 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1828}
1829
1830/// \brief Set the copy inialization expression of a block var decl.
1831void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1832 assert(VD && Init && "Passed null params");
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001833 assert(VD->hasAttr<BlocksAttr>() &&
1834 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001835 BlockVarCopyInits[VD] = Init;
1836}
1837
John McCalla93c9342009-12-07 02:54:59 +00001838TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001839 unsigned DataSize) const {
John McCall109de5e2009-10-21 00:23:54 +00001840 if (!DataSize)
1841 DataSize = TypeLoc::getFullDataSizeForType(T);
1842 else
1843 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001844 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001845
John McCalla93c9342009-12-07 02:54:59 +00001846 TypeSourceInfo *TInfo =
1847 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1848 new (TInfo) TypeSourceInfo(T);
1849 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001850}
1851
John McCalla93c9342009-12-07 02:54:59 +00001852TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001853 SourceLocation L) const {
John McCalla93c9342009-12-07 02:54:59 +00001854 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregorc21c7e92011-01-25 19:13:18 +00001855 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCalla4eb74d2009-10-23 21:14:09 +00001856 return DI;
1857}
1858
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001859const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001860ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001861 return getObjCLayout(D, 0);
1862}
1863
1864const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001865ASTContext::getASTObjCImplementationLayout(
1866 const ObjCImplementationDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001867 return getObjCLayout(D->getClassInterface(), D);
1868}
1869
Chris Lattnera7674d82007-07-13 22:13:22 +00001870//===----------------------------------------------------------------------===//
1871// Type creation/memoization methods
1872//===----------------------------------------------------------------------===//
1873
Jay Foad4ba2a172011-01-12 09:06:06 +00001874QualType
John McCall3b657512011-01-19 10:06:00 +00001875ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1876 unsigned fastQuals = quals.getFastQualifiers();
1877 quals.removeFastQualifiers();
John McCall0953e762009-09-24 19:53:00 +00001878
1879 // Check if we've already instantiated this type.
1880 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001881 ExtQuals::Profile(ID, baseType, quals);
1882 void *insertPos = 0;
1883 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1884 assert(eq->getQualifiers() == quals);
1885 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001886 }
1887
John McCall3b657512011-01-19 10:06:00 +00001888 // If the base type is not canonical, make the appropriate canonical type.
1889 QualType canon;
1890 if (!baseType->isCanonicalUnqualified()) {
1891 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall200fa532012-02-08 00:46:36 +00001892 canonSplit.Quals.addConsistentQualifiers(quals);
1893 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00001894
1895 // Re-find the insert position.
1896 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1897 }
1898
1899 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1900 ExtQualNodes.InsertNode(eq, insertPos);
1901 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001902}
1903
Jay Foad4ba2a172011-01-12 09:06:06 +00001904QualType
1905ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001906 QualType CanT = getCanonicalType(T);
1907 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001908 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001909
John McCall0953e762009-09-24 19:53:00 +00001910 // If we are composing extended qualifiers together, merge together
1911 // into one ExtQuals node.
1912 QualifierCollector Quals;
1913 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001914
John McCall0953e762009-09-24 19:53:00 +00001915 // If this type already has an address space specified, it cannot get
1916 // another one.
1917 assert(!Quals.hasAddressSpace() &&
1918 "Type cannot be in multiple addr spaces!");
1919 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001920
John McCall0953e762009-09-24 19:53:00 +00001921 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001922}
1923
Chris Lattnerb7d25532009-02-18 22:53:11 +00001924QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001925 Qualifiers::GC GCAttr) const {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001926 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001927 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001928 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001929
John McCall7f040a92010-12-24 02:08:15 +00001930 if (const PointerType *ptr = T->getAs<PointerType>()) {
1931 QualType Pointee = ptr->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001932 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001933 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1934 return getPointerType(ResultType);
1935 }
1936 }
Mike Stump1eb44332009-09-09 15:08:12 +00001937
John McCall0953e762009-09-24 19:53:00 +00001938 // If we are composing extended qualifiers together, merge together
1939 // into one ExtQuals node.
1940 QualifierCollector Quals;
1941 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001942
John McCall0953e762009-09-24 19:53:00 +00001943 // If this type already has an ObjCGC specified, it cannot get
1944 // another one.
1945 assert(!Quals.hasObjCGCAttr() &&
1946 "Type cannot have multiple ObjCGCs!");
1947 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001948
John McCall0953e762009-09-24 19:53:00 +00001949 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001950}
Chris Lattnera7674d82007-07-13 22:13:22 +00001951
John McCalle6a365d2010-12-19 02:44:49 +00001952const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1953 FunctionType::ExtInfo Info) {
1954 if (T->getExtInfo() == Info)
1955 return T;
1956
1957 QualType Result;
1958 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1959 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1960 } else {
1961 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1962 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1963 EPI.ExtInfo = Info;
1964 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1965 FPT->getNumArgs(), EPI);
1966 }
1967
1968 return cast<FunctionType>(Result.getTypePtr());
1969}
1970
Reid Spencer5f016e22007-07-11 17:01:13 +00001971/// getComplexType - Return the uniqued reference to the type for a complex
1972/// number with the specified element type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001973QualType ASTContext::getComplexType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001974 // Unique pointers, to guarantee there is only one pointer of a particular
1975 // structure.
1976 llvm::FoldingSetNodeID ID;
1977 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001978
Reid Spencer5f016e22007-07-11 17:01:13 +00001979 void *InsertPos = 0;
1980 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1981 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001982
Reid Spencer5f016e22007-07-11 17:01:13 +00001983 // If the pointee type isn't canonical, this won't be a canonical type either,
1984 // so fill in the canonical type field.
1985 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001986 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001987 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001988
Reid Spencer5f016e22007-07-11 17:01:13 +00001989 // Get the new insert position for the node we care about.
1990 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001991 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001992 }
John McCall6b304a02009-09-24 23:30:46 +00001993 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001994 Types.push_back(New);
1995 ComplexTypes.InsertNode(New, InsertPos);
1996 return QualType(New, 0);
1997}
1998
Reid Spencer5f016e22007-07-11 17:01:13 +00001999/// getPointerType - Return the uniqued reference to the type for a pointer to
2000/// the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002001QualType ASTContext::getPointerType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002002 // Unique pointers, to guarantee there is only one pointer of a particular
2003 // structure.
2004 llvm::FoldingSetNodeID ID;
2005 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00002006
Reid Spencer5f016e22007-07-11 17:01:13 +00002007 void *InsertPos = 0;
2008 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2009 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002010
Reid Spencer5f016e22007-07-11 17:01:13 +00002011 // If the pointee type isn't canonical, this won't be a canonical type either,
2012 // so fill in the canonical type field.
2013 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002014 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002015 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00002016
Reid Spencer5f016e22007-07-11 17:01:13 +00002017 // Get the new insert position for the node we care about.
2018 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002019 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002020 }
John McCall6b304a02009-09-24 23:30:46 +00002021 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00002022 Types.push_back(New);
2023 PointerTypes.InsertNode(New, InsertPos);
2024 return QualType(New, 0);
2025}
2026
Mike Stump1eb44332009-09-09 15:08:12 +00002027/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00002028/// a pointer to the specified block.
Jay Foad4ba2a172011-01-12 09:06:06 +00002029QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff296e8d52008-08-28 19:20:44 +00002030 assert(T->isFunctionType() && "block of function types only");
2031 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00002032 // structure.
2033 llvm::FoldingSetNodeID ID;
2034 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00002035
Steve Naroff5618bd42008-08-27 16:04:49 +00002036 void *InsertPos = 0;
2037 if (BlockPointerType *PT =
2038 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2039 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002040
2041 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00002042 // type either so fill in the canonical type field.
2043 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002044 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00002045 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00002046
Steve Naroff5618bd42008-08-27 16:04:49 +00002047 // Get the new insert position for the node we care about.
2048 BlockPointerType *NewIP =
2049 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002050 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00002051 }
John McCall6b304a02009-09-24 23:30:46 +00002052 BlockPointerType *New
2053 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00002054 Types.push_back(New);
2055 BlockPointerTypes.InsertNode(New, InsertPos);
2056 return QualType(New, 0);
2057}
2058
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002059/// getLValueReferenceType - Return the uniqued reference to the type for an
2060/// lvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002061QualType
2062ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor9625e442011-05-21 22:16:50 +00002063 assert(getCanonicalType(T) != OverloadTy &&
2064 "Unresolved overloaded function type");
2065
Reid Spencer5f016e22007-07-11 17:01:13 +00002066 // Unique pointers, to guarantee there is only one pointer of a particular
2067 // structure.
2068 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00002069 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00002070
2071 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002072 if (LValueReferenceType *RT =
2073 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002074 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002075
John McCall54e14c42009-10-22 22:37:11 +00002076 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2077
Reid Spencer5f016e22007-07-11 17:01:13 +00002078 // If the referencee type isn't canonical, this won't be a canonical type
2079 // either, so fill in the canonical type field.
2080 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00002081 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2082 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2083 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002084
Reid Spencer5f016e22007-07-11 17:01:13 +00002085 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002086 LValueReferenceType *NewIP =
2087 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002088 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002089 }
2090
John McCall6b304a02009-09-24 23:30:46 +00002091 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00002092 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2093 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00002094 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002095 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00002096
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002097 return QualType(New, 0);
2098}
2099
2100/// getRValueReferenceType - Return the uniqued reference to the type for an
2101/// rvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002102QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002103 // Unique pointers, to guarantee there is only one pointer of a particular
2104 // structure.
2105 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00002106 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002107
2108 void *InsertPos = 0;
2109 if (RValueReferenceType *RT =
2110 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2111 return QualType(RT, 0);
2112
John McCall54e14c42009-10-22 22:37:11 +00002113 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2114
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002115 // If the referencee type isn't canonical, this won't be a canonical type
2116 // either, so fill in the canonical type field.
2117 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00002118 if (InnerRef || !T.isCanonical()) {
2119 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2120 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002121
2122 // Get the new insert position for the node we care about.
2123 RValueReferenceType *NewIP =
2124 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002125 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002126 }
2127
John McCall6b304a02009-09-24 23:30:46 +00002128 RValueReferenceType *New
2129 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002130 Types.push_back(New);
2131 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002132 return QualType(New, 0);
2133}
2134
Sebastian Redlf30208a2009-01-24 21:16:55 +00002135/// getMemberPointerType - Return the uniqued reference to the type for a
2136/// member pointer to the specified type, in the specified class.
Jay Foad4ba2a172011-01-12 09:06:06 +00002137QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redlf30208a2009-01-24 21:16:55 +00002138 // Unique pointers, to guarantee there is only one pointer of a particular
2139 // structure.
2140 llvm::FoldingSetNodeID ID;
2141 MemberPointerType::Profile(ID, T, Cls);
2142
2143 void *InsertPos = 0;
2144 if (MemberPointerType *PT =
2145 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2146 return QualType(PT, 0);
2147
2148 // If the pointee or class type isn't canonical, this won't be a canonical
2149 // type either, so fill in the canonical type field.
2150 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00002151 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00002152 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2153
2154 // Get the new insert position for the node we care about.
2155 MemberPointerType *NewIP =
2156 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002157 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redlf30208a2009-01-24 21:16:55 +00002158 }
John McCall6b304a02009-09-24 23:30:46 +00002159 MemberPointerType *New
2160 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00002161 Types.push_back(New);
2162 MemberPointerTypes.InsertNode(New, InsertPos);
2163 return QualType(New, 0);
2164}
2165
Mike Stump1eb44332009-09-09 15:08:12 +00002166/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00002167/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002168QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00002169 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00002170 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002171 unsigned IndexTypeQuals) const {
Sebastian Redl923d56d2009-11-05 15:52:31 +00002172 assert((EltTy->isDependentType() ||
2173 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00002174 "Constant array of VLAs is illegal!");
2175
Chris Lattner38aeec72009-05-13 04:12:56 +00002176 // Convert the array size into a canonical width matching the pointer size for
2177 // the target.
2178 llvm::APInt ArySize(ArySizeIn);
Jay Foad9f71a8f2010-12-07 08:25:34 +00002179 ArySize =
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002180 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump1eb44332009-09-09 15:08:12 +00002181
Reid Spencer5f016e22007-07-11 17:01:13 +00002182 llvm::FoldingSetNodeID ID;
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002183 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00002184
Reid Spencer5f016e22007-07-11 17:01:13 +00002185 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002186 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002187 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002188 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002189
John McCall3b657512011-01-19 10:06:00 +00002190 // If the element type isn't canonical or has qualifiers, this won't
2191 // be a canonical type either, so fill in the canonical type field.
2192 QualType Canon;
2193 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2194 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00002195 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002196 ASM, IndexTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00002197 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00002198
Reid Spencer5f016e22007-07-11 17:01:13 +00002199 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00002200 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002201 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002202 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002203 }
Mike Stump1eb44332009-09-09 15:08:12 +00002204
John McCall6b304a02009-09-24 23:30:46 +00002205 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002206 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002207 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002208 Types.push_back(New);
2209 return QualType(New, 0);
2210}
2211
John McCallce889032011-01-18 08:40:38 +00002212/// getVariableArrayDecayedType - Turns the given type, which may be
2213/// variably-modified, into the corresponding type with all the known
2214/// sizes replaced with [*].
2215QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2216 // Vastly most common case.
2217 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002218
John McCallce889032011-01-18 08:40:38 +00002219 QualType result;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002220
John McCallce889032011-01-18 08:40:38 +00002221 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00002222 const Type *ty = split.Ty;
John McCallce889032011-01-18 08:40:38 +00002223 switch (ty->getTypeClass()) {
2224#define TYPE(Class, Base)
2225#define ABSTRACT_TYPE(Class, Base)
2226#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2227#include "clang/AST/TypeNodes.def"
2228 llvm_unreachable("didn't desugar past all non-canonical types?");
2229
2230 // These types should never be variably-modified.
2231 case Type::Builtin:
2232 case Type::Complex:
2233 case Type::Vector:
2234 case Type::ExtVector:
2235 case Type::DependentSizedExtVector:
2236 case Type::ObjCObject:
2237 case Type::ObjCInterface:
2238 case Type::ObjCObjectPointer:
2239 case Type::Record:
2240 case Type::Enum:
2241 case Type::UnresolvedUsing:
2242 case Type::TypeOfExpr:
2243 case Type::TypeOf:
2244 case Type::Decltype:
Sean Huntca63c202011-05-24 22:41:36 +00002245 case Type::UnaryTransform:
John McCallce889032011-01-18 08:40:38 +00002246 case Type::DependentName:
2247 case Type::InjectedClassName:
2248 case Type::TemplateSpecialization:
2249 case Type::DependentTemplateSpecialization:
2250 case Type::TemplateTypeParm:
2251 case Type::SubstTemplateTypeParmPack:
Richard Smith34b41d92011-02-20 03:19:35 +00002252 case Type::Auto:
John McCallce889032011-01-18 08:40:38 +00002253 case Type::PackExpansion:
2254 llvm_unreachable("type should never be variably-modified");
2255
2256 // These types can be variably-modified but should never need to
2257 // further decay.
2258 case Type::FunctionNoProto:
2259 case Type::FunctionProto:
2260 case Type::BlockPointer:
2261 case Type::MemberPointer:
2262 return type;
2263
2264 // These types can be variably-modified. All these modifications
2265 // preserve structure except as noted by comments.
2266 // TODO: if we ever care about optimizing VLAs, there are no-op
2267 // optimizations available here.
2268 case Type::Pointer:
2269 result = getPointerType(getVariableArrayDecayedType(
2270 cast<PointerType>(ty)->getPointeeType()));
2271 break;
2272
2273 case Type::LValueReference: {
2274 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2275 result = getLValueReferenceType(
2276 getVariableArrayDecayedType(lv->getPointeeType()),
2277 lv->isSpelledAsLValue());
2278 break;
2279 }
2280
2281 case Type::RValueReference: {
2282 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2283 result = getRValueReferenceType(
2284 getVariableArrayDecayedType(lv->getPointeeType()));
2285 break;
2286 }
2287
Eli Friedmanb001de72011-10-06 23:00:33 +00002288 case Type::Atomic: {
2289 const AtomicType *at = cast<AtomicType>(ty);
2290 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2291 break;
2292 }
2293
John McCallce889032011-01-18 08:40:38 +00002294 case Type::ConstantArray: {
2295 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2296 result = getConstantArrayType(
2297 getVariableArrayDecayedType(cat->getElementType()),
2298 cat->getSize(),
2299 cat->getSizeModifier(),
2300 cat->getIndexTypeCVRQualifiers());
2301 break;
2302 }
2303
2304 case Type::DependentSizedArray: {
2305 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2306 result = getDependentSizedArrayType(
2307 getVariableArrayDecayedType(dat->getElementType()),
2308 dat->getSizeExpr(),
2309 dat->getSizeModifier(),
2310 dat->getIndexTypeCVRQualifiers(),
2311 dat->getBracketsRange());
2312 break;
2313 }
2314
2315 // Turn incomplete types into [*] types.
2316 case Type::IncompleteArray: {
2317 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2318 result = getVariableArrayType(
2319 getVariableArrayDecayedType(iat->getElementType()),
2320 /*size*/ 0,
2321 ArrayType::Normal,
2322 iat->getIndexTypeCVRQualifiers(),
2323 SourceRange());
2324 break;
2325 }
2326
2327 // Turn VLA types into [*] types.
2328 case Type::VariableArray: {
2329 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2330 result = getVariableArrayType(
2331 getVariableArrayDecayedType(vat->getElementType()),
2332 /*size*/ 0,
2333 ArrayType::Star,
2334 vat->getIndexTypeCVRQualifiers(),
2335 vat->getBracketsRange());
2336 break;
2337 }
2338 }
2339
2340 // Apply the top-level qualifiers from the original.
John McCall200fa532012-02-08 00:46:36 +00002341 return getQualifiedType(result, split.Quals);
John McCallce889032011-01-18 08:40:38 +00002342}
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002343
Steve Naroffbdbf7b02007-08-30 18:14:25 +00002344/// getVariableArrayType - Returns a non-unique reference to the type for a
2345/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002346QualType ASTContext::getVariableArrayType(QualType EltTy,
2347 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00002348 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002349 unsigned IndexTypeQuals,
Jay Foad4ba2a172011-01-12 09:06:06 +00002350 SourceRange Brackets) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00002351 // Since we don't unique expressions, it isn't possible to unique VLA's
2352 // that have an expression provided for their size.
John McCall3b657512011-01-19 10:06:00 +00002353 QualType Canon;
Douglas Gregor715e9c82010-05-23 16:10:32 +00002354
John McCall3b657512011-01-19 10:06:00 +00002355 // Be sure to pull qualifiers off the element type.
2356 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2357 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00002358 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002359 IndexTypeQuals, Brackets);
John McCall200fa532012-02-08 00:46:36 +00002360 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor715e9c82010-05-23 16:10:32 +00002361 }
2362
John McCall6b304a02009-09-24 23:30:46 +00002363 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002364 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002365
2366 VariableArrayTypes.push_back(New);
2367 Types.push_back(New);
2368 return QualType(New, 0);
2369}
2370
Douglas Gregor898574e2008-12-05 23:32:09 +00002371/// getDependentSizedArrayType - Returns a non-unique reference to
2372/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00002373/// type.
John McCall3b657512011-01-19 10:06:00 +00002374QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2375 Expr *numElements,
Douglas Gregor898574e2008-12-05 23:32:09 +00002376 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00002377 unsigned elementTypeQuals,
2378 SourceRange brackets) const {
2379 assert((!numElements || numElements->isTypeDependent() ||
2380 numElements->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00002381 "Size must be type- or value-dependent!");
2382
John McCall3b657512011-01-19 10:06:00 +00002383 // Dependently-sized array types that do not have a specified number
2384 // of elements will have their sizes deduced from a dependent
2385 // initializer. We do no canonicalization here at all, which is okay
2386 // because they can't be used in most locations.
2387 if (!numElements) {
2388 DependentSizedArrayType *newType
2389 = new (*this, TypeAlignment)
2390 DependentSizedArrayType(*this, elementType, QualType(),
2391 numElements, ASM, elementTypeQuals,
2392 brackets);
2393 Types.push_back(newType);
2394 return QualType(newType, 0);
2395 }
2396
2397 // Otherwise, we actually build a new type every time, but we
2398 // also build a canonical type.
2399
2400 SplitQualType canonElementType = getCanonicalType(elementType).split();
2401
2402 void *insertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00002403 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00002404 DependentSizedArrayType::Profile(ID, *this,
John McCall200fa532012-02-08 00:46:36 +00002405 QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002406 ASM, elementTypeQuals, numElements);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002407
John McCall3b657512011-01-19 10:06:00 +00002408 // Look for an existing type with these properties.
2409 DependentSizedArrayType *canonTy =
2410 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002411
John McCall3b657512011-01-19 10:06:00 +00002412 // If we don't have one, build one.
2413 if (!canonTy) {
2414 canonTy = new (*this, TypeAlignment)
John McCall200fa532012-02-08 00:46:36 +00002415 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002416 QualType(), numElements, ASM, elementTypeQuals,
2417 brackets);
2418 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2419 Types.push_back(canonTy);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002420 }
2421
John McCall3b657512011-01-19 10:06:00 +00002422 // Apply qualifiers from the element type to the array.
2423 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall200fa532012-02-08 00:46:36 +00002424 canonElementType.Quals);
Mike Stump1eb44332009-09-09 15:08:12 +00002425
John McCall3b657512011-01-19 10:06:00 +00002426 // If we didn't need extra canonicalization for the element type,
2427 // then just use that as our result.
John McCall200fa532012-02-08 00:46:36 +00002428 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall3b657512011-01-19 10:06:00 +00002429 return canon;
2430
2431 // Otherwise, we need to build a type which follows the spelling
2432 // of the element type.
2433 DependentSizedArrayType *sugaredType
2434 = new (*this, TypeAlignment)
2435 DependentSizedArrayType(*this, elementType, canon, numElements,
2436 ASM, elementTypeQuals, brackets);
2437 Types.push_back(sugaredType);
2438 return QualType(sugaredType, 0);
Douglas Gregor898574e2008-12-05 23:32:09 +00002439}
2440
John McCall3b657512011-01-19 10:06:00 +00002441QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanc5773c42008-02-15 18:16:39 +00002442 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00002443 unsigned elementTypeQuals) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00002444 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00002445 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002446
John McCall3b657512011-01-19 10:06:00 +00002447 void *insertPos = 0;
2448 if (IncompleteArrayType *iat =
2449 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2450 return QualType(iat, 0);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002451
2452 // If the element type isn't canonical, this won't be a canonical type
John McCall3b657512011-01-19 10:06:00 +00002453 // either, so fill in the canonical type field. We also have to pull
2454 // qualifiers off the element type.
2455 QualType canon;
Eli Friedmanc5773c42008-02-15 18:16:39 +00002456
John McCall3b657512011-01-19 10:06:00 +00002457 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2458 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall200fa532012-02-08 00:46:36 +00002459 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002460 ASM, elementTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00002461 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002462
2463 // Get the new insert position for the node we care about.
John McCall3b657512011-01-19 10:06:00 +00002464 IncompleteArrayType *existing =
2465 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2466 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00002467 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00002468
John McCall3b657512011-01-19 10:06:00 +00002469 IncompleteArrayType *newType = new (*this, TypeAlignment)
2470 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002471
John McCall3b657512011-01-19 10:06:00 +00002472 IncompleteArrayTypes.InsertNode(newType, insertPos);
2473 Types.push_back(newType);
2474 return QualType(newType, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00002475}
2476
Steve Naroff73322922007-07-18 18:00:27 +00002477/// getVectorType - Return the unique reference to a vector type of
2478/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00002479QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad4ba2a172011-01-12 09:06:06 +00002480 VectorType::VectorKind VecKind) const {
John McCall3b657512011-01-19 10:06:00 +00002481 assert(vecType->isBuiltinType());
Mike Stump1eb44332009-09-09 15:08:12 +00002482
Reid Spencer5f016e22007-07-11 17:01:13 +00002483 // Check if we've already instantiated a vector of this type.
2484 llvm::FoldingSetNodeID ID;
Bob Wilsone86d78c2010-11-10 21:56:12 +00002485 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner788b0fd2010-06-23 06:00:24 +00002486
Reid Spencer5f016e22007-07-11 17:01:13 +00002487 void *InsertPos = 0;
2488 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2489 return QualType(VTP, 0);
2490
2491 // If the element type isn't canonical, this won't be a canonical type either,
2492 // so fill in the canonical type field.
2493 QualType Canonical;
Douglas Gregor255210e2010-08-06 10:14:59 +00002494 if (!vecType.isCanonical()) {
Bob Wilson231da7e2010-11-16 00:32:20 +00002495 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump1eb44332009-09-09 15:08:12 +00002496
Reid Spencer5f016e22007-07-11 17:01:13 +00002497 // Get the new insert position for the node we care about.
2498 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002499 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002500 }
John McCall6b304a02009-09-24 23:30:46 +00002501 VectorType *New = new (*this, TypeAlignment)
Bob Wilsone86d78c2010-11-10 21:56:12 +00002502 VectorType(vecType, NumElts, Canonical, VecKind);
Reid Spencer5f016e22007-07-11 17:01:13 +00002503 VectorTypes.InsertNode(New, InsertPos);
2504 Types.push_back(New);
2505 return QualType(New, 0);
2506}
2507
Nate Begeman213541a2008-04-18 23:10:10 +00002508/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00002509/// the specified element type and size. VectorType must be a built-in type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002510QualType
2511ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor4ac01402011-06-15 16:02:29 +00002512 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump1eb44332009-09-09 15:08:12 +00002513
Steve Naroff73322922007-07-18 18:00:27 +00002514 // Check if we've already instantiated a vector of this type.
2515 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00002516 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsone86d78c2010-11-10 21:56:12 +00002517 VectorType::GenericVector);
Steve Naroff73322922007-07-18 18:00:27 +00002518 void *InsertPos = 0;
2519 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2520 return QualType(VTP, 0);
2521
2522 // If the element type isn't canonical, this won't be a canonical type either,
2523 // so fill in the canonical type field.
2524 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002525 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00002526 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00002527
Steve Naroff73322922007-07-18 18:00:27 +00002528 // Get the new insert position for the node we care about.
2529 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002530 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00002531 }
John McCall6b304a02009-09-24 23:30:46 +00002532 ExtVectorType *New = new (*this, TypeAlignment)
2533 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00002534 VectorTypes.InsertNode(New, InsertPos);
2535 Types.push_back(New);
2536 return QualType(New, 0);
2537}
2538
Jay Foad4ba2a172011-01-12 09:06:06 +00002539QualType
2540ASTContext::getDependentSizedExtVectorType(QualType vecType,
2541 Expr *SizeExpr,
2542 SourceLocation AttrLoc) const {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002543 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00002544 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002545 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002546
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002547 void *InsertPos = 0;
2548 DependentSizedExtVectorType *Canon
2549 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2550 DependentSizedExtVectorType *New;
2551 if (Canon) {
2552 // We already have a canonical version of this array type; use it as
2553 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00002554 New = new (*this, TypeAlignment)
2555 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2556 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002557 } else {
2558 QualType CanonVecTy = getCanonicalType(vecType);
2559 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00002560 New = new (*this, TypeAlignment)
2561 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2562 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002563
2564 DependentSizedExtVectorType *CanonCheck
2565 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2566 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2567 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002568 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2569 } else {
2570 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2571 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00002572 New = new (*this, TypeAlignment)
2573 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002574 }
2575 }
Mike Stump1eb44332009-09-09 15:08:12 +00002576
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00002577 Types.push_back(New);
2578 return QualType(New, 0);
2579}
2580
Douglas Gregor72564e72009-02-26 23:50:07 +00002581/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00002582///
Jay Foad4ba2a172011-01-12 09:06:06 +00002583QualType
2584ASTContext::getFunctionNoProtoType(QualType ResultTy,
2585 const FunctionType::ExtInfo &Info) const {
Roman Divackycfe9af22011-03-01 17:40:53 +00002586 const CallingConv DefaultCC = Info.getCC();
2587 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2588 CC_X86StdCall : DefaultCC;
Reid Spencer5f016e22007-07-11 17:01:13 +00002589 // Unique functions, to guarantee there is only one function of a particular
2590 // structure.
2591 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00002592 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00002593
Reid Spencer5f016e22007-07-11 17:01:13 +00002594 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002595 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00002596 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002597 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002598
Reid Spencer5f016e22007-07-11 17:01:13 +00002599 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00002600 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00002601 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00002602 Canonical =
2603 getFunctionNoProtoType(getCanonicalType(ResultTy),
2604 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump1eb44332009-09-09 15:08:12 +00002605
Reid Spencer5f016e22007-07-11 17:01:13 +00002606 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002607 FunctionNoProtoType *NewIP =
2608 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002609 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002610 }
Mike Stump1eb44332009-09-09 15:08:12 +00002611
Roman Divackycfe9af22011-03-01 17:40:53 +00002612 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall6b304a02009-09-24 23:30:46 +00002613 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divackycfe9af22011-03-01 17:40:53 +00002614 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00002615 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00002616 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002617 return QualType(New, 0);
2618}
2619
Douglas Gregor02dd7982013-01-17 23:36:45 +00002620/// \brief Determine whether \p T is canonical as the result type of a function.
2621static bool isCanonicalResultType(QualType T) {
2622 return T.isCanonical() &&
2623 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2624 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2625}
2626
Reid Spencer5f016e22007-07-11 17:01:13 +00002627/// getFunctionType - Return a normal function type with a typed argument
2628/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad4ba2a172011-01-12 09:06:06 +00002629QualType
2630ASTContext::getFunctionType(QualType ResultTy,
2631 const QualType *ArgArray, unsigned NumArgs,
2632 const FunctionProtoType::ExtProtoInfo &EPI) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002633 // Unique functions, to guarantee there is only one function of a particular
2634 // structure.
2635 llvm::FoldingSetNodeID ID;
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002636 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Reid Spencer5f016e22007-07-11 17:01:13 +00002637
2638 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002639 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00002640 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002641 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00002642
2643 // Determine whether the type being created is already canonical or not.
Richard Smitheefb3d52012-02-10 09:58:53 +00002644 bool isCanonical =
Douglas Gregor02dd7982013-01-17 23:36:45 +00002645 EPI.ExceptionSpecType == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smitheefb3d52012-02-10 09:58:53 +00002646 !EPI.HasTrailingReturn;
Reid Spencer5f016e22007-07-11 17:01:13 +00002647 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002648 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00002649 isCanonical = false;
2650
Roman Divackycfe9af22011-03-01 17:40:53 +00002651 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2652 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2653 CC_X86StdCall : DefaultCC;
John McCalle23cf432010-12-14 08:05:40 +00002654
Reid Spencer5f016e22007-07-11 17:01:13 +00002655 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00002656 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002657 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00002658 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002659 SmallVector<QualType, 16> CanonicalArgs;
Reid Spencer5f016e22007-07-11 17:01:13 +00002660 CanonicalArgs.reserve(NumArgs);
2661 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002662 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00002663
John McCalle23cf432010-12-14 08:05:40 +00002664 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smitheefb3d52012-02-10 09:58:53 +00002665 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002666 CanonicalEPI.ExceptionSpecType = EST_None;
2667 CanonicalEPI.NumExceptions = 0;
John McCalle23cf432010-12-14 08:05:40 +00002668 CanonicalEPI.ExtInfo
2669 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2670
Douglas Gregor02dd7982013-01-17 23:36:45 +00002671 // Result types do not have ARC lifetime qualifiers.
2672 QualType CanResultTy = getCanonicalType(ResultTy);
2673 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2674 Qualifiers Qs = CanResultTy.getQualifiers();
2675 Qs.removeObjCLifetime();
2676 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2677 }
2678
2679 Canonical = getFunctionType(CanResultTy,
Jay Foadbeaaccd2009-05-21 09:52:38 +00002680 CanonicalArgs.data(), NumArgs,
John McCalle23cf432010-12-14 08:05:40 +00002681 CanonicalEPI);
Sebastian Redl465226e2009-05-27 22:11:52 +00002682
Reid Spencer5f016e22007-07-11 17:01:13 +00002683 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002684 FunctionProtoType *NewIP =
2685 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002686 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002687 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002688
John McCallf85e1932011-06-15 23:02:42 +00002689 // FunctionProtoType objects are allocated with extra bytes after
2690 // them for three variable size arrays at the end:
2691 // - parameter types
2692 // - exception types
2693 // - consumed-arguments flags
2694 // Instead of the exception types, there could be a noexcept
Richard Smithb9d0b762012-07-27 04:22:15 +00002695 // expression, or information used to resolve the exception
2696 // specification.
John McCalle23cf432010-12-14 08:05:40 +00002697 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redl60618fa2011-03-12 11:50:43 +00002698 NumArgs * sizeof(QualType);
Richard Smithb9d0b762012-07-27 04:22:15 +00002699 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redl60618fa2011-03-12 11:50:43 +00002700 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithb9d0b762012-07-27 04:22:15 +00002701 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002702 Size += sizeof(Expr*);
Richard Smithe6975e92012-04-17 00:58:00 +00002703 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smith13bffc52012-04-19 00:08:28 +00002704 Size += 2 * sizeof(FunctionDecl*);
Richard Smithb9d0b762012-07-27 04:22:15 +00002705 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2706 Size += sizeof(FunctionDecl*);
Sebastian Redl60618fa2011-03-12 11:50:43 +00002707 }
John McCallf85e1932011-06-15 23:02:42 +00002708 if (EPI.ConsumedArguments)
2709 Size += NumArgs * sizeof(bool);
2710
John McCalle23cf432010-12-14 08:05:40 +00002711 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divackycfe9af22011-03-01 17:40:53 +00002712 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2713 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002714 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00002715 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00002716 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002717 return QualType(FTP, 0);
2718}
2719
John McCall3cb0ebd2010-03-10 03:28:59 +00002720#ifndef NDEBUG
2721static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2722 if (!isa<CXXRecordDecl>(D)) return false;
2723 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2724 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2725 return true;
2726 if (RD->getDescribedClassTemplate() &&
2727 !isa<ClassTemplateSpecializationDecl>(RD))
2728 return true;
2729 return false;
2730}
2731#endif
2732
2733/// getInjectedClassNameType - Return the unique reference to the
2734/// injected class name type for the specified templated declaration.
2735QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00002736 QualType TST) const {
John McCall3cb0ebd2010-03-10 03:28:59 +00002737 assert(NeedsInjectedClassNameType(Decl));
2738 if (Decl->TypeForDecl) {
2739 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregoref96ee02012-01-14 16:38:05 +00002740 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00002741 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2742 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2743 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2744 } else {
John McCallf4c73712011-01-19 06:33:43 +00002745 Type *newType =
John McCall31f17ec2010-04-27 00:57:59 +00002746 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCallf4c73712011-01-19 06:33:43 +00002747 Decl->TypeForDecl = newType;
2748 Types.push_back(newType);
John McCall3cb0ebd2010-03-10 03:28:59 +00002749 }
2750 return QualType(Decl->TypeForDecl, 0);
2751}
2752
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002753/// getTypeDeclType - Return the unique reference to the type for the
2754/// specified type declaration.
Jay Foad4ba2a172011-01-12 09:06:06 +00002755QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00002756 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00002757 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00002758
Richard Smith162e1c12011-04-15 14:24:37 +00002759 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002760 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00002761
John McCallbecb8d52010-03-10 06:48:02 +00002762 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2763 "Template type parameter types are always available.");
2764
John McCall19c85762010-02-16 03:57:14 +00002765 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002766 assert(!Record->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002767 "struct/union has previous declaration");
2768 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002769 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00002770 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002771 assert(!Enum->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002772 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002773 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00002774 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00002775 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCallf4c73712011-01-19 06:33:43 +00002776 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2777 Decl->TypeForDecl = newType;
2778 Types.push_back(newType);
Mike Stump9fdbab32009-07-31 02:02:20 +00002779 } else
John McCallbecb8d52010-03-10 06:48:02 +00002780 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002781
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002782 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002783}
2784
Reid Spencer5f016e22007-07-11 17:01:13 +00002785/// getTypedefType - Return the unique reference to the type for the
Richard Smith162e1c12011-04-15 14:24:37 +00002786/// specified typedef name decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002787QualType
Richard Smith162e1c12011-04-15 14:24:37 +00002788ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2789 QualType Canonical) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002790 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002791
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002792 if (Canonical.isNull())
2793 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCallf4c73712011-01-19 06:33:43 +00002794 TypedefType *newType = new(*this, TypeAlignment)
John McCall6b304a02009-09-24 23:30:46 +00002795 TypedefType(Type::Typedef, Decl, Canonical);
John McCallf4c73712011-01-19 06:33:43 +00002796 Decl->TypeForDecl = newType;
2797 Types.push_back(newType);
2798 return QualType(newType, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002799}
2800
Jay Foad4ba2a172011-01-12 09:06:06 +00002801QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002802 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2803
Douglas Gregoref96ee02012-01-14 16:38:05 +00002804 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002805 if (PrevDecl->TypeForDecl)
2806 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2807
John McCallf4c73712011-01-19 06:33:43 +00002808 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2809 Decl->TypeForDecl = newType;
2810 Types.push_back(newType);
2811 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002812}
2813
Jay Foad4ba2a172011-01-12 09:06:06 +00002814QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002815 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2816
Douglas Gregoref96ee02012-01-14 16:38:05 +00002817 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002818 if (PrevDecl->TypeForDecl)
2819 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2820
John McCallf4c73712011-01-19 06:33:43 +00002821 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2822 Decl->TypeForDecl = newType;
2823 Types.push_back(newType);
2824 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002825}
2826
John McCall9d156a72011-01-06 01:58:22 +00002827QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2828 QualType modifiedType,
2829 QualType equivalentType) {
2830 llvm::FoldingSetNodeID id;
2831 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2832
2833 void *insertPos = 0;
2834 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2835 if (type) return QualType(type, 0);
2836
2837 QualType canon = getCanonicalType(equivalentType);
2838 type = new (*this, TypeAlignment)
2839 AttributedType(canon, attrKind, modifiedType, equivalentType);
2840
2841 Types.push_back(type);
2842 AttributedTypes.InsertNode(type, insertPos);
2843
2844 return QualType(type, 0);
2845}
2846
2847
John McCall49a832b2009-10-18 09:09:24 +00002848/// \brief Retrieve a substitution-result type.
2849QualType
2850ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad4ba2a172011-01-12 09:06:06 +00002851 QualType Replacement) const {
John McCall467b27b2009-10-22 20:10:53 +00002852 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00002853 && "replacement types must always be canonical");
2854
2855 llvm::FoldingSetNodeID ID;
2856 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2857 void *InsertPos = 0;
2858 SubstTemplateTypeParmType *SubstParm
2859 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2860
2861 if (!SubstParm) {
2862 SubstParm = new (*this, TypeAlignment)
2863 SubstTemplateTypeParmType(Parm, Replacement);
2864 Types.push_back(SubstParm);
2865 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2866 }
2867
2868 return QualType(SubstParm, 0);
2869}
2870
Douglas Gregorc3069d62011-01-14 02:55:32 +00002871/// \brief Retrieve a
2872QualType ASTContext::getSubstTemplateTypeParmPackType(
2873 const TemplateTypeParmType *Parm,
2874 const TemplateArgument &ArgPack) {
2875#ifndef NDEBUG
2876 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2877 PEnd = ArgPack.pack_end();
2878 P != PEnd; ++P) {
2879 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2880 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2881 }
2882#endif
2883
2884 llvm::FoldingSetNodeID ID;
2885 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2886 void *InsertPos = 0;
2887 if (SubstTemplateTypeParmPackType *SubstParm
2888 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2889 return QualType(SubstParm, 0);
2890
2891 QualType Canon;
2892 if (!Parm->isCanonicalUnqualified()) {
2893 Canon = getCanonicalType(QualType(Parm, 0));
2894 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2895 ArgPack);
2896 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2897 }
2898
2899 SubstTemplateTypeParmPackType *SubstParm
2900 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2901 ArgPack);
2902 Types.push_back(SubstParm);
2903 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2904 return QualType(SubstParm, 0);
2905}
2906
Douglas Gregorfab9d672009-02-05 23:33:38 +00002907/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00002908/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002909/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00002910QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002911 bool ParameterPack,
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002912 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregorfab9d672009-02-05 23:33:38 +00002913 llvm::FoldingSetNodeID ID;
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002914 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002915 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002916 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00002917 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2918
2919 if (TypeParm)
2920 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002921
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002922 if (TTPDecl) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002923 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002924 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002925
2926 TemplateTypeParmType *TypeCheck
2927 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2928 assert(!TypeCheck && "Template type parameter canonical type broken");
2929 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002930 } else
John McCall6b304a02009-09-24 23:30:46 +00002931 TypeParm = new (*this, TypeAlignment)
2932 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002933
2934 Types.push_back(TypeParm);
2935 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2936
2937 return QualType(TypeParm, 0);
2938}
2939
John McCall3cb0ebd2010-03-10 03:28:59 +00002940TypeSourceInfo *
2941ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2942 SourceLocation NameLoc,
2943 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002944 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002945 assert(!Name.getAsDependentTemplateName() &&
2946 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00002947 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCall3cb0ebd2010-03-10 03:28:59 +00002948
2949 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2950 TemplateSpecializationTypeLoc TL
2951 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
Abramo Bagnara55d23c92012-02-06 14:41:24 +00002952 TL.setTemplateKeywordLoc(SourceLocation());
John McCall3cb0ebd2010-03-10 03:28:59 +00002953 TL.setTemplateNameLoc(NameLoc);
2954 TL.setLAngleLoc(Args.getLAngleLoc());
2955 TL.setRAngleLoc(Args.getRAngleLoc());
2956 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2957 TL.setArgLocInfo(i, Args[i].getLocInfo());
2958 return DI;
2959}
2960
Mike Stump1eb44332009-09-09 15:08:12 +00002961QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00002962ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00002963 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002964 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002965 assert(!Template.getAsDependentTemplateName() &&
2966 "No dependent template names here!");
2967
John McCalld5532b62009-11-23 01:53:49 +00002968 unsigned NumArgs = Args.size();
2969
Chris Lattner5f9e2722011-07-23 10:55:15 +00002970 SmallVector<TemplateArgument, 4> ArgVec;
John McCall833ca992009-10-29 08:12:44 +00002971 ArgVec.reserve(NumArgs);
2972 for (unsigned i = 0; i != NumArgs; ++i)
2973 ArgVec.push_back(Args[i].getArgument());
2974
John McCall31f17ec2010-04-27 00:57:59 +00002975 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002976 Underlying);
John McCall833ca992009-10-29 08:12:44 +00002977}
2978
Douglas Gregorb70126a2012-02-03 17:16:23 +00002979#ifndef NDEBUG
2980static bool hasAnyPackExpansions(const TemplateArgument *Args,
2981 unsigned NumArgs) {
2982 for (unsigned I = 0; I != NumArgs; ++I)
2983 if (Args[I].isPackExpansion())
2984 return true;
2985
2986 return true;
2987}
2988#endif
2989
John McCall833ca992009-10-29 08:12:44 +00002990QualType
2991ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00002992 const TemplateArgument *Args,
2993 unsigned NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002994 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002995 assert(!Template.getAsDependentTemplateName() &&
2996 "No dependent template names here!");
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00002997 // Look through qualified template names.
2998 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2999 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003000
Douglas Gregorb70126a2012-02-03 17:16:23 +00003001 bool IsTypeAlias =
Richard Smith3e4c6c42011-05-05 21:57:07 +00003002 Template.getAsTemplateDecl() &&
3003 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00003004 QualType CanonType;
3005 if (!Underlying.isNull())
3006 CanonType = getCanonicalType(Underlying);
3007 else {
Douglas Gregorb70126a2012-02-03 17:16:23 +00003008 // We can get here with an alias template when the specialization contains
3009 // a pack expansion that does not match up with a parameter pack.
3010 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3011 "Caller must compute aliased type");
3012 IsTypeAlias = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00003013 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3014 NumArgs);
3015 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00003016
Douglas Gregor1275ae02009-07-28 23:00:59 +00003017 // Allocate the (non-canonical) template specialization type, but don't
3018 // try to unique it: these types typically have location information that
3019 // we don't unique and don't want to lose.
Richard Smith3e4c6c42011-05-05 21:57:07 +00003020 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3021 sizeof(TemplateArgument) * NumArgs +
Douglas Gregorb70126a2012-02-03 17:16:23 +00003022 (IsTypeAlias? sizeof(QualType) : 0),
John McCall6b304a02009-09-24 23:30:46 +00003023 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00003024 TemplateSpecializationType *Spec
Douglas Gregorb70126a2012-02-03 17:16:23 +00003025 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3026 IsTypeAlias ? Underlying : QualType());
Mike Stump1eb44332009-09-09 15:08:12 +00003027
Douglas Gregor55f6b142009-02-09 18:46:07 +00003028 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00003029 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00003030}
3031
Mike Stump1eb44332009-09-09 15:08:12 +00003032QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003033ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3034 const TemplateArgument *Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00003035 unsigned NumArgs) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003036 assert(!Template.getAsDependentTemplateName() &&
3037 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00003038
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00003039 // Look through qualified template names.
3040 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3041 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003042
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003043 // Build the canonical template specialization type.
3044 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003045 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003046 CanonArgs.reserve(NumArgs);
3047 for (unsigned I = 0; I != NumArgs; ++I)
3048 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3049
3050 // Determine whether this canonical template specialization type already
3051 // exists.
3052 llvm::FoldingSetNodeID ID;
3053 TemplateSpecializationType::Profile(ID, CanonTemplate,
3054 CanonArgs.data(), NumArgs, *this);
3055
3056 void *InsertPos = 0;
3057 TemplateSpecializationType *Spec
3058 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3059
3060 if (!Spec) {
3061 // Allocate a new canonical template specialization type.
3062 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3063 sizeof(TemplateArgument) * NumArgs),
3064 TypeAlignment);
3065 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3066 CanonArgs.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003067 QualType(), QualType());
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003068 Types.push_back(Spec);
3069 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3070 }
3071
3072 assert(Spec->isDependentType() &&
3073 "Non-dependent template-id type must have a canonical type");
3074 return QualType(Spec, 0);
3075}
3076
3077QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003078ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3079 NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00003080 QualType NamedType) const {
Douglas Gregore4e5b052009-03-19 00:18:19 +00003081 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003082 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003083
3084 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003085 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003086 if (T)
3087 return QualType(T, 0);
3088
Douglas Gregor789b1f62010-02-04 18:10:26 +00003089 QualType Canon = NamedType;
3090 if (!Canon.isCanonical()) {
3091 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003092 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3093 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00003094 (void)CheckT;
3095 }
3096
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003097 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003098 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003099 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003100 return QualType(T, 0);
3101}
3102
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003103QualType
Jay Foad4ba2a172011-01-12 09:06:06 +00003104ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003105 llvm::FoldingSetNodeID ID;
3106 ParenType::Profile(ID, InnerType);
3107
3108 void *InsertPos = 0;
3109 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3110 if (T)
3111 return QualType(T, 0);
3112
3113 QualType Canon = InnerType;
3114 if (!Canon.isCanonical()) {
3115 Canon = getCanonicalType(InnerType);
3116 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3117 assert(!CheckT && "Paren canonical type broken");
3118 (void)CheckT;
3119 }
3120
3121 T = new (*this) ParenType(InnerType, Canon);
3122 Types.push_back(T);
3123 ParenTypes.InsertNode(T, InsertPos);
3124 return QualType(T, 0);
3125}
3126
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003127QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3128 NestedNameSpecifier *NNS,
3129 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00003130 QualType Canon) const {
Douglas Gregord57959a2009-03-27 23:10:48 +00003131 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
3132
3133 if (Canon.isNull()) {
3134 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003135 ElaboratedTypeKeyword CanonKeyword = Keyword;
3136 if (Keyword == ETK_None)
3137 CanonKeyword = ETK_Typename;
3138
3139 if (CanonNNS != NNS || CanonKeyword != Keyword)
3140 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00003141 }
3142
3143 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003144 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00003145
3146 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00003147 DependentNameType *T
3148 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00003149 if (T)
3150 return QualType(T, 0);
3151
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003152 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00003153 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00003154 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00003155 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00003156}
3157
Mike Stump1eb44332009-09-09 15:08:12 +00003158QualType
John McCall33500952010-06-11 00:33:02 +00003159ASTContext::getDependentTemplateSpecializationType(
3160 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003161 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00003162 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00003163 const TemplateArgumentListInfo &Args) const {
John McCall33500952010-06-11 00:33:02 +00003164 // TODO: avoid this copy
Chris Lattner5f9e2722011-07-23 10:55:15 +00003165 SmallVector<TemplateArgument, 16> ArgCopy;
John McCall33500952010-06-11 00:33:02 +00003166 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3167 ArgCopy.push_back(Args[I].getArgument());
3168 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3169 ArgCopy.size(),
3170 ArgCopy.data());
3171}
3172
3173QualType
3174ASTContext::getDependentTemplateSpecializationType(
3175 ElaboratedTypeKeyword Keyword,
3176 NestedNameSpecifier *NNS,
3177 const IdentifierInfo *Name,
3178 unsigned NumArgs,
Jay Foad4ba2a172011-01-12 09:06:06 +00003179 const TemplateArgument *Args) const {
Douglas Gregoraa2187d2011-02-28 00:04:36 +00003180 assert((!NNS || NNS->isDependent()) &&
3181 "nested-name-specifier must be dependent");
Douglas Gregor17343172009-04-01 00:28:59 +00003182
Douglas Gregor789b1f62010-02-04 18:10:26 +00003183 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00003184 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3185 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003186
3187 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00003188 DependentTemplateSpecializationType *T
3189 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003190 if (T)
3191 return QualType(T, 0);
3192
John McCall33500952010-06-11 00:33:02 +00003193 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003194
John McCall33500952010-06-11 00:33:02 +00003195 ElaboratedTypeKeyword CanonKeyword = Keyword;
3196 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3197
3198 bool AnyNonCanonArgs = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003199 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCall33500952010-06-11 00:33:02 +00003200 for (unsigned I = 0; I != NumArgs; ++I) {
3201 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3202 if (!CanonArgs[I].structurallyEquals(Args[I]))
3203 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00003204 }
3205
John McCall33500952010-06-11 00:33:02 +00003206 QualType Canon;
3207 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3208 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3209 Name, NumArgs,
3210 CanonArgs.data());
3211
3212 // Find the insert position again.
3213 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3214 }
3215
3216 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3217 sizeof(TemplateArgument) * NumArgs),
3218 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00003219 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00003220 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00003221 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00003222 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00003223 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00003224}
3225
Douglas Gregorcded4f62011-01-14 17:04:44 +00003226QualType ASTContext::getPackExpansionType(QualType Pattern,
3227 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregor7536dd52010-12-20 02:24:11 +00003228 llvm::FoldingSetNodeID ID;
Douglas Gregorcded4f62011-01-14 17:04:44 +00003229 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003230
3231 assert(Pattern->containsUnexpandedParameterPack() &&
3232 "Pack expansions must expand one or more parameter packs");
3233 void *InsertPos = 0;
3234 PackExpansionType *T
3235 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3236 if (T)
3237 return QualType(T, 0);
3238
3239 QualType Canon;
3240 if (!Pattern.isCanonical()) {
Richard Smithd8672ef2012-07-16 00:20:35 +00003241 Canon = getCanonicalType(Pattern);
3242 // The canonical type might not contain an unexpanded parameter pack, if it
3243 // contains an alias template specialization which ignores one of its
3244 // parameters.
3245 if (Canon->containsUnexpandedParameterPack()) {
3246 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003247
Richard Smithd8672ef2012-07-16 00:20:35 +00003248 // Find the insert position again, in case we inserted an element into
3249 // PackExpansionTypes and invalidated our insert position.
3250 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3251 }
Douglas Gregor7536dd52010-12-20 02:24:11 +00003252 }
3253
Douglas Gregorcded4f62011-01-14 17:04:44 +00003254 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003255 Types.push_back(T);
3256 PackExpansionTypes.InsertNode(T, InsertPos);
3257 return QualType(T, 0);
3258}
3259
Chris Lattner88cb27a2008-04-07 04:56:42 +00003260/// CmpProtocolNames - Comparison predicate for sorting protocols
3261/// alphabetically.
3262static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3263 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003264 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00003265}
3266
John McCallc12c5bb2010-05-15 11:32:37 +00003267static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00003268 unsigned NumProtocols) {
3269 if (NumProtocols == 0) return true;
3270
Douglas Gregor61cc2962012-01-02 02:00:30 +00003271 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3272 return false;
3273
John McCall54e14c42009-10-22 22:37:11 +00003274 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregor61cc2962012-01-02 02:00:30 +00003275 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3276 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCall54e14c42009-10-22 22:37:11 +00003277 return false;
3278 return true;
3279}
3280
3281static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00003282 unsigned &NumProtocols) {
3283 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00003284
Chris Lattner88cb27a2008-04-07 04:56:42 +00003285 // Sort protocols, keyed by name.
3286 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3287
Douglas Gregor61cc2962012-01-02 02:00:30 +00003288 // Canonicalize.
3289 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3290 Protocols[I] = Protocols[I]->getCanonicalDecl();
3291
Chris Lattner88cb27a2008-04-07 04:56:42 +00003292 // Remove duplicates.
3293 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3294 NumProtocols = ProtocolsEnd-Protocols;
3295}
3296
John McCallc12c5bb2010-05-15 11:32:37 +00003297QualType ASTContext::getObjCObjectType(QualType BaseType,
3298 ObjCProtocolDecl * const *Protocols,
Jay Foad4ba2a172011-01-12 09:06:06 +00003299 unsigned NumProtocols) const {
John McCallc12c5bb2010-05-15 11:32:37 +00003300 // If the base type is an interface and there aren't any protocols
3301 // to add, then the interface type will do just fine.
3302 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3303 return BaseType;
3304
3305 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003306 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00003307 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003308 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00003309 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3310 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003311
John McCallc12c5bb2010-05-15 11:32:37 +00003312 // Build the canonical type, which has the canonical base type and
3313 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00003314 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00003315 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3316 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3317 if (!ProtocolsSorted) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003318 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer02379412010-04-27 17:12:11 +00003319 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00003320 unsigned UniqueCount = NumProtocols;
3321
John McCall54e14c42009-10-22 22:37:11 +00003322 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00003323 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3324 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00003325 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00003326 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3327 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00003328 }
3329
3330 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00003331 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3332 }
3333
3334 unsigned Size = sizeof(ObjCObjectTypeImpl);
3335 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3336 void *Mem = Allocate(Size, TypeAlignment);
3337 ObjCObjectTypeImpl *T =
3338 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3339
3340 Types.push_back(T);
3341 ObjCObjectTypes.InsertNode(T, InsertPos);
3342 return QualType(T, 0);
3343}
3344
3345/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3346/// the given object type.
Jay Foad4ba2a172011-01-12 09:06:06 +00003347QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCallc12c5bb2010-05-15 11:32:37 +00003348 llvm::FoldingSetNodeID ID;
3349 ObjCObjectPointerType::Profile(ID, ObjectT);
3350
3351 void *InsertPos = 0;
3352 if (ObjCObjectPointerType *QT =
3353 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3354 return QualType(QT, 0);
3355
3356 // Find the canonical object type.
3357 QualType Canonical;
3358 if (!ObjectT.isCanonical()) {
3359 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3360
3361 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00003362 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3363 }
3364
Douglas Gregorfd6a0882010-02-08 22:59:26 +00003365 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00003366 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3367 ObjCObjectPointerType *QType =
3368 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00003369
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003370 Types.push_back(QType);
3371 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00003372 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003373}
Chris Lattner88cb27a2008-04-07 04:56:42 +00003374
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003375/// getObjCInterfaceType - Return the unique reference to the type for the
3376/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregor0af55012011-12-16 03:12:41 +00003377QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3378 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003379 if (Decl->TypeForDecl)
3380 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00003381
Douglas Gregor0af55012011-12-16 03:12:41 +00003382 if (PrevDecl) {
3383 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3384 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3385 return QualType(PrevDecl->TypeForDecl, 0);
3386 }
3387
Douglas Gregor8d2dbbf2011-12-16 16:34:57 +00003388 // Prefer the definition, if there is one.
3389 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3390 Decl = Def;
3391
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003392 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3393 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3394 Decl->TypeForDecl = T;
3395 Types.push_back(T);
3396 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00003397}
3398
Douglas Gregor72564e72009-02-26 23:50:07 +00003399/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3400/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00003401/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00003402/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00003403/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00003404QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003405 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00003406 if (tofExpr->isTypeDependent()) {
3407 llvm::FoldingSetNodeID ID;
3408 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00003409
Douglas Gregorb1975722009-07-30 23:18:24 +00003410 void *InsertPos = 0;
3411 DependentTypeOfExprType *Canon
3412 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3413 if (Canon) {
3414 // We already have a "canonical" version of an identical, dependent
3415 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00003416 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00003417 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00003418 } else {
Douglas Gregorb1975722009-07-30 23:18:24 +00003419 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00003420 Canon
3421 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00003422 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3423 toe = Canon;
3424 }
3425 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003426 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00003427 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00003428 }
Steve Naroff9752f252007-08-01 18:02:17 +00003429 Types.push_back(toe);
3430 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00003431}
3432
Steve Naroff9752f252007-08-01 18:02:17 +00003433/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3434/// TypeOfType AST's. The only motivation to unique these nodes would be
3435/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00003436/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00003437/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00003438QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00003439 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00003440 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00003441 Types.push_back(tot);
3442 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00003443}
3444
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00003445
Anders Carlsson395b4752009-06-24 19:06:50 +00003446/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3447/// DecltypeType AST's. The only motivation to unique these nodes would be
3448/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00003449/// an issue. This doesn't effect the type checker, since it operates
David Blaikie39e02032011-11-06 22:28:03 +00003450/// on canonical types (which are always unique).
Douglas Gregorf8af9822012-02-12 18:42:33 +00003451QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003452 DecltypeType *dt;
Douglas Gregor561f8122011-07-01 01:22:09 +00003453
3454 // C++0x [temp.type]p2:
3455 // If an expression e involves a template parameter, decltype(e) denotes a
3456 // unique dependent type. Two such decltype-specifiers refer to the same
3457 // type only if their expressions are equivalent (14.5.6.1).
3458 if (e->isInstantiationDependent()) {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003459 llvm::FoldingSetNodeID ID;
3460 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00003461
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003462 void *InsertPos = 0;
3463 DependentDecltypeType *Canon
3464 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3465 if (Canon) {
3466 // We already have a "canonical" version of an equivalent, dependent
3467 // decltype type. Use that as our canonical type.
Richard Smith0d729102012-08-13 20:08:14 +00003468 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003469 QualType((DecltypeType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00003470 } else {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003471 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00003472 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003473 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3474 dt = Canon;
3475 }
3476 } else {
Douglas Gregorf8af9822012-02-12 18:42:33 +00003477 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3478 getCanonicalType(UnderlyingType));
Douglas Gregordd0257c2009-07-08 00:03:05 +00003479 }
Anders Carlsson395b4752009-06-24 19:06:50 +00003480 Types.push_back(dt);
3481 return QualType(dt, 0);
3482}
3483
Sean Huntca63c202011-05-24 22:41:36 +00003484/// getUnaryTransformationType - We don't unique these, since the memory
3485/// savings are minimal and these are rare.
3486QualType ASTContext::getUnaryTransformType(QualType BaseType,
3487 QualType UnderlyingType,
3488 UnaryTransformType::UTTKind Kind)
3489 const {
3490 UnaryTransformType *Ty =
Douglas Gregor69d97752011-05-25 17:51:54 +00003491 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3492 Kind,
3493 UnderlyingType->isDependentType() ?
Peter Collingbourne12fc4b02012-03-05 16:02:06 +00003494 QualType() : getCanonicalType(UnderlyingType));
Sean Huntca63c202011-05-24 22:41:36 +00003495 Types.push_back(Ty);
3496 return QualType(Ty, 0);
3497}
3498
Richard Smith483b9f32011-02-21 20:05:19 +00003499/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith34b41d92011-02-20 03:19:35 +00003500QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smith483b9f32011-02-21 20:05:19 +00003501 void *InsertPos = 0;
3502 if (!DeducedType.isNull()) {
3503 // Look in the folding set for an existing type.
3504 llvm::FoldingSetNodeID ID;
3505 AutoType::Profile(ID, DeducedType);
3506 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3507 return QualType(AT, 0);
3508 }
3509
3510 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
3511 Types.push_back(AT);
3512 if (InsertPos)
3513 AutoTypes.InsertNode(AT, InsertPos);
3514 return QualType(AT, 0);
Richard Smith34b41d92011-02-20 03:19:35 +00003515}
3516
Eli Friedmanb001de72011-10-06 23:00:33 +00003517/// getAtomicType - Return the uniqued reference to the atomic type for
3518/// the given value type.
3519QualType ASTContext::getAtomicType(QualType T) const {
3520 // Unique pointers, to guarantee there is only one pointer of a particular
3521 // structure.
3522 llvm::FoldingSetNodeID ID;
3523 AtomicType::Profile(ID, T);
3524
3525 void *InsertPos = 0;
3526 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3527 return QualType(AT, 0);
3528
3529 // If the atomic value type isn't canonical, this won't be a canonical type
3530 // either, so fill in the canonical type field.
3531 QualType Canonical;
3532 if (!T.isCanonical()) {
3533 Canonical = getAtomicType(getCanonicalType(T));
3534
3535 // Get the new insert position for the node we care about.
3536 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3537 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3538 }
3539 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3540 Types.push_back(New);
3541 AtomicTypes.InsertNode(New, InsertPos);
3542 return QualType(New, 0);
3543}
3544
Richard Smithad762fc2011-04-14 22:09:26 +00003545/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3546QualType ASTContext::getAutoDeductType() const {
3547 if (AutoDeductTy.isNull())
3548 AutoDeductTy = getAutoType(QualType());
3549 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
3550 return AutoDeductTy;
3551}
3552
3553/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3554QualType ASTContext::getAutoRRefDeductType() const {
3555 if (AutoRRefDeductTy.isNull())
3556 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3557 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3558 return AutoRRefDeductTy;
3559}
3560
Reid Spencer5f016e22007-07-11 17:01:13 +00003561/// getTagDeclType - Return the unique reference to the type for the
3562/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad4ba2a172011-01-12 09:06:06 +00003563QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenekd778f882007-11-26 21:16:01 +00003564 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00003565 // FIXME: What is the design on getTagDeclType when it requires casting
3566 // away const? mutable?
3567 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003568}
3569
Mike Stump1eb44332009-09-09 15:08:12 +00003570/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3571/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3572/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00003573CanQualType ASTContext::getSizeType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003574 return getFromTargetType(Target->getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00003575}
3576
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003577/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3578CanQualType ASTContext::getIntMaxType() const {
3579 return getFromTargetType(Target->getIntMaxType());
3580}
3581
3582/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3583CanQualType ASTContext::getUIntMaxType() const {
3584 return getFromTargetType(Target->getUIntMaxType());
3585}
3586
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00003587/// getSignedWCharType - Return the type of "signed wchar_t".
3588/// Used when in C++, as a GCC extension.
3589QualType ASTContext::getSignedWCharType() const {
3590 // FIXME: derive from "Target" ?
3591 return WCharTy;
3592}
3593
3594/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3595/// Used when in C++, as a GCC extension.
3596QualType ASTContext::getUnsignedWCharType() const {
3597 // FIXME: derive from "Target" ?
3598 return UnsignedIntTy;
3599}
3600
Enea Zaffanella9677eb82013-01-26 17:08:37 +00003601QualType ASTContext::getIntPtrType() const {
3602 return getFromTargetType(Target->getIntPtrType());
3603}
3604
3605QualType ASTContext::getUIntPtrType() const {
3606 return getCorrespondingUnsignedType(getIntPtrType());
3607}
3608
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003609/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattner8b9023b2007-07-13 03:05:23 +00003610/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3611QualType ASTContext::getPointerDiffType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003612 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00003613}
3614
Eli Friedman6902e412012-11-27 02:58:24 +00003615/// \brief Return the unique type for "pid_t" defined in
3616/// <sys/types.h>. We need this to compute the correct type for vfork().
3617QualType ASTContext::getProcessIDType() const {
3618 return getFromTargetType(Target->getProcessIDType());
3619}
3620
Chris Lattnere6327742008-04-02 05:18:44 +00003621//===----------------------------------------------------------------------===//
3622// Type Operators
3623//===----------------------------------------------------------------------===//
3624
Jay Foad4ba2a172011-01-12 09:06:06 +00003625CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCall54e14c42009-10-22 22:37:11 +00003626 // Push qualifiers into arrays, and then discard any remaining
3627 // qualifiers.
3628 T = getCanonicalType(T);
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003629 T = getVariableArrayDecayedType(T);
John McCall54e14c42009-10-22 22:37:11 +00003630 const Type *Ty = T.getTypePtr();
John McCall54e14c42009-10-22 22:37:11 +00003631 QualType Result;
3632 if (isa<ArrayType>(Ty)) {
3633 Result = getArrayDecayedType(QualType(Ty,0));
3634 } else if (isa<FunctionType>(Ty)) {
3635 Result = getPointerType(QualType(Ty, 0));
3636 } else {
3637 Result = QualType(Ty, 0);
3638 }
3639
3640 return CanQualType::CreateUnsafe(Result);
3641}
3642
John McCall62c28c82011-01-18 07:41:22 +00003643QualType ASTContext::getUnqualifiedArrayType(QualType type,
3644 Qualifiers &quals) {
3645 SplitQualType splitType = type.getSplitUnqualifiedType();
3646
3647 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3648 // the unqualified desugared type and then drops it on the floor.
3649 // We then have to strip that sugar back off with
3650 // getUnqualifiedDesugaredType(), which is silly.
3651 const ArrayType *AT =
John McCall200fa532012-02-08 00:46:36 +00003652 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall62c28c82011-01-18 07:41:22 +00003653
3654 // If we don't have an array, just use the results in splitType.
Douglas Gregor9dadd942010-05-17 18:45:21 +00003655 if (!AT) {
John McCall200fa532012-02-08 00:46:36 +00003656 quals = splitType.Quals;
3657 return QualType(splitType.Ty, 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003658 }
3659
John McCall62c28c82011-01-18 07:41:22 +00003660 // Otherwise, recurse on the array's element type.
3661 QualType elementType = AT->getElementType();
3662 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3663
3664 // If that didn't change the element type, AT has no qualifiers, so we
3665 // can just use the results in splitType.
3666 if (elementType == unqualElementType) {
3667 assert(quals.empty()); // from the recursive call
John McCall200fa532012-02-08 00:46:36 +00003668 quals = splitType.Quals;
3669 return QualType(splitType.Ty, 0);
John McCall62c28c82011-01-18 07:41:22 +00003670 }
3671
3672 // Otherwise, add in the qualifiers from the outermost type, then
3673 // build the type back up.
John McCall200fa532012-02-08 00:46:36 +00003674 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003675
Douglas Gregor9dadd942010-05-17 18:45:21 +00003676 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003677 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003678 CAT->getSizeModifier(), 0);
3679 }
3680
Douglas Gregor9dadd942010-05-17 18:45:21 +00003681 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003682 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003683 }
3684
Douglas Gregor9dadd942010-05-17 18:45:21 +00003685 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003686 return getVariableArrayType(unqualElementType,
John McCall3fa5cae2010-10-26 07:05:15 +00003687 VAT->getSizeExpr(),
Douglas Gregor9dadd942010-05-17 18:45:21 +00003688 VAT->getSizeModifier(),
3689 VAT->getIndexTypeCVRQualifiers(),
3690 VAT->getBracketsRange());
3691 }
3692
3693 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall62c28c82011-01-18 07:41:22 +00003694 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003695 DSAT->getSizeModifier(), 0,
3696 SourceRange());
3697}
3698
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003699/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3700/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3701/// they point to and return true. If T1 and T2 aren't pointer types
3702/// or pointer-to-member types, or if they are not similar at this
3703/// level, returns false and leaves T1 and T2 unchanged. Top-level
3704/// qualifiers on T1 and T2 are ignored. This function will typically
3705/// be called in a loop that successively "unwraps" pointer and
3706/// pointer-to-member types to compare them at each level.
3707bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3708 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3709 *T2PtrType = T2->getAs<PointerType>();
3710 if (T1PtrType && T2PtrType) {
3711 T1 = T1PtrType->getPointeeType();
3712 T2 = T2PtrType->getPointeeType();
3713 return true;
3714 }
3715
3716 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3717 *T2MPType = T2->getAs<MemberPointerType>();
3718 if (T1MPType && T2MPType &&
3719 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3720 QualType(T2MPType->getClass(), 0))) {
3721 T1 = T1MPType->getPointeeType();
3722 T2 = T2MPType->getPointeeType();
3723 return true;
3724 }
3725
David Blaikie4e4d0842012-03-11 07:00:24 +00003726 if (getLangOpts().ObjC1) {
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003727 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3728 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3729 if (T1OPType && T2OPType) {
3730 T1 = T1OPType->getPointeeType();
3731 T2 = T2OPType->getPointeeType();
3732 return true;
3733 }
3734 }
3735
3736 // FIXME: Block pointers, too?
3737
3738 return false;
3739}
3740
Jay Foad4ba2a172011-01-12 09:06:06 +00003741DeclarationNameInfo
3742ASTContext::getNameForTemplate(TemplateName Name,
3743 SourceLocation NameLoc) const {
John McCall14606042011-06-30 08:33:18 +00003744 switch (Name.getKind()) {
3745 case TemplateName::QualifiedTemplate:
3746 case TemplateName::Template:
Abramo Bagnara25777432010-08-11 22:01:17 +00003747 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCall14606042011-06-30 08:33:18 +00003748 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3749 NameLoc);
Abramo Bagnara25777432010-08-11 22:01:17 +00003750
John McCall14606042011-06-30 08:33:18 +00003751 case TemplateName::OverloadedTemplate: {
3752 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3753 // DNInfo work in progress: CHECKME: what about DNLoc?
3754 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3755 }
3756
3757 case TemplateName::DependentTemplate: {
3758 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnara25777432010-08-11 22:01:17 +00003759 DeclarationName DName;
John McCall80ad16f2009-11-24 18:42:40 +00003760 if (DTN->isIdentifier()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00003761 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3762 return DeclarationNameInfo(DName, NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003763 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00003764 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3765 // DNInfo work in progress: FIXME: source locations?
3766 DeclarationNameLoc DNLoc;
3767 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3768 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3769 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003770 }
3771 }
3772
John McCall14606042011-06-30 08:33:18 +00003773 case TemplateName::SubstTemplateTemplateParm: {
3774 SubstTemplateTemplateParmStorage *subst
3775 = Name.getAsSubstTemplateTemplateParm();
3776 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3777 NameLoc);
3778 }
3779
3780 case TemplateName::SubstTemplateTemplateParmPack: {
3781 SubstTemplateTemplateParmPackStorage *subst
3782 = Name.getAsSubstTemplateTemplateParmPack();
3783 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3784 NameLoc);
3785 }
3786 }
3787
3788 llvm_unreachable("bad template name kind!");
John McCall80ad16f2009-11-24 18:42:40 +00003789}
3790
Jay Foad4ba2a172011-01-12 09:06:06 +00003791TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCall14606042011-06-30 08:33:18 +00003792 switch (Name.getKind()) {
3793 case TemplateName::QualifiedTemplate:
3794 case TemplateName::Template: {
3795 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003796 if (TemplateTemplateParmDecl *TTP
John McCall14606042011-06-30 08:33:18 +00003797 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003798 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3799
3800 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00003801 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003802 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003803
John McCall14606042011-06-30 08:33:18 +00003804 case TemplateName::OverloadedTemplate:
3805 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump1eb44332009-09-09 15:08:12 +00003806
John McCall14606042011-06-30 08:33:18 +00003807 case TemplateName::DependentTemplate: {
3808 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3809 assert(DTN && "Non-dependent template names must refer to template decls.");
3810 return DTN->CanonicalTemplateName;
3811 }
3812
3813 case TemplateName::SubstTemplateTemplateParm: {
3814 SubstTemplateTemplateParmStorage *subst
3815 = Name.getAsSubstTemplateTemplateParm();
3816 return getCanonicalTemplateName(subst->getReplacement());
3817 }
3818
3819 case TemplateName::SubstTemplateTemplateParmPack: {
3820 SubstTemplateTemplateParmPackStorage *subst
3821 = Name.getAsSubstTemplateTemplateParmPack();
3822 TemplateTemplateParmDecl *canonParameter
3823 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3824 TemplateArgument canonArgPack
3825 = getCanonicalTemplateArgument(subst->getArgumentPack());
3826 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3827 }
3828 }
3829
3830 llvm_unreachable("bad template name!");
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003831}
3832
Douglas Gregordb0d4b72009-11-11 23:06:43 +00003833bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3834 X = getCanonicalTemplateName(X);
3835 Y = getCanonicalTemplateName(Y);
3836 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3837}
3838
Mike Stump1eb44332009-09-09 15:08:12 +00003839TemplateArgument
Jay Foad4ba2a172011-01-12 09:06:06 +00003840ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregor1275ae02009-07-28 23:00:59 +00003841 switch (Arg.getKind()) {
3842 case TemplateArgument::Null:
3843 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003844
Douglas Gregor1275ae02009-07-28 23:00:59 +00003845 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00003846 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003847
Douglas Gregord2008e22012-04-06 22:40:38 +00003848 case TemplateArgument::Declaration: {
Eli Friedmand7a6b162012-09-26 02:36:12 +00003849 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
3850 return TemplateArgument(D, Arg.isDeclForReferenceParam());
Douglas Gregord2008e22012-04-06 22:40:38 +00003851 }
Mike Stump1eb44332009-09-09 15:08:12 +00003852
Eli Friedmand7a6b162012-09-26 02:36:12 +00003853 case TemplateArgument::NullPtr:
3854 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
3855 /*isNullPtr*/true);
3856
Douglas Gregor788cd062009-11-11 01:00:40 +00003857 case TemplateArgument::Template:
3858 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregora7fc9012011-01-05 18:58:31 +00003859
3860 case TemplateArgument::TemplateExpansion:
3861 return TemplateArgument(getCanonicalTemplateName(
3862 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregor2be29f42011-01-14 23:41:42 +00003863 Arg.getNumTemplateExpansions());
Douglas Gregora7fc9012011-01-05 18:58:31 +00003864
Douglas Gregor1275ae02009-07-28 23:00:59 +00003865 case TemplateArgument::Integral:
Benjamin Kramer85524372012-06-07 15:09:51 +00003866 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003867
Douglas Gregor1275ae02009-07-28 23:00:59 +00003868 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00003869 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003870
Douglas Gregor1275ae02009-07-28 23:00:59 +00003871 case TemplateArgument::Pack: {
Douglas Gregor87dd6972010-12-20 16:52:59 +00003872 if (Arg.pack_size() == 0)
3873 return Arg;
3874
Douglas Gregor910f8002010-11-07 23:05:16 +00003875 TemplateArgument *CanonArgs
3876 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregor1275ae02009-07-28 23:00:59 +00003877 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003878 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00003879 AEnd = Arg.pack_end();
3880 A != AEnd; (void)++A, ++Idx)
3881 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00003882
Douglas Gregor910f8002010-11-07 23:05:16 +00003883 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregor1275ae02009-07-28 23:00:59 +00003884 }
3885 }
3886
3887 // Silence GCC warning
David Blaikieb219cfc2011-09-23 05:06:16 +00003888 llvm_unreachable("Unhandled template argument kind");
Douglas Gregor1275ae02009-07-28 23:00:59 +00003889}
3890
Douglas Gregord57959a2009-03-27 23:10:48 +00003891NestedNameSpecifier *
Jay Foad4ba2a172011-01-12 09:06:06 +00003892ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump1eb44332009-09-09 15:08:12 +00003893 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00003894 return 0;
3895
3896 switch (NNS->getKind()) {
3897 case NestedNameSpecifier::Identifier:
3898 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00003899 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00003900 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3901 NNS->getAsIdentifier());
3902
3903 case NestedNameSpecifier::Namespace:
3904 // A namespace is canonical; build a nested-name-specifier with
3905 // this namespace and no prefix.
Douglas Gregor14aba762011-02-24 02:36:08 +00003906 return NestedNameSpecifier::Create(*this, 0,
3907 NNS->getAsNamespace()->getOriginalNamespace());
3908
3909 case NestedNameSpecifier::NamespaceAlias:
3910 // A namespace is canonical; build a nested-name-specifier with
3911 // this namespace and no prefix.
3912 return NestedNameSpecifier::Create(*this, 0,
3913 NNS->getAsNamespaceAlias()->getNamespace()
3914 ->getOriginalNamespace());
Douglas Gregord57959a2009-03-27 23:10:48 +00003915
3916 case NestedNameSpecifier::TypeSpec:
3917 case NestedNameSpecifier::TypeSpecWithTemplate: {
3918 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor264bf662010-11-04 00:09:33 +00003919
3920 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3921 // break it apart into its prefix and identifier, then reconsititute those
3922 // as the canonical nested-name-specifier. This is required to canonicalize
3923 // a dependent nested-name-specifier involving typedefs of dependent-name
3924 // types, e.g.,
3925 // typedef typename T::type T1;
3926 // typedef typename T1::type T2;
Eli Friedman16412ef2012-03-03 04:09:56 +00003927 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
3928 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor264bf662010-11-04 00:09:33 +00003929 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor264bf662010-11-04 00:09:33 +00003930
Eli Friedman16412ef2012-03-03 04:09:56 +00003931 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
3932 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
3933 // first place?
John McCall3b657512011-01-19 10:06:00 +00003934 return NestedNameSpecifier::Create(*this, 0, false,
3935 const_cast<Type*>(T.getTypePtr()));
Douglas Gregord57959a2009-03-27 23:10:48 +00003936 }
3937
3938 case NestedNameSpecifier::Global:
3939 // The global specifier is canonical and unique.
3940 return NNS;
3941 }
3942
David Blaikie7530c032012-01-17 06:56:22 +00003943 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregord57959a2009-03-27 23:10:48 +00003944}
3945
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003946
Jay Foad4ba2a172011-01-12 09:06:06 +00003947const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003948 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00003949 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003950 // Handle the common positive case fast.
3951 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3952 return AT;
3953 }
Mike Stump1eb44332009-09-09 15:08:12 +00003954
John McCall0953e762009-09-24 19:53:00 +00003955 // Handle the common negative case fast.
John McCall3b657512011-01-19 10:06:00 +00003956 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003957 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003958
John McCall0953e762009-09-24 19:53:00 +00003959 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003960 // implements C99 6.7.3p8: "If the specification of an array type includes
3961 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00003962
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003963 // If we get here, we either have type qualifiers on the type, or we have
3964 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00003965 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00003966
John McCall3b657512011-01-19 10:06:00 +00003967 SplitQualType split = T.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00003968 Qualifiers qs = split.Quals;
Mike Stump1eb44332009-09-09 15:08:12 +00003969
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003970 // If we have a simple case, just return now.
John McCall200fa532012-02-08 00:46:36 +00003971 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall3b657512011-01-19 10:06:00 +00003972 if (ATy == 0 || qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003973 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00003974
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003975 // Otherwise, we have an array and we have qualifiers on it. Push the
3976 // qualifiers into the array element type and return a new array type.
John McCall3b657512011-01-19 10:06:00 +00003977 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump1eb44332009-09-09 15:08:12 +00003978
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003979 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3980 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3981 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003982 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003983 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3984 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3985 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003986 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00003987
Mike Stump1eb44332009-09-09 15:08:12 +00003988 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00003989 = dyn_cast<DependentSizedArrayType>(ATy))
3990 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00003991 getDependentSizedArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003992 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00003993 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003994 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003995 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00003996
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003997 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003998 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003999 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004000 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004001 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004002 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00004003}
4004
Abramo Bagnaraad9689f2012-05-17 12:44:05 +00004005QualType ASTContext::getAdjustedParameterType(QualType T) const {
Douglas Gregor79e6bd32011-07-12 04:42:08 +00004006 // C99 6.7.5.3p7:
4007 // A declaration of a parameter as "array of type" shall be
4008 // adjusted to "qualified pointer to type", where the type
4009 // qualifiers (if any) are those specified within the [ and ] of
4010 // the array type derivation.
4011 if (T->isArrayType())
4012 return getArrayDecayedType(T);
4013
4014 // C99 6.7.5.3p8:
4015 // A declaration of a parameter as "function returning type"
4016 // shall be adjusted to "pointer to function returning type", as
4017 // in 6.3.2.1.
4018 if (T->isFunctionType())
4019 return getPointerType(T);
4020
4021 return T;
4022}
4023
Abramo Bagnaraad9689f2012-05-17 12:44:05 +00004024QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor79e6bd32011-07-12 04:42:08 +00004025 T = getVariableArrayDecayedType(T);
4026 T = getAdjustedParameterType(T);
4027 return T.getUnqualifiedType();
4028}
4029
Chris Lattnere6327742008-04-02 05:18:44 +00004030/// getArrayDecayedType - Return the properly qualified result of decaying the
4031/// specified array type to a pointer. This operation is non-trivial when
4032/// handling typedefs etc. The canonical type of "T" must be an array type,
4033/// this returns a pointer to a properly qualified element of the array.
4034///
4035/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad4ba2a172011-01-12 09:06:06 +00004036QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004037 // Get the element type with 'getAsArrayType' so that we don't lose any
4038 // typedefs in the element type of the array. This also handles propagation
4039 // of type qualifiers from the array type into the element type if present
4040 // (C99 6.7.3p8).
4041 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4042 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00004043
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004044 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00004045
4046 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00004047 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00004048}
4049
John McCall3b657512011-01-19 10:06:00 +00004050QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4051 return getBaseElementType(array->getElementType());
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00004052}
4053
John McCall3b657512011-01-19 10:06:00 +00004054QualType ASTContext::getBaseElementType(QualType type) const {
4055 Qualifiers qs;
4056 while (true) {
4057 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00004058 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall3b657512011-01-19 10:06:00 +00004059 if (!array) break;
Mike Stump1eb44332009-09-09 15:08:12 +00004060
John McCall3b657512011-01-19 10:06:00 +00004061 type = array->getElementType();
John McCall200fa532012-02-08 00:46:36 +00004062 qs.addConsistentQualifiers(split.Quals);
John McCall3b657512011-01-19 10:06:00 +00004063 }
Mike Stump1eb44332009-09-09 15:08:12 +00004064
John McCall3b657512011-01-19 10:06:00 +00004065 return getQualifiedType(type, qs);
Anders Carlsson6183a992008-12-21 03:44:36 +00004066}
4067
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004068/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00004069uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004070ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4071 uint64_t ElementCount = 1;
4072 do {
4073 ElementCount *= CA->getSize().getZExtValue();
Richard Smithd5e83942012-12-06 03:04:50 +00004074 CA = dyn_cast_or_null<ConstantArrayType>(
4075 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004076 } while (CA);
4077 return ElementCount;
4078}
4079
Reid Spencer5f016e22007-07-11 17:01:13 +00004080/// getFloatingRank - Return a relative rank for floating point types.
4081/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00004082static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00004083 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00004084 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00004085
John McCall183700f2009-09-21 23:43:11 +00004086 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4087 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004088 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00004089 case BuiltinType::Half: return HalfRank;
Reid Spencer5f016e22007-07-11 17:01:13 +00004090 case BuiltinType::Float: return FloatRank;
4091 case BuiltinType::Double: return DoubleRank;
4092 case BuiltinType::LongDouble: return LongDoubleRank;
4093 }
4094}
4095
Mike Stump1eb44332009-09-09 15:08:12 +00004096/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4097/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00004098/// 'typeDomain' is a real floating point or complex type.
4099/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00004100QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4101 QualType Domain) const {
4102 FloatingRank EltRank = getFloatingRank(Size);
4103 if (Domain->isComplexType()) {
4104 switch (EltRank) {
David Blaikie561d3ab2012-01-17 02:30:50 +00004105 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Narofff1448a02007-08-27 01:27:54 +00004106 case FloatRank: return FloatComplexTy;
4107 case DoubleRank: return DoubleComplexTy;
4108 case LongDoubleRank: return LongDoubleComplexTy;
4109 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004110 }
Chris Lattner1361b112008-04-06 23:58:54 +00004111
4112 assert(Domain->isRealFloatingType() && "Unknown domain!");
4113 switch (EltRank) {
Joey Gouly19dbb202013-01-23 11:56:20 +00004114 case HalfRank: return HalfTy;
Chris Lattner1361b112008-04-06 23:58:54 +00004115 case FloatRank: return FloatTy;
4116 case DoubleRank: return DoubleTy;
4117 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00004118 }
David Blaikie561d3ab2012-01-17 02:30:50 +00004119 llvm_unreachable("getFloatingRank(): illegal value for rank");
Reid Spencer5f016e22007-07-11 17:01:13 +00004120}
4121
Chris Lattner7cfeb082008-04-06 23:55:33 +00004122/// getFloatingTypeOrder - Compare the rank of the two specified floating
4123/// point types, ignoring the domain of the type (i.e. 'double' ==
4124/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00004125/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00004126int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnera75cea32008-04-06 23:38:49 +00004127 FloatingRank LHSR = getFloatingRank(LHS);
4128 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004129
Chris Lattnera75cea32008-04-06 23:38:49 +00004130 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00004131 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00004132 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00004133 return 1;
4134 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00004135}
4136
Chris Lattnerf52ab252008-04-06 22:59:24 +00004137/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4138/// routine will assert if passed a built-in type that isn't an integer or enum,
4139/// or if it is not canonicalized.
John McCallf4c73712011-01-19 06:33:43 +00004140unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCall467b27b2009-10-22 20:10:53 +00004141 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00004142
Chris Lattnerf52ab252008-04-06 22:59:24 +00004143 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004144 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattner7cfeb082008-04-06 23:55:33 +00004145 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004146 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004147 case BuiltinType::Char_S:
4148 case BuiltinType::Char_U:
4149 case BuiltinType::SChar:
4150 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004151 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004152 case BuiltinType::Short:
4153 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004154 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004155 case BuiltinType::Int:
4156 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004157 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004158 case BuiltinType::Long:
4159 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004160 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004161 case BuiltinType::LongLong:
4162 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004163 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00004164 case BuiltinType::Int128:
4165 case BuiltinType::UInt128:
4166 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00004167 }
4168}
4169
Eli Friedman04e83572009-08-20 04:21:42 +00004170/// \brief Whether this is a promotable bitfield reference according
4171/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4172///
4173/// \returns the type this bit-field will promote to, or NULL if no
4174/// promotion occurs.
Jay Foad4ba2a172011-01-12 09:06:06 +00004175QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregorceafbde2010-05-24 20:13:53 +00004176 if (E->isTypeDependent() || E->isValueDependent())
4177 return QualType();
4178
Eli Friedman04e83572009-08-20 04:21:42 +00004179 FieldDecl *Field = E->getBitField();
4180 if (!Field)
4181 return QualType();
4182
4183 QualType FT = Field->getType();
4184
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004185 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman04e83572009-08-20 04:21:42 +00004186 uint64_t IntSize = getTypeSize(IntTy);
4187 // GCC extension compatibility: if the bit-field size is less than or equal
4188 // to the size of int, it gets promoted no matter what its type is.
4189 // For instance, unsigned long bf : 4 gets promoted to signed int.
4190 if (BitWidth < IntSize)
4191 return IntTy;
4192
4193 if (BitWidth == IntSize)
4194 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4195
4196 // Types bigger than int are not subject to promotions, and therefore act
4197 // like the base type.
4198 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4199 // is ridiculous.
4200 return QualType();
4201}
4202
Eli Friedmana95d7572009-08-19 07:44:53 +00004203/// getPromotedIntegerType - Returns the type that Promotable will
4204/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4205/// integer type.
Jay Foad4ba2a172011-01-12 09:06:06 +00004206QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedmana95d7572009-08-19 07:44:53 +00004207 assert(!Promotable.isNull());
4208 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00004209 if (const EnumType *ET = Promotable->getAs<EnumType>())
4210 return ET->getDecl()->getPromotionType();
Eli Friedman68a2dc42011-10-26 07:22:48 +00004211
4212 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4213 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4214 // (3.9.1) can be converted to a prvalue of the first of the following
4215 // types that can represent all the values of its underlying type:
4216 // int, unsigned int, long int, unsigned long int, long long int, or
4217 // unsigned long long int [...]
4218 // FIXME: Is there some better way to compute this?
4219 if (BT->getKind() == BuiltinType::WChar_S ||
4220 BT->getKind() == BuiltinType::WChar_U ||
4221 BT->getKind() == BuiltinType::Char16 ||
4222 BT->getKind() == BuiltinType::Char32) {
4223 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4224 uint64_t FromSize = getTypeSize(BT);
4225 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4226 LongLongTy, UnsignedLongLongTy };
4227 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4228 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4229 if (FromSize < ToSize ||
4230 (FromSize == ToSize &&
4231 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4232 return PromoteTypes[Idx];
4233 }
4234 llvm_unreachable("char type should fit into long long");
4235 }
4236 }
4237
4238 // At this point, we should have a signed or unsigned integer type.
Eli Friedmana95d7572009-08-19 07:44:53 +00004239 if (Promotable->isSignedIntegerType())
4240 return IntTy;
Eli Friedman5b64e772012-11-15 01:21:59 +00004241 uint64_t PromotableSize = getIntWidth(Promotable);
4242 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedmana95d7572009-08-19 07:44:53 +00004243 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4244 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4245}
4246
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00004247/// \brief Recurses in pointer/array types until it finds an objc retainable
4248/// type and returns its ownership.
4249Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4250 while (!T.isNull()) {
4251 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4252 return T.getObjCLifetime();
4253 if (T->isArrayType())
4254 T = getBaseElementType(T);
4255 else if (const PointerType *PT = T->getAs<PointerType>())
4256 T = PT->getPointeeType();
4257 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis28445f02011-07-01 23:01:46 +00004258 T = RT->getPointeeType();
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00004259 else
4260 break;
4261 }
4262
4263 return Qualifiers::OCL_None;
4264}
4265
Mike Stump1eb44332009-09-09 15:08:12 +00004266/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00004267/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00004268/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00004269int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCallf4c73712011-01-19 06:33:43 +00004270 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4271 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00004272 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004273
Chris Lattnerf52ab252008-04-06 22:59:24 +00004274 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4275 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00004276
Chris Lattner7cfeb082008-04-06 23:55:33 +00004277 unsigned LHSRank = getIntegerRank(LHSC);
4278 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00004279
Chris Lattner7cfeb082008-04-06 23:55:33 +00004280 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4281 if (LHSRank == RHSRank) return 0;
4282 return LHSRank > RHSRank ? 1 : -1;
4283 }
Mike Stump1eb44332009-09-09 15:08:12 +00004284
Chris Lattner7cfeb082008-04-06 23:55:33 +00004285 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4286 if (LHSUnsigned) {
4287 // If the unsigned [LHS] type is larger, return it.
4288 if (LHSRank >= RHSRank)
4289 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004290
Chris Lattner7cfeb082008-04-06 23:55:33 +00004291 // If the signed type can represent all values of the unsigned type, it
4292 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00004293 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00004294 return -1;
4295 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00004296
Chris Lattner7cfeb082008-04-06 23:55:33 +00004297 // If the unsigned [RHS] type is larger, return it.
4298 if (RHSRank >= LHSRank)
4299 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00004300
Chris Lattner7cfeb082008-04-06 23:55:33 +00004301 // If the signed type can represent all values of the unsigned type, it
4302 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00004303 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00004304 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00004305}
Anders Carlsson71993dd2007-08-17 05:31:46 +00004306
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004307static RecordDecl *
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004308CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
4309 DeclContext *DC, IdentifierInfo *Id) {
4310 SourceLocation Loc;
David Blaikie4e4d0842012-03-11 07:00:24 +00004311 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004312 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004313 else
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004314 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004315}
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004316
Mike Stump1eb44332009-09-09 15:08:12 +00004317// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00004318QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson71993dd2007-08-17 05:31:46 +00004319 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00004320 CFConstantStringTypeDecl =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004321 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004322 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00004323 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004324
Anders Carlssonf06273f2007-11-19 00:25:30 +00004325 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00004326
Anders Carlsson71993dd2007-08-17 05:31:46 +00004327 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00004328 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00004329 // int flags;
4330 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00004331 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00004332 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00004333 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00004334 FieldTypes[3] = LongTy;
4335
Anders Carlsson71993dd2007-08-17 05:31:46 +00004336 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00004337 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00004338 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004339 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00004340 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00004341 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00004342 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004343 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004344 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004345 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004346 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00004347 }
4348
Douglas Gregor838db382010-02-11 01:19:42 +00004349 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00004350 }
Mike Stump1eb44332009-09-09 15:08:12 +00004351
Anders Carlsson71993dd2007-08-17 05:31:46 +00004352 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00004353}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004354
Fariborz Jahanianf7992132013-01-04 18:45:40 +00004355QualType ASTContext::getObjCSuperType() const {
4356 if (ObjCSuperType.isNull()) {
4357 RecordDecl *ObjCSuperTypeDecl =
4358 CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get("objc_super"));
4359 TUDecl->addDecl(ObjCSuperTypeDecl);
4360 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4361 }
4362 return ObjCSuperType;
4363}
4364
Douglas Gregor319ac892009-04-23 22:29:11 +00004365void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004366 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00004367 assert(Rec && "Invalid CFConstantStringType");
4368 CFConstantStringTypeDecl = Rec->getDecl();
4369}
4370
Jay Foad4ba2a172011-01-12 09:06:06 +00004371QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpadaaad32009-10-20 02:12:22 +00004372 if (BlockDescriptorType)
4373 return getTagDeclType(BlockDescriptorType);
4374
4375 RecordDecl *T;
4376 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004377 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004378 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00004379 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00004380
4381 QualType FieldTypes[] = {
4382 UnsignedLongTy,
4383 UnsignedLongTy,
4384 };
4385
4386 const char *FieldNames[] = {
4387 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00004388 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00004389 };
4390
4391 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004392 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00004393 SourceLocation(),
4394 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004395 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00004396 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004397 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004398 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004399 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00004400 T->addDecl(Field);
4401 }
4402
Douglas Gregor838db382010-02-11 01:19:42 +00004403 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00004404
4405 BlockDescriptorType = T;
4406
4407 return getTagDeclType(BlockDescriptorType);
4408}
4409
Jay Foad4ba2a172011-01-12 09:06:06 +00004410QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stump083c25e2009-10-22 00:49:09 +00004411 if (BlockDescriptorExtendedType)
4412 return getTagDeclType(BlockDescriptorExtendedType);
4413
4414 RecordDecl *T;
4415 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004416 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004417 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00004418 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00004419
4420 QualType FieldTypes[] = {
4421 UnsignedLongTy,
4422 UnsignedLongTy,
4423 getPointerType(VoidPtrTy),
4424 getPointerType(VoidPtrTy)
4425 };
4426
4427 const char *FieldNames[] = {
4428 "reserved",
4429 "Size",
4430 "CopyFuncPtr",
4431 "DestroyFuncPtr"
4432 };
4433
4434 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004435 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stump083c25e2009-10-22 00:49:09 +00004436 SourceLocation(),
4437 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004438 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00004439 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004440 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004441 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004442 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00004443 T->addDecl(Field);
4444 }
4445
Douglas Gregor838db382010-02-11 01:19:42 +00004446 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00004447
4448 BlockDescriptorExtendedType = T;
4449
4450 return getTagDeclType(BlockDescriptorExtendedType);
4451}
4452
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00004453/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4454/// requires copy/dispose. Note that this must match the logic
4455/// in buildByrefHelpers.
4456bool ASTContext::BlockRequiresCopying(QualType Ty,
4457 const VarDecl *D) {
4458 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4459 const Expr *copyExpr = getBlockVarCopyInits(D);
4460 if (!copyExpr && record->hasTrivialDestructor()) return false;
4461
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004462 return true;
Fariborz Jahaniane38be612010-11-17 00:21:28 +00004463 }
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00004464
4465 if (!Ty->isObjCRetainableType()) return false;
4466
4467 Qualifiers qs = Ty.getQualifiers();
4468
4469 // If we have lifetime, that dominates.
4470 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4471 assert(getLangOpts().ObjCAutoRefCount);
4472
4473 switch (lifetime) {
4474 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4475
4476 // These are just bits as far as the runtime is concerned.
4477 case Qualifiers::OCL_ExplicitNone:
4478 case Qualifiers::OCL_Autoreleasing:
4479 return false;
4480
4481 // Tell the runtime that this is ARC __weak, called by the
4482 // byref routines.
4483 case Qualifiers::OCL_Weak:
4484 // ARC __strong __block variables need to be retained.
4485 case Qualifiers::OCL_Strong:
4486 return true;
4487 }
4488 llvm_unreachable("fell out of lifetime switch!");
4489 }
4490 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4491 Ty->isObjCObjectPointerType());
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004492}
4493
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00004494bool ASTContext::getByrefLifetime(QualType Ty,
4495 Qualifiers::ObjCLifetime &LifeTime,
4496 bool &HasByrefExtendedLayout) const {
4497
4498 if (!getLangOpts().ObjC1 ||
4499 getLangOpts().getGC() != LangOptions::NonGC)
4500 return false;
4501
4502 HasByrefExtendedLayout = false;
Fariborz Jahanian34db84f2012-12-11 19:58:01 +00004503 if (Ty->isRecordType()) {
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00004504 HasByrefExtendedLayout = true;
4505 LifeTime = Qualifiers::OCL_None;
4506 }
4507 else if (getLangOpts().ObjCAutoRefCount)
4508 LifeTime = Ty.getObjCLifetime();
4509 // MRR.
4510 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4511 LifeTime = Qualifiers::OCL_ExplicitNone;
4512 else
4513 LifeTime = Qualifiers::OCL_None;
4514 return true;
4515}
4516
Douglas Gregore97179c2011-09-08 01:46:34 +00004517TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4518 if (!ObjCInstanceTypeDecl)
4519 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4520 getTranslationUnitDecl(),
4521 SourceLocation(),
4522 SourceLocation(),
4523 &Idents.get("instancetype"),
4524 getTrivialTypeSourceInfo(getObjCIdType()));
4525 return ObjCInstanceTypeDecl;
4526}
4527
Anders Carlssone8c49532007-10-29 06:33:42 +00004528// This returns true if a type has been typedefed to BOOL:
4529// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00004530static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00004531 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00004532 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4533 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00004534
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004535 return false;
4536}
4537
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004538/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004539/// purpose.
Jay Foad4ba2a172011-01-12 09:06:06 +00004540CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregorf968d832011-05-27 01:19:52 +00004541 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4542 return CharUnits::Zero();
4543
Ken Dyck199c3d62010-01-11 17:06:35 +00004544 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00004545
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004546 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004547 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004548 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004549 // Treat arrays as pointers, since that's how they're passed in.
4550 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004551 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004552 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00004553}
4554
4555static inline
4556std::string charUnitsToString(const CharUnits &CU) {
4557 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004558}
4559
John McCall6b5a61b2011-02-07 10:33:21 +00004560/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00004561/// declaration.
John McCall6b5a61b2011-02-07 10:33:21 +00004562std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4563 std::string S;
4564
David Chisnall5e530af2009-11-17 19:33:30 +00004565 const BlockDecl *Decl = Expr->getBlockDecl();
4566 QualType BlockTy =
4567 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4568 // Encode result type.
Fariborz Jahanian3d145f62012-11-15 19:02:45 +00004569 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian06cffc02012-11-14 23:11:38 +00004570 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None,
4571 BlockTy->getAs<FunctionType>()->getResultType(),
4572 S, true /*Extended*/);
4573 else
4574 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(),
4575 S);
David Chisnall5e530af2009-11-17 19:33:30 +00004576 // Compute size of all parameters.
4577 // Start with computing size of a pointer in number of bytes.
4578 // FIXME: There might(should) be a better way of doing this computation!
4579 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004580 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4581 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00004582 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00004583 E = Decl->param_end(); PI != E; ++PI) {
4584 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004585 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahanian075a5432012-06-30 00:48:59 +00004586 if (sz.isZero())
4587 continue;
Ken Dyck199c3d62010-01-11 17:06:35 +00004588 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00004589 ParmOffset += sz;
4590 }
4591 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00004592 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00004593 // Block pointer and offset.
4594 S += "@?0";
David Chisnall5e530af2009-11-17 19:33:30 +00004595
4596 // Argument types.
4597 ParmOffset = PtrSize;
4598 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4599 Decl->param_end(); PI != E; ++PI) {
4600 ParmVarDecl *PVDecl = *PI;
4601 QualType PType = PVDecl->getOriginalType();
4602 if (const ArrayType *AT =
4603 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4604 // Use array's original type only if it has known number of
4605 // elements.
4606 if (!isa<ConstantArrayType>(AT))
4607 PType = PVDecl->getType();
4608 } else if (PType->isFunctionType())
4609 PType = PVDecl->getType();
Fariborz Jahanian3d145f62012-11-15 19:02:45 +00004610 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian06cffc02012-11-14 23:11:38 +00004611 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4612 S, true /*Extended*/);
4613 else
4614 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00004615 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004616 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00004617 }
John McCall6b5a61b2011-02-07 10:33:21 +00004618
4619 return S;
David Chisnall5e530af2009-11-17 19:33:30 +00004620}
4621
Douglas Gregorf968d832011-05-27 01:19:52 +00004622bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall5389f482010-12-30 14:05:53 +00004623 std::string& S) {
4624 // Encode result type.
4625 getObjCEncodingForType(Decl->getResultType(), S);
4626 CharUnits ParmOffset;
4627 // Compute size of all parameters.
4628 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4629 E = Decl->param_end(); PI != E; ++PI) {
4630 QualType PType = (*PI)->getType();
4631 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004632 if (sz.isZero())
Fariborz Jahanian7e68ba52012-06-29 22:54:56 +00004633 continue;
4634
David Chisnall5389f482010-12-30 14:05:53 +00004635 assert (sz.isPositive() &&
Douglas Gregorf968d832011-05-27 01:19:52 +00004636 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall5389f482010-12-30 14:05:53 +00004637 ParmOffset += sz;
4638 }
4639 S += charUnitsToString(ParmOffset);
4640 ParmOffset = CharUnits::Zero();
4641
4642 // Argument types.
4643 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4644 E = Decl->param_end(); PI != E; ++PI) {
4645 ParmVarDecl *PVDecl = *PI;
4646 QualType PType = PVDecl->getOriginalType();
4647 if (const ArrayType *AT =
4648 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4649 // Use array's original type only if it has known number of
4650 // elements.
4651 if (!isa<ConstantArrayType>(AT))
4652 PType = PVDecl->getType();
4653 } else if (PType->isFunctionType())
4654 PType = PVDecl->getType();
4655 getObjCEncodingForType(PType, S);
4656 S += charUnitsToString(ParmOffset);
4657 ParmOffset += getObjCEncodingTypeSize(PType);
4658 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004659
4660 return false;
David Chisnall5389f482010-12-30 14:05:53 +00004661}
4662
Bob Wilsondc8dab62011-11-30 01:57:58 +00004663/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4664/// method parameter or return type. If Extended, include class names and
4665/// block object types.
4666void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4667 QualType T, std::string& S,
4668 bool Extended) const {
4669 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4670 getObjCEncodingForTypeQualifier(QT, S);
4671 // Encode parameter type.
4672 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4673 true /*OutermostType*/,
4674 false /*EncodingProperty*/,
4675 false /*StructField*/,
4676 Extended /*EncodeBlockParameters*/,
4677 Extended /*EncodeClassNames*/);
4678}
4679
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004680/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004681/// declaration.
Douglas Gregorf968d832011-05-27 01:19:52 +00004682bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilsondc8dab62011-11-30 01:57:58 +00004683 std::string& S,
4684 bool Extended) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004685 // FIXME: This is not very efficient.
Bob Wilsondc8dab62011-11-30 01:57:58 +00004686 // Encode return type.
4687 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4688 Decl->getResultType(), S, Extended);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004689 // Compute size of all parameters.
4690 // Start with computing size of a pointer in number of bytes.
4691 // FIXME: There might(should) be a better way of doing this computation!
4692 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004693 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004694 // The first two arguments (self and _cmd) are pointers; account for
4695 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00004696 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004697 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004698 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00004699 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004700 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004701 if (sz.isZero())
Fariborz Jahanian7e68ba52012-06-29 22:54:56 +00004702 continue;
4703
Ken Dyck199c3d62010-01-11 17:06:35 +00004704 assert (sz.isPositive() &&
4705 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004706 ParmOffset += sz;
4707 }
Ken Dyck199c3d62010-01-11 17:06:35 +00004708 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004709 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00004710 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00004711
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004712 // Argument types.
4713 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004714 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004715 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004716 const ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00004717 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00004718 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00004719 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4720 // Use array's original type only if it has known number of
4721 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00004722 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00004723 PType = PVDecl->getType();
4724 } else if (PType->isFunctionType())
4725 PType = PVDecl->getType();
Bob Wilsondc8dab62011-11-30 01:57:58 +00004726 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4727 PType, S, Extended);
Ken Dyck199c3d62010-01-11 17:06:35 +00004728 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004729 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004730 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004731
4732 return false;
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004733}
4734
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004735/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004736/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004737/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4738/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00004739/// Property attributes are stored as a comma-delimited C string. The simple
4740/// attributes readonly and bycopy are encoded as single characters. The
4741/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4742/// encoded as single characters, followed by an identifier. Property types
4743/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004744/// these attributes are defined by the following enumeration:
4745/// @code
4746/// enum PropertyAttributes {
4747/// kPropertyReadOnly = 'R', // property is read-only.
4748/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4749/// kPropertyByref = '&', // property is a reference to the value last assigned
4750/// kPropertyDynamic = 'D', // property is dynamic
4751/// kPropertyGetter = 'G', // followed by getter selector name
4752/// kPropertySetter = 'S', // followed by setter selector name
4753/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson0d4cb852012-03-22 17:48:02 +00004754/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004755/// kPropertyWeak = 'W' // 'weak' property
4756/// kPropertyStrong = 'P' // property GC'able
4757/// kPropertyNonAtomic = 'N' // property non-atomic
4758/// };
4759/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00004760void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004761 const Decl *Container,
Jay Foad4ba2a172011-01-12 09:06:06 +00004762 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004763 // Collect information from the property implementation decl(s).
4764 bool Dynamic = false;
4765 ObjCPropertyImplDecl *SynthesizePID = 0;
4766
4767 // FIXME: Duplicated code due to poor abstraction.
4768 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00004769 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004770 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4771 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004772 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004773 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00004774 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004775 if (PID->getPropertyDecl() == PD) {
4776 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4777 Dynamic = true;
4778 } else {
4779 SynthesizePID = PID;
4780 }
4781 }
4782 }
4783 } else {
Chris Lattner61710852008-10-05 17:34:18 +00004784 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004785 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004786 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004787 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00004788 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004789 if (PID->getPropertyDecl() == PD) {
4790 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4791 Dynamic = true;
4792 } else {
4793 SynthesizePID = PID;
4794 }
4795 }
Mike Stump1eb44332009-09-09 15:08:12 +00004796 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004797 }
4798 }
4799
4800 // FIXME: This is not very efficient.
4801 S = "T";
4802
4803 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004804 // GCC has some special rules regarding encoding of properties which
4805 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00004806 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004807 true /* outermost type */,
4808 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004809
4810 if (PD->isReadOnly()) {
4811 S += ",R";
4812 } else {
4813 switch (PD->getSetterKind()) {
4814 case ObjCPropertyDecl::Assign: break;
4815 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00004816 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian3a02b442011-08-12 20:47:08 +00004817 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004818 }
4819 }
4820
4821 // It really isn't clear at all what this means, since properties
4822 // are "dynamic by default".
4823 if (Dynamic)
4824 S += ",D";
4825
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004826 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4827 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00004828
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004829 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4830 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004831 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004832 }
4833
4834 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4835 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004836 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004837 }
4838
4839 if (SynthesizePID) {
4840 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4841 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00004842 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004843 }
4844
4845 // FIXME: OBJCGC: weak & strong
4846}
4847
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004848/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00004849/// Another legacy compatibility encoding: 32-bit longs are encoded as
4850/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004851/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4852///
4853void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00004854 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00004855 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad4ba2a172011-01-12 09:06:06 +00004856 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004857 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00004858 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004859 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004860 PointeeTy = IntTy;
4861 }
4862 }
4863}
4864
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004865void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad4ba2a172011-01-12 09:06:06 +00004866 const FieldDecl *Field) const {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004867 // We follow the behavior of gcc, expanding structures which are
4868 // directly pointed to, and expanding embedded structures. Note that
4869 // these rules are sufficient to prevent recursive encoding of the
4870 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00004871 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00004872 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004873}
4874
John McCall3624e9e2012-12-20 02:45:14 +00004875static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
4876 BuiltinType::Kind kind) {
4877 switch (kind) {
David Chisnall64fd7e82010-06-04 01:10:52 +00004878 case BuiltinType::Void: return 'v';
4879 case BuiltinType::Bool: return 'B';
4880 case BuiltinType::Char_U:
4881 case BuiltinType::UChar: return 'C';
John McCall3624e9e2012-12-20 02:45:14 +00004882 case BuiltinType::Char16:
David Chisnall64fd7e82010-06-04 01:10:52 +00004883 case BuiltinType::UShort: return 'S';
John McCall3624e9e2012-12-20 02:45:14 +00004884 case BuiltinType::Char32:
David Chisnall64fd7e82010-06-04 01:10:52 +00004885 case BuiltinType::UInt: return 'I';
4886 case BuiltinType::ULong:
John McCall3624e9e2012-12-20 02:45:14 +00004887 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004888 case BuiltinType::UInt128: return 'T';
4889 case BuiltinType::ULongLong: return 'Q';
4890 case BuiltinType::Char_S:
4891 case BuiltinType::SChar: return 'c';
4892 case BuiltinType::Short: return 's';
Chris Lattner3f59c972010-12-25 23:25:43 +00004893 case BuiltinType::WChar_S:
4894 case BuiltinType::WChar_U:
David Chisnall64fd7e82010-06-04 01:10:52 +00004895 case BuiltinType::Int: return 'i';
4896 case BuiltinType::Long:
John McCall3624e9e2012-12-20 02:45:14 +00004897 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004898 case BuiltinType::LongLong: return 'q';
4899 case BuiltinType::Int128: return 't';
4900 case BuiltinType::Float: return 'f';
4901 case BuiltinType::Double: return 'd';
Daniel Dunbar3a0be842010-10-11 21:13:48 +00004902 case BuiltinType::LongDouble: return 'D';
John McCall3624e9e2012-12-20 02:45:14 +00004903 case BuiltinType::NullPtr: return '*'; // like char*
4904
4905 case BuiltinType::Half:
4906 // FIXME: potentially need @encodes for these!
4907 return ' ';
4908
4909 case BuiltinType::ObjCId:
4910 case BuiltinType::ObjCClass:
4911 case BuiltinType::ObjCSel:
4912 llvm_unreachable("@encoding ObjC primitive type");
4913
4914 // OpenCL and placeholder types don't need @encodings.
4915 case BuiltinType::OCLImage1d:
4916 case BuiltinType::OCLImage1dArray:
4917 case BuiltinType::OCLImage1dBuffer:
4918 case BuiltinType::OCLImage2d:
4919 case BuiltinType::OCLImage2dArray:
4920 case BuiltinType::OCLImage3d:
Guy Benyeie6b9d802013-01-20 12:31:11 +00004921 case BuiltinType::OCLEvent:
John McCall3624e9e2012-12-20 02:45:14 +00004922 case BuiltinType::Dependent:
4923#define BUILTIN_TYPE(KIND, ID)
4924#define PLACEHOLDER_TYPE(KIND, ID) \
4925 case BuiltinType::KIND:
4926#include "clang/AST/BuiltinTypes.def"
4927 llvm_unreachable("invalid builtin type for @encode");
David Chisnall64fd7e82010-06-04 01:10:52 +00004928 }
David Blaikie719e53f2013-01-09 17:48:41 +00004929 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnall64fd7e82010-06-04 01:10:52 +00004930}
4931
Douglas Gregor5471bc82011-09-08 17:18:35 +00004932static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4933 EnumDecl *Enum = ET->getDecl();
4934
4935 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4936 if (!Enum->isFixed())
4937 return 'i';
4938
4939 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall3624e9e2012-12-20 02:45:14 +00004940 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
4941 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor5471bc82011-09-08 17:18:35 +00004942}
4943
Jay Foad4ba2a172011-01-12 09:06:06 +00004944static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00004945 QualType T, const FieldDecl *FD) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004946 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004947 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00004948 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4949 // The GNU runtime requires more information; bitfields are encoded as b,
4950 // then the offset (in bits) of the first element, then the type of the
4951 // bitfield, then the size in bits. For example, in this structure:
4952 //
4953 // struct
4954 // {
4955 // int integer;
4956 // int flags:2;
4957 // };
4958 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4959 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4960 // information is not especially sensible, but we're stuck with it for
4961 // compatibility with GCC, although providing it breaks anything that
4962 // actually uses runtime introspection and wants to work on both runtimes...
John McCall260611a2012-06-20 06:18:46 +00004963 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnall64fd7e82010-06-04 01:10:52 +00004964 const RecordDecl *RD = FD->getParent();
4965 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedman82905742011-07-07 01:54:01 +00004966 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor5471bc82011-09-08 17:18:35 +00004967 if (const EnumType *ET = T->getAs<EnumType>())
4968 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall3624e9e2012-12-20 02:45:14 +00004969 else {
4970 const BuiltinType *BT = T->castAs<BuiltinType>();
4971 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
4972 }
David Chisnall64fd7e82010-06-04 01:10:52 +00004973 }
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004974 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004975}
4976
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00004977// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004978void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4979 bool ExpandPointedToStructures,
4980 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00004981 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004982 bool OutermostType,
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004983 bool EncodingProperty,
Bob Wilsondc8dab62011-11-30 01:57:58 +00004984 bool StructField,
4985 bool EncodeBlockParameters,
4986 bool EncodeClassNames) const {
John McCall3624e9e2012-12-20 02:45:14 +00004987 CanQualType CT = getCanonicalType(T);
4988 switch (CT->getTypeClass()) {
4989 case Type::Builtin:
4990 case Type::Enum:
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004991 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004992 return EncodeBitField(this, S, T, FD);
John McCall3624e9e2012-12-20 02:45:14 +00004993 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
4994 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
4995 else
4996 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004997 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004998
John McCall3624e9e2012-12-20 02:45:14 +00004999 case Type::Complex: {
5000 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlssonc612f7b2009-04-09 21:55:45 +00005001 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00005002 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00005003 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005004 return;
5005 }
John McCall3624e9e2012-12-20 02:45:14 +00005006
5007 case Type::Atomic: {
5008 const AtomicType *AT = T->castAs<AtomicType>();
5009 S += 'A';
5010 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, 0,
5011 false, false);
5012 return;
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00005013 }
John McCall3624e9e2012-12-20 02:45:14 +00005014
5015 // encoding for pointer or reference types.
5016 case Type::Pointer:
5017 case Type::LValueReference:
5018 case Type::RValueReference: {
5019 QualType PointeeTy;
5020 if (isa<PointerType>(CT)) {
5021 const PointerType *PT = T->castAs<PointerType>();
5022 if (PT->isObjCSelType()) {
5023 S += ':';
5024 return;
5025 }
5026 PointeeTy = PT->getPointeeType();
5027 } else {
5028 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5029 }
5030
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005031 bool isReadOnly = false;
5032 // For historical/compatibility reasons, the read-only qualifier of the
5033 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5034 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00005035 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00005036 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005037 if (OutermostType && T.isConstQualified()) {
5038 isReadOnly = true;
5039 S += 'r';
5040 }
Mike Stump9fdbab32009-07-31 02:02:20 +00005041 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005042 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00005043 while (P->getAs<PointerType>())
5044 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005045 if (P.isConstQualified()) {
5046 isReadOnly = true;
5047 S += 'r';
5048 }
5049 }
5050 if (isReadOnly) {
5051 // Another legacy compatibility encoding. Some ObjC qualifier and type
5052 // combinations need to be rearranged.
5053 // Rewrite "in const" from "nr" to "rn"
Chris Lattner5f9e2722011-07-23 10:55:15 +00005054 if (StringRef(S).endswith("nr"))
Benjamin Kramer02379412010-04-27 17:12:11 +00005055 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005056 }
Mike Stump1eb44332009-09-09 15:08:12 +00005057
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005058 if (PointeeTy->isCharType()) {
5059 // char pointer types should be encoded as '*' unless it is a
5060 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00005061 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005062 S += '*';
5063 return;
5064 }
Ted Kremenek6217b802009-07-29 21:53:49 +00005065 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00005066 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5067 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5068 S += '#';
5069 return;
5070 }
5071 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5072 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5073 S += '@';
5074 return;
5075 }
5076 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005077 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005078 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005079 getLegacyIntegralTypeEncoding(PointeeTy);
5080
Mike Stump1eb44332009-09-09 15:08:12 +00005081 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005082 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005083 return;
5084 }
John McCall3624e9e2012-12-20 02:45:14 +00005085
5086 case Type::ConstantArray:
5087 case Type::IncompleteArray:
5088 case Type::VariableArray: {
5089 const ArrayType *AT = cast<ArrayType>(CT);
5090
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005091 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlsson559a8332009-02-22 01:38:57 +00005092 // Incomplete arrays are encoded as a pointer to the array element.
5093 S += '^';
5094
Mike Stump1eb44332009-09-09 15:08:12 +00005095 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00005096 false, ExpandStructures, FD);
5097 } else {
5098 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00005099
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005100 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
5101 if (getTypeSize(CAT->getElementType()) == 0)
5102 S += '0';
5103 else
5104 S += llvm::utostr(CAT->getSize().getZExtValue());
5105 } else {
Anders Carlsson559a8332009-02-22 01:38:57 +00005106 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005107 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5108 "Unknown array type!");
Anders Carlsson559a8332009-02-22 01:38:57 +00005109 S += '0';
5110 }
Mike Stump1eb44332009-09-09 15:08:12 +00005111
5112 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00005113 false, ExpandStructures, FD);
5114 S += ']';
5115 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005116 return;
5117 }
Mike Stump1eb44332009-09-09 15:08:12 +00005118
John McCall3624e9e2012-12-20 02:45:14 +00005119 case Type::FunctionNoProto:
5120 case Type::FunctionProto:
Anders Carlssonc0a87b72007-10-30 00:06:20 +00005121 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005122 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005123
John McCall3624e9e2012-12-20 02:45:14 +00005124 case Type::Record: {
5125 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005126 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00005127 // Anonymous structures print as '?'
5128 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5129 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00005130 if (ClassTemplateSpecializationDecl *Spec
5131 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5132 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
5133 std::string TemplateArgsStr
5134 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00005135 TemplateArgs.data(),
5136 TemplateArgs.size(),
Douglas Gregor30c42402011-09-27 22:38:19 +00005137 (*this).getPrintingPolicy());
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00005138
5139 S += TemplateArgsStr;
5140 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00005141 } else {
5142 S += '?';
5143 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00005144 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00005145 S += '=';
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005146 if (!RDecl->isUnion()) {
5147 getObjCEncodingForStructureImpl(RDecl, S, FD);
5148 } else {
5149 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5150 FieldEnd = RDecl->field_end();
5151 Field != FieldEnd; ++Field) {
5152 if (FD) {
5153 S += '"';
5154 S += Field->getNameAsString();
5155 S += '"';
5156 }
Mike Stump1eb44332009-09-09 15:08:12 +00005157
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005158 // Special case bit-fields.
5159 if (Field->isBitField()) {
5160 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie581deb32012-06-06 20:45:41 +00005161 *Field);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005162 } else {
5163 QualType qt = Field->getType();
5164 getLegacyIntegralTypeEncoding(qt);
5165 getObjCEncodingForTypeImpl(qt, S, false, true,
5166 FD, /*OutermostType*/false,
5167 /*EncodingProperty*/false,
5168 /*StructField*/true);
5169 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005170 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00005171 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00005172 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005173 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005174 return;
5175 }
Mike Stump1eb44332009-09-09 15:08:12 +00005176
John McCall3624e9e2012-12-20 02:45:14 +00005177 case Type::BlockPointer: {
5178 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff21a98b12009-02-02 18:24:29 +00005179 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilsondc8dab62011-11-30 01:57:58 +00005180 if (EncodeBlockParameters) {
John McCall3624e9e2012-12-20 02:45:14 +00005181 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilsondc8dab62011-11-30 01:57:58 +00005182
5183 S += '<';
5184 // Block return type
5185 getObjCEncodingForTypeImpl(FT->getResultType(), S,
5186 ExpandPointedToStructures, ExpandStructures,
5187 FD,
5188 false /* OutermostType */,
5189 EncodingProperty,
5190 false /* StructField */,
5191 EncodeBlockParameters,
5192 EncodeClassNames);
5193 // Block self
5194 S += "@?";
5195 // Block parameters
5196 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
5197 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
5198 E = FPT->arg_type_end(); I && (I != E); ++I) {
5199 getObjCEncodingForTypeImpl(*I, S,
5200 ExpandPointedToStructures,
5201 ExpandStructures,
5202 FD,
5203 false /* OutermostType */,
5204 EncodingProperty,
5205 false /* StructField */,
5206 EncodeBlockParameters,
5207 EncodeClassNames);
5208 }
5209 }
5210 S += '>';
5211 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005212 return;
5213 }
Mike Stump1eb44332009-09-09 15:08:12 +00005214
John McCall3624e9e2012-12-20 02:45:14 +00005215 case Type::ObjCObject:
5216 case Type::ObjCInterface: {
5217 // Ignore protocol qualifiers when mangling at this level.
5218 T = T->castAs<ObjCObjectType>()->getBaseType();
John McCallc12c5bb2010-05-15 11:32:37 +00005219
John McCall3624e9e2012-12-20 02:45:14 +00005220 // The assumption seems to be that this assert will succeed
5221 // because nested levels will have filtered out 'id' and 'Class'.
5222 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005223 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00005224 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005225 S += '{';
5226 const IdentifierInfo *II = OI->getIdentifier();
5227 S += II->getName();
5228 S += '=';
Jordy Rosedb8264e2011-07-22 02:08:32 +00005229 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00005230 DeepCollectObjCIvars(OI, true, Ivars);
5231 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00005232 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00005233 if (Field->isBitField())
5234 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005235 else
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00005236 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005237 }
5238 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005239 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005240 }
Mike Stump1eb44332009-09-09 15:08:12 +00005241
John McCall3624e9e2012-12-20 02:45:14 +00005242 case Type::ObjCObjectPointer: {
5243 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff14108da2009-07-10 23:34:53 +00005244 if (OPT->isObjCIdType()) {
5245 S += '@';
5246 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005247 }
Mike Stump1eb44332009-09-09 15:08:12 +00005248
Steve Naroff27d20a22009-10-28 22:03:49 +00005249 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5250 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5251 // Since this is a binary compatibility issue, need to consult with runtime
5252 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00005253 S += '#';
5254 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005255 }
Mike Stump1eb44332009-09-09 15:08:12 +00005256
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005257 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005258 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00005259 ExpandPointedToStructures,
5260 ExpandStructures, FD);
Bob Wilsondc8dab62011-11-30 01:57:58 +00005261 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff14108da2009-07-10 23:34:53 +00005262 // Note that we do extended encoding of protocol qualifer list
5263 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00005264 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005265 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5266 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00005267 S += '<';
5268 S += (*I)->getNameAsString();
5269 S += '>';
5270 }
5271 S += '"';
5272 }
5273 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005274 }
Mike Stump1eb44332009-09-09 15:08:12 +00005275
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005276 QualType PointeeTy = OPT->getPointeeType();
5277 if (!EncodingProperty &&
5278 isa<TypedefType>(PointeeTy.getTypePtr())) {
5279 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00005280 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005281 // {...};
5282 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00005283 getObjCEncodingForTypeImpl(PointeeTy, S,
5284 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005285 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00005286 return;
5287 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005288
5289 S += '@';
Bob Wilsondc8dab62011-11-30 01:57:58 +00005290 if (OPT->getInterfaceDecl() &&
5291 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005292 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00005293 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005294 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5295 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005296 S += '<';
5297 S += (*I)->getNameAsString();
5298 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00005299 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005300 S += '"';
5301 }
5302 return;
5303 }
Mike Stump1eb44332009-09-09 15:08:12 +00005304
John McCall532ec7b2010-05-17 23:56:34 +00005305 // gcc just blithely ignores member pointers.
John McCall3624e9e2012-12-20 02:45:14 +00005306 // FIXME: we shoul do better than that. 'M' is available.
5307 case Type::MemberPointer:
John McCall532ec7b2010-05-17 23:56:34 +00005308 return;
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005309
John McCall3624e9e2012-12-20 02:45:14 +00005310 case Type::Vector:
5311 case Type::ExtVector:
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005312 // This matches gcc's encoding, even though technically it is
5313 // insufficient.
5314 // FIXME. We should do a better job than gcc.
5315 return;
John McCall3624e9e2012-12-20 02:45:14 +00005316
5317#define ABSTRACT_TYPE(KIND, BASE)
5318#define TYPE(KIND, BASE)
5319#define DEPENDENT_TYPE(KIND, BASE) \
5320 case Type::KIND:
5321#define NON_CANONICAL_TYPE(KIND, BASE) \
5322 case Type::KIND:
5323#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5324 case Type::KIND:
5325#include "clang/AST/TypeNodes.def"
5326 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005327 }
John McCall3624e9e2012-12-20 02:45:14 +00005328 llvm_unreachable("bad type kind!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005329}
5330
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005331void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5332 std::string &S,
5333 const FieldDecl *FD,
5334 bool includeVBases) const {
5335 assert(RDecl && "Expected non-null RecordDecl");
5336 assert(!RDecl->isUnion() && "Should not be called for unions");
5337 if (!RDecl->getDefinition())
5338 return;
5339
5340 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5341 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5342 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5343
5344 if (CXXRec) {
5345 for (CXXRecordDecl::base_class_iterator
5346 BI = CXXRec->bases_begin(),
5347 BE = CXXRec->bases_end(); BI != BE; ++BI) {
5348 if (!BI->isVirtual()) {
5349 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005350 if (base->isEmpty())
5351 continue;
Benjamin Kramerd4f51982012-07-04 18:45:14 +00005352 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005353 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5354 std::make_pair(offs, base));
5355 }
5356 }
5357 }
5358
5359 unsigned i = 0;
5360 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5361 FieldEnd = RDecl->field_end();
5362 Field != FieldEnd; ++Field, ++i) {
5363 uint64_t offs = layout.getFieldOffset(i);
5364 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie581deb32012-06-06 20:45:41 +00005365 std::make_pair(offs, *Field));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005366 }
5367
5368 if (CXXRec && includeVBases) {
5369 for (CXXRecordDecl::base_class_iterator
5370 BI = CXXRec->vbases_begin(),
5371 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
5372 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005373 if (base->isEmpty())
5374 continue;
Benjamin Kramerd4f51982012-07-04 18:45:14 +00005375 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Argyrios Kyrtzidis19aa8602011-09-26 18:14:24 +00005376 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
5377 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5378 std::make_pair(offs, base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005379 }
5380 }
5381
5382 CharUnits size;
5383 if (CXXRec) {
5384 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5385 } else {
5386 size = layout.getSize();
5387 }
5388
5389 uint64_t CurOffs = 0;
5390 std::multimap<uint64_t, NamedDecl *>::iterator
5391 CurLayObj = FieldOrBaseOffsets.begin();
5392
Douglas Gregor58db7a52012-04-27 22:30:01 +00005393 if (CXXRec && CXXRec->isDynamicClass() &&
5394 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005395 if (FD) {
5396 S += "\"_vptr$";
5397 std::string recname = CXXRec->getNameAsString();
5398 if (recname.empty()) recname = "?";
5399 S += recname;
5400 S += '"';
5401 }
5402 S += "^^?";
5403 CurOffs += getTypeSize(VoidPtrTy);
5404 }
5405
5406 if (!RDecl->hasFlexibleArrayMember()) {
5407 // Mark the end of the structure.
5408 uint64_t offs = toBits(size);
5409 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5410 std::make_pair(offs, (NamedDecl*)0));
5411 }
5412
5413 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5414 assert(CurOffs <= CurLayObj->first);
5415
5416 if (CurOffs < CurLayObj->first) {
5417 uint64_t padding = CurLayObj->first - CurOffs;
5418 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5419 // packing/alignment of members is different that normal, in which case
5420 // the encoding will be out-of-sync with the real layout.
5421 // If the runtime switches to just consider the size of types without
5422 // taking into account alignment, we could make padding explicit in the
5423 // encoding (e.g. using arrays of chars). The encoding strings would be
5424 // longer then though.
5425 CurOffs += padding;
5426 }
5427
5428 NamedDecl *dcl = CurLayObj->second;
5429 if (dcl == 0)
5430 break; // reached end of structure.
5431
5432 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5433 // We expand the bases without their virtual bases since those are going
5434 // in the initial structure. Note that this differs from gcc which
5435 // expands virtual bases each time one is encountered in the hierarchy,
5436 // making the encoding type bigger than it really is.
5437 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005438 assert(!base->isEmpty());
5439 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005440 } else {
5441 FieldDecl *field = cast<FieldDecl>(dcl);
5442 if (FD) {
5443 S += '"';
5444 S += field->getNameAsString();
5445 S += '"';
5446 }
5447
5448 if (field->isBitField()) {
5449 EncodeBitField(this, S, field->getType(), field);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005450 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005451 } else {
5452 QualType qt = field->getType();
5453 getLegacyIntegralTypeEncoding(qt);
5454 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5455 /*OutermostType*/false,
5456 /*EncodingProperty*/false,
5457 /*StructField*/true);
5458 CurOffs += getTypeSize(field->getType());
5459 }
5460 }
5461 }
5462}
5463
Mike Stump1eb44332009-09-09 15:08:12 +00005464void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00005465 std::string& S) const {
5466 if (QT & Decl::OBJC_TQ_In)
5467 S += 'n';
5468 if (QT & Decl::OBJC_TQ_Inout)
5469 S += 'N';
5470 if (QT & Decl::OBJC_TQ_Out)
5471 S += 'o';
5472 if (QT & Decl::OBJC_TQ_Bycopy)
5473 S += 'O';
5474 if (QT & Decl::OBJC_TQ_Byref)
5475 S += 'R';
5476 if (QT & Decl::OBJC_TQ_Oneway)
5477 S += 'V';
5478}
5479
Douglas Gregor4dfd02a2011-08-12 05:46:01 +00005480TypedefDecl *ASTContext::getObjCIdDecl() const {
5481 if (!ObjCIdDecl) {
5482 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5483 T = getObjCObjectPointerType(T);
5484 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
5485 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5486 getTranslationUnitDecl(),
5487 SourceLocation(), SourceLocation(),
5488 &Idents.get("id"), IdInfo);
5489 }
5490
5491 return ObjCIdDecl;
Steve Naroff7e219e42007-10-15 14:41:52 +00005492}
5493
Douglas Gregor7a27ea52011-08-12 06:17:30 +00005494TypedefDecl *ASTContext::getObjCSelDecl() const {
5495 if (!ObjCSelDecl) {
5496 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5497 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5498 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5499 getTranslationUnitDecl(),
5500 SourceLocation(), SourceLocation(),
5501 &Idents.get("SEL"), SelInfo);
5502 }
5503 return ObjCSelDecl;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00005504}
5505
Douglas Gregor79d67262011-08-12 05:59:41 +00005506TypedefDecl *ASTContext::getObjCClassDecl() const {
5507 if (!ObjCClassDecl) {
5508 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5509 T = getObjCObjectPointerType(T);
5510 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5511 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5512 getTranslationUnitDecl(),
5513 SourceLocation(), SourceLocation(),
5514 &Idents.get("Class"), ClassInfo);
5515 }
5516
5517 return ObjCClassDecl;
Anders Carlsson8baaca52007-10-31 02:53:19 +00005518}
5519
Douglas Gregora6ea10e2012-01-17 18:09:05 +00005520ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5521 if (!ObjCProtocolClassDecl) {
5522 ObjCProtocolClassDecl
5523 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5524 SourceLocation(),
5525 &Idents.get("Protocol"),
5526 /*PrevDecl=*/0,
5527 SourceLocation(), true);
5528 }
5529
5530 return ObjCProtocolClassDecl;
5531}
5532
Meador Ingec5613b22012-06-16 03:34:49 +00005533//===----------------------------------------------------------------------===//
5534// __builtin_va_list Construction Functions
5535//===----------------------------------------------------------------------===//
5536
5537static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5538 // typedef char* __builtin_va_list;
5539 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5540 TypeSourceInfo *TInfo
5541 = Context->getTrivialTypeSourceInfo(CharPtrType);
5542
5543 TypedefDecl *VaListTypeDecl
5544 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5545 Context->getTranslationUnitDecl(),
5546 SourceLocation(), SourceLocation(),
5547 &Context->Idents.get("__builtin_va_list"),
5548 TInfo);
5549 return VaListTypeDecl;
5550}
5551
5552static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5553 // typedef void* __builtin_va_list;
5554 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5555 TypeSourceInfo *TInfo
5556 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5557
5558 TypedefDecl *VaListTypeDecl
5559 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5560 Context->getTranslationUnitDecl(),
5561 SourceLocation(), SourceLocation(),
5562 &Context->Idents.get("__builtin_va_list"),
5563 TInfo);
5564 return VaListTypeDecl;
5565}
5566
Tim Northoverc264e162013-01-31 12:13:10 +00005567static TypedefDecl *
5568CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
5569 RecordDecl *VaListTagDecl;
5570 if (Context->getLangOpts().CPlusPlus) {
5571 // namespace std { struct __va_list {
5572 NamespaceDecl *NS;
5573 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5574 Context->getTranslationUnitDecl(),
5575 /*Inline*/false, SourceLocation(),
5576 SourceLocation(), &Context->Idents.get("std"),
5577 /*PrevDecl*/0);
5578
5579 VaListTagDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5580 Context->getTranslationUnitDecl(),
5581 SourceLocation(), SourceLocation(),
5582 &Context->Idents.get("__va_list"));
5583 VaListTagDecl->setDeclContext(NS);
5584 } else {
5585 // struct __va_list
5586 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5587 Context->getTranslationUnitDecl(),
5588 &Context->Idents.get("__va_list"));
5589 }
5590
5591 VaListTagDecl->startDefinition();
5592
5593 const size_t NumFields = 5;
5594 QualType FieldTypes[NumFields];
5595 const char *FieldNames[NumFields];
5596
5597 // void *__stack;
5598 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
5599 FieldNames[0] = "__stack";
5600
5601 // void *__gr_top;
5602 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
5603 FieldNames[1] = "__gr_top";
5604
5605 // void *__vr_top;
5606 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5607 FieldNames[2] = "__vr_top";
5608
5609 // int __gr_offs;
5610 FieldTypes[3] = Context->IntTy;
5611 FieldNames[3] = "__gr_offs";
5612
5613 // int __vr_offs;
5614 FieldTypes[4] = Context->IntTy;
5615 FieldNames[4] = "__vr_offs";
5616
5617 // Create fields
5618 for (unsigned i = 0; i < NumFields; ++i) {
5619 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5620 VaListTagDecl,
5621 SourceLocation(),
5622 SourceLocation(),
5623 &Context->Idents.get(FieldNames[i]),
5624 FieldTypes[i], /*TInfo=*/0,
5625 /*BitWidth=*/0,
5626 /*Mutable=*/false,
5627 ICIS_NoInit);
5628 Field->setAccess(AS_public);
5629 VaListTagDecl->addDecl(Field);
5630 }
5631 VaListTagDecl->completeDefinition();
5632 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5633 Context->VaListTagTy = VaListTagType;
5634
5635 // } __builtin_va_list;
5636 TypedefDecl *VaListTypedefDecl
5637 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5638 Context->getTranslationUnitDecl(),
5639 SourceLocation(), SourceLocation(),
5640 &Context->Idents.get("__builtin_va_list"),
5641 Context->getTrivialTypeSourceInfo(VaListTagType));
5642
5643 return VaListTypedefDecl;
5644}
5645
Meador Ingec5613b22012-06-16 03:34:49 +00005646static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5647 // typedef struct __va_list_tag {
5648 RecordDecl *VaListTagDecl;
5649
5650 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5651 Context->getTranslationUnitDecl(),
5652 &Context->Idents.get("__va_list_tag"));
5653 VaListTagDecl->startDefinition();
5654
5655 const size_t NumFields = 5;
5656 QualType FieldTypes[NumFields];
5657 const char *FieldNames[NumFields];
5658
5659 // unsigned char gpr;
5660 FieldTypes[0] = Context->UnsignedCharTy;
5661 FieldNames[0] = "gpr";
5662
5663 // unsigned char fpr;
5664 FieldTypes[1] = Context->UnsignedCharTy;
5665 FieldNames[1] = "fpr";
5666
5667 // unsigned short reserved;
5668 FieldTypes[2] = Context->UnsignedShortTy;
5669 FieldNames[2] = "reserved";
5670
5671 // void* overflow_arg_area;
5672 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5673 FieldNames[3] = "overflow_arg_area";
5674
5675 // void* reg_save_area;
5676 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5677 FieldNames[4] = "reg_save_area";
5678
5679 // Create fields
5680 for (unsigned i = 0; i < NumFields; ++i) {
5681 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5682 SourceLocation(),
5683 SourceLocation(),
5684 &Context->Idents.get(FieldNames[i]),
5685 FieldTypes[i], /*TInfo=*/0,
5686 /*BitWidth=*/0,
5687 /*Mutable=*/false,
5688 ICIS_NoInit);
5689 Field->setAccess(AS_public);
5690 VaListTagDecl->addDecl(Field);
5691 }
5692 VaListTagDecl->completeDefinition();
5693 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingefb40e3f2012-07-01 15:57:25 +00005694 Context->VaListTagTy = VaListTagType;
Meador Ingec5613b22012-06-16 03:34:49 +00005695
5696 // } __va_list_tag;
5697 TypedefDecl *VaListTagTypedefDecl
5698 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5699 Context->getTranslationUnitDecl(),
5700 SourceLocation(), SourceLocation(),
5701 &Context->Idents.get("__va_list_tag"),
5702 Context->getTrivialTypeSourceInfo(VaListTagType));
5703 QualType VaListTagTypedefType =
5704 Context->getTypedefType(VaListTagTypedefDecl);
5705
5706 // typedef __va_list_tag __builtin_va_list[1];
5707 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5708 QualType VaListTagArrayType
5709 = Context->getConstantArrayType(VaListTagTypedefType,
5710 Size, ArrayType::Normal, 0);
5711 TypeSourceInfo *TInfo
5712 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5713 TypedefDecl *VaListTypedefDecl
5714 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5715 Context->getTranslationUnitDecl(),
5716 SourceLocation(), SourceLocation(),
5717 &Context->Idents.get("__builtin_va_list"),
5718 TInfo);
5719
5720 return VaListTypedefDecl;
5721}
5722
5723static TypedefDecl *
5724CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5725 // typedef struct __va_list_tag {
5726 RecordDecl *VaListTagDecl;
5727 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5728 Context->getTranslationUnitDecl(),
5729 &Context->Idents.get("__va_list_tag"));
5730 VaListTagDecl->startDefinition();
5731
5732 const size_t NumFields = 4;
5733 QualType FieldTypes[NumFields];
5734 const char *FieldNames[NumFields];
5735
5736 // unsigned gp_offset;
5737 FieldTypes[0] = Context->UnsignedIntTy;
5738 FieldNames[0] = "gp_offset";
5739
5740 // unsigned fp_offset;
5741 FieldTypes[1] = Context->UnsignedIntTy;
5742 FieldNames[1] = "fp_offset";
5743
5744 // void* overflow_arg_area;
5745 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5746 FieldNames[2] = "overflow_arg_area";
5747
5748 // void* reg_save_area;
5749 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5750 FieldNames[3] = "reg_save_area";
5751
5752 // Create fields
5753 for (unsigned i = 0; i < NumFields; ++i) {
5754 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5755 VaListTagDecl,
5756 SourceLocation(),
5757 SourceLocation(),
5758 &Context->Idents.get(FieldNames[i]),
5759 FieldTypes[i], /*TInfo=*/0,
5760 /*BitWidth=*/0,
5761 /*Mutable=*/false,
5762 ICIS_NoInit);
5763 Field->setAccess(AS_public);
5764 VaListTagDecl->addDecl(Field);
5765 }
5766 VaListTagDecl->completeDefinition();
5767 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingefb40e3f2012-07-01 15:57:25 +00005768 Context->VaListTagTy = VaListTagType;
Meador Ingec5613b22012-06-16 03:34:49 +00005769
5770 // } __va_list_tag;
5771 TypedefDecl *VaListTagTypedefDecl
5772 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5773 Context->getTranslationUnitDecl(),
5774 SourceLocation(), SourceLocation(),
5775 &Context->Idents.get("__va_list_tag"),
5776 Context->getTrivialTypeSourceInfo(VaListTagType));
5777 QualType VaListTagTypedefType =
5778 Context->getTypedefType(VaListTagTypedefDecl);
5779
5780 // typedef __va_list_tag __builtin_va_list[1];
5781 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5782 QualType VaListTagArrayType
5783 = Context->getConstantArrayType(VaListTagTypedefType,
5784 Size, ArrayType::Normal,0);
5785 TypeSourceInfo *TInfo
5786 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5787 TypedefDecl *VaListTypedefDecl
5788 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5789 Context->getTranslationUnitDecl(),
5790 SourceLocation(), SourceLocation(),
5791 &Context->Idents.get("__builtin_va_list"),
5792 TInfo);
5793
5794 return VaListTypedefDecl;
5795}
5796
5797static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5798 // typedef int __builtin_va_list[4];
5799 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5800 QualType IntArrayType
5801 = Context->getConstantArrayType(Context->IntTy,
5802 Size, ArrayType::Normal, 0);
5803 TypedefDecl *VaListTypedefDecl
5804 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5805 Context->getTranslationUnitDecl(),
5806 SourceLocation(), SourceLocation(),
5807 &Context->Idents.get("__builtin_va_list"),
5808 Context->getTrivialTypeSourceInfo(IntArrayType));
5809
5810 return VaListTypedefDecl;
5811}
5812
Logan Chieneae5a8202012-10-10 06:56:20 +00005813static TypedefDecl *
5814CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
5815 RecordDecl *VaListDecl;
5816 if (Context->getLangOpts().CPlusPlus) {
5817 // namespace std { struct __va_list {
5818 NamespaceDecl *NS;
5819 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5820 Context->getTranslationUnitDecl(),
5821 /*Inline*/false, SourceLocation(),
5822 SourceLocation(), &Context->Idents.get("std"),
5823 /*PrevDecl*/0);
5824
5825 VaListDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5826 Context->getTranslationUnitDecl(),
5827 SourceLocation(), SourceLocation(),
5828 &Context->Idents.get("__va_list"));
5829
5830 VaListDecl->setDeclContext(NS);
5831
5832 } else {
5833 // struct __va_list {
5834 VaListDecl = CreateRecordDecl(*Context, TTK_Struct,
5835 Context->getTranslationUnitDecl(),
5836 &Context->Idents.get("__va_list"));
5837 }
5838
5839 VaListDecl->startDefinition();
5840
5841 // void * __ap;
5842 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5843 VaListDecl,
5844 SourceLocation(),
5845 SourceLocation(),
5846 &Context->Idents.get("__ap"),
5847 Context->getPointerType(Context->VoidTy),
5848 /*TInfo=*/0,
5849 /*BitWidth=*/0,
5850 /*Mutable=*/false,
5851 ICIS_NoInit);
5852 Field->setAccess(AS_public);
5853 VaListDecl->addDecl(Field);
5854
5855 // };
5856 VaListDecl->completeDefinition();
5857
5858 // typedef struct __va_list __builtin_va_list;
5859 TypeSourceInfo *TInfo
5860 = Context->getTrivialTypeSourceInfo(Context->getRecordType(VaListDecl));
5861
5862 TypedefDecl *VaListTypeDecl
5863 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5864 Context->getTranslationUnitDecl(),
5865 SourceLocation(), SourceLocation(),
5866 &Context->Idents.get("__builtin_va_list"),
5867 TInfo);
5868
5869 return VaListTypeDecl;
5870}
5871
Meador Ingec5613b22012-06-16 03:34:49 +00005872static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
5873 TargetInfo::BuiltinVaListKind Kind) {
5874 switch (Kind) {
5875 case TargetInfo::CharPtrBuiltinVaList:
5876 return CreateCharPtrBuiltinVaListDecl(Context);
5877 case TargetInfo::VoidPtrBuiltinVaList:
5878 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northoverc264e162013-01-31 12:13:10 +00005879 case TargetInfo::AArch64ABIBuiltinVaList:
5880 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Ingec5613b22012-06-16 03:34:49 +00005881 case TargetInfo::PowerABIBuiltinVaList:
5882 return CreatePowerABIBuiltinVaListDecl(Context);
5883 case TargetInfo::X86_64ABIBuiltinVaList:
5884 return CreateX86_64ABIBuiltinVaListDecl(Context);
5885 case TargetInfo::PNaClABIBuiltinVaList:
5886 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chieneae5a8202012-10-10 06:56:20 +00005887 case TargetInfo::AAPCSABIBuiltinVaList:
5888 return CreateAAPCSABIBuiltinVaListDecl(Context);
Meador Ingec5613b22012-06-16 03:34:49 +00005889 }
5890
5891 llvm_unreachable("Unhandled __builtin_va_list type kind");
5892}
5893
5894TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
5895 if (!BuiltinVaListDecl)
5896 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
5897
5898 return BuiltinVaListDecl;
5899}
5900
Meador Ingefb40e3f2012-07-01 15:57:25 +00005901QualType ASTContext::getVaListTagType() const {
5902 // Force the creation of VaListTagTy by building the __builtin_va_list
5903 // declaration.
5904 if (VaListTagTy.isNull())
5905 (void) getBuiltinVaListDecl();
5906
5907 return VaListTagTy;
5908}
5909
Ted Kremeneka526c5c2008-01-07 19:49:32 +00005910void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00005911 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00005912 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00005913
Ted Kremeneka526c5c2008-01-07 19:49:32 +00005914 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00005915}
5916
John McCall0bd6feb2009-12-02 08:04:21 +00005917/// \brief Retrieve the template name that corresponds to a non-empty
5918/// lookup.
Jay Foad4ba2a172011-01-12 09:06:06 +00005919TemplateName
5920ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
5921 UnresolvedSetIterator End) const {
John McCall0bd6feb2009-12-02 08:04:21 +00005922 unsigned size = End - Begin;
5923 assert(size > 1 && "set is not overloaded!");
5924
5925 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
5926 size * sizeof(FunctionTemplateDecl*));
5927 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
5928
5929 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00005930 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00005931 NamedDecl *D = *I;
5932 assert(isa<FunctionTemplateDecl>(D) ||
5933 (isa<UsingShadowDecl>(D) &&
5934 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
5935 *Storage++ = D;
5936 }
5937
5938 return TemplateName(OT);
5939}
5940
Douglas Gregor7532dc62009-03-30 22:58:21 +00005941/// \brief Retrieve the template name that represents a qualified
5942/// template name such as \c std::vector.
Jay Foad4ba2a172011-01-12 09:06:06 +00005943TemplateName
5944ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
5945 bool TemplateKeyword,
5946 TemplateDecl *Template) const {
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00005947 assert(NNS && "Missing nested-name-specifier in qualified template name");
5948
Douglas Gregor789b1f62010-02-04 18:10:26 +00005949 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00005950 llvm::FoldingSetNodeID ID;
5951 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
5952
5953 void *InsertPos = 0;
5954 QualifiedTemplateName *QTN =
5955 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5956 if (!QTN) {
Richard Smith2f47cab2012-08-16 01:19:31 +00005957 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
5958 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregor7532dc62009-03-30 22:58:21 +00005959 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
5960 }
5961
5962 return TemplateName(QTN);
5963}
5964
5965/// \brief Retrieve the template name that represents a dependent
5966/// template name such as \c MetaFun::template apply.
Jay Foad4ba2a172011-01-12 09:06:06 +00005967TemplateName
5968ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
5969 const IdentifierInfo *Name) const {
Mike Stump1eb44332009-09-09 15:08:12 +00005970 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00005971 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00005972
5973 llvm::FoldingSetNodeID ID;
5974 DependentTemplateName::Profile(ID, NNS, Name);
5975
5976 void *InsertPos = 0;
5977 DependentTemplateName *QTN =
5978 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5979
5980 if (QTN)
5981 return TemplateName(QTN);
5982
5983 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5984 if (CanonNNS == NNS) {
Richard Smith2f47cab2012-08-16 01:19:31 +00005985 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5986 DependentTemplateName(NNS, Name);
Douglas Gregor7532dc62009-03-30 22:58:21 +00005987 } else {
5988 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smith2f47cab2012-08-16 01:19:31 +00005989 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5990 DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00005991 DependentTemplateName *CheckQTN =
5992 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5993 assert(!CheckQTN && "Dependent type name canonicalization broken");
5994 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00005995 }
5996
5997 DependentTemplateNames.InsertNode(QTN, InsertPos);
5998 return TemplateName(QTN);
5999}
6000
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006001/// \brief Retrieve the template name that represents a dependent
6002/// template name such as \c MetaFun::template operator+.
6003TemplateName
6004ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00006005 OverloadedOperatorKind Operator) const {
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006006 assert((!NNS || NNS->isDependent()) &&
6007 "Nested name specifier must be dependent");
6008
6009 llvm::FoldingSetNodeID ID;
6010 DependentTemplateName::Profile(ID, NNS, Operator);
6011
6012 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00006013 DependentTemplateName *QTN
6014 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006015
6016 if (QTN)
6017 return TemplateName(QTN);
6018
6019 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6020 if (CanonNNS == NNS) {
Richard Smith2f47cab2012-08-16 01:19:31 +00006021 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6022 DependentTemplateName(NNS, Operator);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006023 } else {
6024 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smith2f47cab2012-08-16 01:19:31 +00006025 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6026 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00006027
6028 DependentTemplateName *CheckQTN
6029 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6030 assert(!CheckQTN && "Dependent template name canonicalization broken");
6031 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006032 }
6033
6034 DependentTemplateNames.InsertNode(QTN, InsertPos);
6035 return TemplateName(QTN);
6036}
6037
Douglas Gregor1aee05d2011-01-15 06:45:20 +00006038TemplateName
John McCall14606042011-06-30 08:33:18 +00006039ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6040 TemplateName replacement) const {
6041 llvm::FoldingSetNodeID ID;
6042 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
6043
6044 void *insertPos = 0;
6045 SubstTemplateTemplateParmStorage *subst
6046 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6047
6048 if (!subst) {
6049 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6050 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6051 }
6052
6053 return TemplateName(subst);
6054}
6055
6056TemplateName
Douglas Gregor1aee05d2011-01-15 06:45:20 +00006057ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6058 const TemplateArgument &ArgPack) const {
6059 ASTContext &Self = const_cast<ASTContext &>(*this);
6060 llvm::FoldingSetNodeID ID;
6061 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
6062
6063 void *InsertPos = 0;
6064 SubstTemplateTemplateParmPackStorage *Subst
6065 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6066
6067 if (!Subst) {
John McCall14606042011-06-30 08:33:18 +00006068 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor1aee05d2011-01-15 06:45:20 +00006069 ArgPack.pack_size(),
6070 ArgPack.pack_begin());
6071 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6072 }
6073
6074 return TemplateName(Subst);
6075}
6076
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006077/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00006078/// TargetInfo, produce the corresponding type. The unsigned @p Type
6079/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00006080CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006081 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00006082 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006083 case TargetInfo::SignedShort: return ShortTy;
6084 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6085 case TargetInfo::SignedInt: return IntTy;
6086 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6087 case TargetInfo::SignedLong: return LongTy;
6088 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6089 case TargetInfo::SignedLongLong: return LongLongTy;
6090 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6091 }
6092
David Blaikieb219cfc2011-09-23 05:06:16 +00006093 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006094}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00006095
6096//===----------------------------------------------------------------------===//
6097// Type Predicates.
6098//===----------------------------------------------------------------------===//
6099
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00006100/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6101/// garbage collection attribute.
6102///
John McCallae278a32011-01-12 00:34:59 +00006103Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikie4e4d0842012-03-11 07:00:24 +00006104 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCallae278a32011-01-12 00:34:59 +00006105 return Qualifiers::GCNone;
6106
David Blaikie4e4d0842012-03-11 07:00:24 +00006107 assert(getLangOpts().ObjC1);
John McCallae278a32011-01-12 00:34:59 +00006108 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6109
6110 // Default behaviour under objective-C's gc is for ObjC pointers
6111 // (or pointers to them) be treated as though they were declared
6112 // as __strong.
6113 if (GCAttrs == Qualifiers::GCNone) {
6114 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6115 return Qualifiers::Strong;
6116 else if (Ty->isPointerType())
6117 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6118 } else {
6119 // It's not valid to set GC attributes on anything that isn't a
6120 // pointer.
6121#ifndef NDEBUG
6122 QualType CT = Ty->getCanonicalTypeInternal();
6123 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6124 CT = AT->getElementType();
6125 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6126#endif
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00006127 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00006128 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00006129}
6130
Chris Lattner6ac46a42008-04-07 06:51:04 +00006131//===----------------------------------------------------------------------===//
6132// Type Compatibility Testing
6133//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00006134
Mike Stump1eb44332009-09-09 15:08:12 +00006135/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00006136/// compatible.
6137static bool areCompatVectorTypes(const VectorType *LHS,
6138 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00006139 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00006140 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00006141 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00006142}
6143
Douglas Gregor255210e2010-08-06 10:14:59 +00006144bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6145 QualType SecondVec) {
6146 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6147 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6148
6149 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6150 return true;
6151
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00006152 // Treat Neon vector types and most AltiVec vector types as if they are the
6153 // equivalent GCC vector types.
Douglas Gregor255210e2010-08-06 10:14:59 +00006154 const VectorType *First = FirstVec->getAs<VectorType>();
6155 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00006156 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor255210e2010-08-06 10:14:59 +00006157 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00006158 First->getVectorKind() != VectorType::AltiVecPixel &&
6159 First->getVectorKind() != VectorType::AltiVecBool &&
6160 Second->getVectorKind() != VectorType::AltiVecPixel &&
6161 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor255210e2010-08-06 10:14:59 +00006162 return true;
6163
6164 return false;
6165}
6166
Steve Naroff4084c302009-07-23 01:01:38 +00006167//===----------------------------------------------------------------------===//
6168// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6169//===----------------------------------------------------------------------===//
6170
6171/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6172/// inheritance hierarchy of 'rProto'.
Jay Foad4ba2a172011-01-12 09:06:06 +00006173bool
6174ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6175 ObjCProtocolDecl *rProto) const {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00006176 if (declaresSameEntity(lProto, rProto))
Steve Naroff4084c302009-07-23 01:01:38 +00006177 return true;
6178 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
6179 E = rProto->protocol_end(); PI != E; ++PI)
6180 if (ProtocolCompatibleWithProtocol(lProto, *PI))
6181 return true;
6182 return false;
6183}
6184
Dmitri Gribenko4c3b8a32012-08-28 02:49:14 +00006185/// QualifiedIdConformsQualifiedId - compare id<pr,...> with id<pr1,...>
Steve Naroff4084c302009-07-23 01:01:38 +00006186/// return true if lhs's protocols conform to rhs's protocol; false
6187/// otherwise.
6188bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
6189 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
6190 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
6191 return false;
6192}
6193
Dmitri Gribenko4c3b8a32012-08-28 02:49:14 +00006194/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6195/// Class<pr1, ...>.
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00006196bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6197 QualType rhs) {
6198 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6199 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6200 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6201
6202 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6203 E = lhsQID->qual_end(); I != E; ++I) {
6204 bool match = false;
6205 ObjCProtocolDecl *lhsProto = *I;
6206 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6207 E = rhsOPT->qual_end(); J != E; ++J) {
6208 ObjCProtocolDecl *rhsProto = *J;
6209 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6210 match = true;
6211 break;
6212 }
6213 }
6214 if (!match)
6215 return false;
6216 }
6217 return true;
6218}
6219
Steve Naroff4084c302009-07-23 01:01:38 +00006220/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6221/// ObjCQualifiedIDType.
6222bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6223 bool compare) {
6224 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00006225 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00006226 lhs->isObjCIdType() || lhs->isObjCClassType())
6227 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00006228 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00006229 rhs->isObjCIdType() || rhs->isObjCClassType())
6230 return true;
6231
6232 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00006233 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00006234
Steve Naroff4084c302009-07-23 01:01:38 +00006235 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006236
Steve Naroff4084c302009-07-23 01:01:38 +00006237 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006238 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00006239 // make sure we check the class hierarchy.
6240 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6241 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6242 E = lhsQID->qual_end(); I != E; ++I) {
6243 // when comparing an id<P> on lhs with a static type on rhs,
6244 // see if static class implements all of id's protocols, directly or
6245 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00006246 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00006247 return false;
6248 }
6249 }
6250 // If there are no qualifiers and no interface, we have an 'id'.
6251 return true;
6252 }
Mike Stump1eb44332009-09-09 15:08:12 +00006253 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00006254 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6255 E = lhsQID->qual_end(); I != E; ++I) {
6256 ObjCProtocolDecl *lhsProto = *I;
6257 bool match = false;
6258
6259 // when comparing an id<P> on lhs with a static type on rhs,
6260 // see if static class implements all of id's protocols, directly or
6261 // through its super class and categories.
6262 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6263 E = rhsOPT->qual_end(); J != E; ++J) {
6264 ObjCProtocolDecl *rhsProto = *J;
6265 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6266 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6267 match = true;
6268 break;
6269 }
6270 }
Mike Stump1eb44332009-09-09 15:08:12 +00006271 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00006272 // make sure we check the class hierarchy.
6273 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6274 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6275 E = lhsQID->qual_end(); I != E; ++I) {
6276 // when comparing an id<P> on lhs with a static type on rhs,
6277 // see if static class implements all of id's protocols, directly or
6278 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00006279 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00006280 match = true;
6281 break;
6282 }
6283 }
6284 }
6285 if (!match)
6286 return false;
6287 }
Mike Stump1eb44332009-09-09 15:08:12 +00006288
Steve Naroff4084c302009-07-23 01:01:38 +00006289 return true;
6290 }
Mike Stump1eb44332009-09-09 15:08:12 +00006291
Steve Naroff4084c302009-07-23 01:01:38 +00006292 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6293 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6294
Mike Stump1eb44332009-09-09 15:08:12 +00006295 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00006296 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006297 // If both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00006298 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
6299 E = lhsOPT->qual_end(); I != E; ++I) {
6300 ObjCProtocolDecl *lhsProto = *I;
6301 bool match = false;
6302
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006303 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff4084c302009-07-23 01:01:38 +00006304 // see if static class implements all of id's protocols, directly or
6305 // through its super class and categories.
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006306 // First, lhs protocols in the qualifier list must be found, direct
6307 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff4084c302009-07-23 01:01:38 +00006308 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6309 E = rhsQID->qual_end(); J != E; ++J) {
6310 ObjCProtocolDecl *rhsProto = *J;
6311 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6312 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6313 match = true;
6314 break;
6315 }
6316 }
6317 if (!match)
6318 return false;
6319 }
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006320
6321 // Static class's protocols, or its super class or category protocols
6322 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6323 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6324 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6325 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6326 // This is rather dubious but matches gcc's behavior. If lhs has
6327 // no type qualifier and its class has no static protocol(s)
6328 // assume that it is mismatch.
6329 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6330 return false;
6331 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6332 LHSInheritedProtocols.begin(),
6333 E = LHSInheritedProtocols.end(); I != E; ++I) {
6334 bool match = false;
6335 ObjCProtocolDecl *lhsProto = (*I);
6336 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6337 E = rhsQID->qual_end(); J != E; ++J) {
6338 ObjCProtocolDecl *rhsProto = *J;
6339 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6340 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6341 match = true;
6342 break;
6343 }
6344 }
6345 if (!match)
6346 return false;
6347 }
6348 }
Steve Naroff4084c302009-07-23 01:01:38 +00006349 return true;
6350 }
6351 return false;
6352}
6353
Eli Friedman3d815e72008-08-22 00:56:42 +00006354/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00006355/// compatible for assignment from RHS to LHS. This handles validation of any
6356/// protocol qualifiers on the LHS or RHS.
6357///
Steve Naroff14108da2009-07-10 23:34:53 +00006358bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6359 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00006360 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6361 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6362
Steve Naroffde2e22d2009-07-15 18:40:39 +00006363 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00006364 if (LHS->isObjCUnqualifiedIdOrClass() ||
6365 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00006366 return true;
6367
John McCallc12c5bb2010-05-15 11:32:37 +00006368 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00006369 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6370 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00006371 false);
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00006372
6373 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6374 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6375 QualType(RHSOPT,0));
6376
John McCallc12c5bb2010-05-15 11:32:37 +00006377 // If we have 2 user-defined types, fall into that path.
6378 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00006379 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00006380
Steve Naroff4084c302009-07-23 01:01:38 +00006381 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00006382}
6383
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006384/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00006385/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006386/// arguments in block literals. When passed as arguments, passing 'A*' where
6387/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6388/// not OK. For the return type, the opposite is not OK.
6389bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6390 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006391 const ObjCObjectPointerType *RHSOPT,
6392 bool BlockReturnType) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00006393 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006394 return true;
6395
6396 if (LHSOPT->isObjCBuiltinType()) {
6397 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6398 }
6399
Fariborz Jahaniana9834482010-04-06 17:23:39 +00006400 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006401 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6402 QualType(RHSOPT,0),
6403 false);
6404
6405 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6406 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6407 if (LHS && RHS) { // We have 2 user-defined types.
6408 if (LHS != RHS) {
6409 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006410 return BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006411 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006412 return !BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006413 }
6414 else
6415 return true;
6416 }
6417 return false;
6418}
6419
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006420/// getIntersectionOfProtocols - This routine finds the intersection of set
6421/// of protocols inherited from two distinct objective-c pointer objects.
6422/// It is used to build composite qualifier list of the composite type of
6423/// the conditional expression involving two objective-c pointer objects.
6424static
6425void getIntersectionOfProtocols(ASTContext &Context,
6426 const ObjCObjectPointerType *LHSOPT,
6427 const ObjCObjectPointerType *RHSOPT,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006428 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006429
John McCallc12c5bb2010-05-15 11:32:37 +00006430 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6431 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6432 assert(LHS->getInterface() && "LHS must have an interface base");
6433 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006434
6435 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6436 unsigned LHSNumProtocols = LHS->getNumProtocols();
6437 if (LHSNumProtocols > 0)
6438 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6439 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006440 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006441 Context.CollectInheritedProtocols(LHS->getInterface(),
6442 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006443 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6444 LHSInheritedProtocols.end());
6445 }
6446
6447 unsigned RHSNumProtocols = RHS->getNumProtocols();
6448 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00006449 ObjCProtocolDecl **RHSProtocols =
6450 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006451 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6452 if (InheritedProtocolSet.count(RHSProtocols[i]))
6453 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier30601782011-08-17 23:08:45 +00006454 } else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006455 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006456 Context.CollectInheritedProtocols(RHS->getInterface(),
6457 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006458 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6459 RHSInheritedProtocols.begin(),
6460 E = RHSInheritedProtocols.end(); I != E; ++I)
6461 if (InheritedProtocolSet.count((*I)))
6462 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006463 }
6464}
6465
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006466/// areCommonBaseCompatible - Returns common base class of the two classes if
6467/// one found. Note that this is O'2 algorithm. But it will be called as the
6468/// last type comparison in a ?-exp of ObjC pointer types before a
6469/// warning is issued. So, its invokation is extremely rare.
6470QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00006471 const ObjCObjectPointerType *Lptr,
6472 const ObjCObjectPointerType *Rptr) {
6473 const ObjCObjectType *LHS = Lptr->getObjectType();
6474 const ObjCObjectType *RHS = Rptr->getObjectType();
6475 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6476 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor60ef3082011-12-15 00:29:59 +00006477 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006478 return QualType();
6479
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00006480 do {
John McCallc12c5bb2010-05-15 11:32:37 +00006481 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006482 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006483 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006484 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6485
6486 QualType Result = QualType(LHS, 0);
6487 if (!Protocols.empty())
6488 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6489 Result = getObjCObjectPointerType(Result);
6490 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006491 }
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00006492 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006493
6494 return QualType();
6495}
6496
John McCallc12c5bb2010-05-15 11:32:37 +00006497bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6498 const ObjCObjectType *RHS) {
6499 assert(LHS->getInterface() && "LHS is not an interface type");
6500 assert(RHS->getInterface() && "RHS is not an interface type");
6501
Chris Lattner6ac46a42008-04-07 06:51:04 +00006502 // Verify that the base decls are compatible: the RHS must be a subclass of
6503 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00006504 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00006505 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006506
Chris Lattner6ac46a42008-04-07 06:51:04 +00006507 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6508 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00006509 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00006510 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00006511
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006512 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6513 // more detailed analysis is required.
6514 if (RHS->getNumProtocols() == 0) {
6515 // OK, if LHS is a superclass of RHS *and*
6516 // this superclass is assignment compatible with LHS.
6517 // false otherwise.
Fariborz Jahanian627788c2011-04-12 16:34:14 +00006518 bool IsSuperClass =
6519 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6520 if (IsSuperClass) {
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006521 // OK if conversion of LHS to SuperClass results in narrowing of types
6522 // ; i.e., SuperClass may implement at least one of the protocols
6523 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6524 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6525 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian627788c2011-04-12 16:34:14 +00006526 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006527 // If super class has no protocols, it is not a match.
6528 if (SuperClassInheritedProtocols.empty())
6529 return false;
6530
6531 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6532 LHSPE = LHS->qual_end();
6533 LHSPI != LHSPE; LHSPI++) {
6534 bool SuperImplementsProtocol = false;
6535 ObjCProtocolDecl *LHSProto = (*LHSPI);
6536
6537 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6538 SuperClassInheritedProtocols.begin(),
6539 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6540 ObjCProtocolDecl *SuperClassProto = (*I);
6541 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6542 SuperImplementsProtocol = true;
6543 break;
6544 }
6545 }
6546 if (!SuperImplementsProtocol)
6547 return false;
6548 }
6549 return true;
6550 }
6551 return false;
6552 }
Mike Stump1eb44332009-09-09 15:08:12 +00006553
John McCallc12c5bb2010-05-15 11:32:37 +00006554 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6555 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006556 LHSPI != LHSPE; LHSPI++) {
6557 bool RHSImplementsProtocol = false;
6558
6559 // If the RHS doesn't implement the protocol on the left, the types
6560 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00006561 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6562 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00006563 RHSPI != RHSPE; RHSPI++) {
6564 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006565 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00006566 break;
6567 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006568 }
6569 // FIXME: For better diagnostics, consider passing back the protocol name.
6570 if (!RHSImplementsProtocol)
6571 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00006572 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006573 // The RHS implements all protocols listed on the LHS.
6574 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00006575}
6576
Steve Naroff389bf462009-02-12 17:52:19 +00006577bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6578 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00006579 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6580 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00006581
Steve Naroff14108da2009-07-10 23:34:53 +00006582 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00006583 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00006584
6585 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6586 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00006587}
6588
Douglas Gregor569c3162010-08-07 11:51:51 +00006589bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6590 return canAssignObjCInterfaces(
6591 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6592 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6593}
6594
Mike Stump1eb44332009-09-09 15:08:12 +00006595/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00006596/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00006597/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00006598/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor447234d2010-07-29 15:18:02 +00006599bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6600 bool CompareUnqualified) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006601 if (getLangOpts().CPlusPlus)
Douglas Gregor0e709ab2010-02-03 21:02:30 +00006602 return hasSameType(LHS, RHS);
6603
Douglas Gregor447234d2010-07-29 15:18:02 +00006604 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman3d815e72008-08-22 00:56:42 +00006605}
6606
Fariborz Jahanianc286f382011-07-12 22:05:16 +00006607bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanian82378392011-07-12 23:20:13 +00006608 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc286f382011-07-12 22:05:16 +00006609}
6610
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006611bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6612 return !mergeTypes(LHS, RHS, true).isNull();
6613}
6614
Peter Collingbourne48466752010-10-24 18:30:18 +00006615/// mergeTransparentUnionType - if T is a transparent union type and a member
6616/// of T is compatible with SubType, return the merged type, else return
6617/// QualType()
6618QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6619 bool OfBlockPointer,
6620 bool Unqualified) {
6621 if (const RecordType *UT = T->getAsUnionType()) {
6622 RecordDecl *UD = UT->getDecl();
6623 if (UD->hasAttr<TransparentUnionAttr>()) {
6624 for (RecordDecl::field_iterator it = UD->field_begin(),
6625 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbournef91d7572010-12-02 21:00:06 +00006626 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00006627 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6628 if (!MT.isNull())
6629 return MT;
6630 }
6631 }
6632 }
6633
6634 return QualType();
6635}
6636
6637/// mergeFunctionArgumentTypes - merge two types which appear as function
6638/// argument types
6639QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
6640 bool OfBlockPointer,
6641 bool Unqualified) {
6642 // GNU extension: two types are compatible if they appear as a function
6643 // argument, one of the types is a transparent union type and the other
6644 // type is compatible with a union member
6645 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6646 Unqualified);
6647 if (!lmerge.isNull())
6648 return lmerge;
6649
6650 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6651 Unqualified);
6652 if (!rmerge.isNull())
6653 return rmerge;
6654
6655 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6656}
6657
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006658QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor447234d2010-07-29 15:18:02 +00006659 bool OfBlockPointer,
6660 bool Unqualified) {
John McCall183700f2009-09-21 23:43:11 +00006661 const FunctionType *lbase = lhs->getAs<FunctionType>();
6662 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00006663 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6664 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00006665 bool allLTypes = true;
6666 bool allRTypes = true;
6667
6668 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006669 QualType retType;
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00006670 if (OfBlockPointer) {
6671 QualType RHS = rbase->getResultType();
6672 QualType LHS = lbase->getResultType();
6673 bool UnqualifiedResult = Unqualified;
6674 if (!UnqualifiedResult)
6675 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006676 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00006677 }
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006678 else
John McCall8cc246c2010-12-15 01:06:38 +00006679 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6680 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006681 if (retType.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006682
6683 if (Unqualified)
6684 retType = retType.getUnqualifiedType();
6685
6686 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6687 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6688 if (Unqualified) {
6689 LRetType = LRetType.getUnqualifiedType();
6690 RRetType = RRetType.getUnqualifiedType();
6691 }
6692
6693 if (getCanonicalType(retType) != LRetType)
Chris Lattner61710852008-10-05 17:34:18 +00006694 allLTypes = false;
Douglas Gregor447234d2010-07-29 15:18:02 +00006695 if (getCanonicalType(retType) != RRetType)
Chris Lattner61710852008-10-05 17:34:18 +00006696 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00006697
Daniel Dunbar6a15c852010-04-28 16:20:58 +00006698 // FIXME: double check this
6699 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6700 // rbase->getRegParmAttr() != 0 &&
6701 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00006702 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6703 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8cc246c2010-12-15 01:06:38 +00006704
Douglas Gregorab8bbf42010-01-18 17:14:39 +00006705 // Compatible functions must have compatible calling conventions
John McCall8cc246c2010-12-15 01:06:38 +00006706 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00006707 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00006708
John McCall8cc246c2010-12-15 01:06:38 +00006709 // Regparm is part of the calling convention.
Eli Friedmana49218e2011-04-09 08:18:08 +00006710 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6711 return QualType();
John McCall8cc246c2010-12-15 01:06:38 +00006712 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6713 return QualType();
6714
John McCallf85e1932011-06-15 23:02:42 +00006715 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6716 return QualType();
6717
John McCall8cc246c2010-12-15 01:06:38 +00006718 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6719 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8cc246c2010-12-15 01:06:38 +00006720
Rafael Espindola8b8a09e2012-11-29 16:09:03 +00006721 if (lbaseInfo.getNoReturn() != NoReturn)
6722 allLTypes = false;
6723 if (rbaseInfo.getNoReturn() != NoReturn)
6724 allRTypes = false;
6725
John McCallf85e1932011-06-15 23:02:42 +00006726 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00006727
Eli Friedman3d815e72008-08-22 00:56:42 +00006728 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00006729 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6730 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00006731 unsigned lproto_nargs = lproto->getNumArgs();
6732 unsigned rproto_nargs = rproto->getNumArgs();
6733
6734 // Compatible functions must have the same number of arguments
6735 if (lproto_nargs != rproto_nargs)
6736 return QualType();
6737
6738 // Variadic and non-variadic functions aren't compatible
6739 if (lproto->isVariadic() != rproto->isVariadic())
6740 return QualType();
6741
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00006742 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6743 return QualType();
6744
Fariborz Jahanian78213e42011-09-28 21:52:05 +00006745 if (LangOpts.ObjCAutoRefCount &&
6746 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6747 return QualType();
6748
Eli Friedman3d815e72008-08-22 00:56:42 +00006749 // Check argument compatibility
Chris Lattner5f9e2722011-07-23 10:55:15 +00006750 SmallVector<QualType, 10> types;
Eli Friedman3d815e72008-08-22 00:56:42 +00006751 for (unsigned i = 0; i < lproto_nargs; i++) {
6752 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
6753 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00006754 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
6755 OfBlockPointer,
6756 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006757 if (argtype.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006758
6759 if (Unqualified)
6760 argtype = argtype.getUnqualifiedType();
6761
Eli Friedman3d815e72008-08-22 00:56:42 +00006762 types.push_back(argtype);
Douglas Gregor447234d2010-07-29 15:18:02 +00006763 if (Unqualified) {
6764 largtype = largtype.getUnqualifiedType();
6765 rargtype = rargtype.getUnqualifiedType();
6766 }
6767
Chris Lattner61710852008-10-05 17:34:18 +00006768 if (getCanonicalType(argtype) != getCanonicalType(largtype))
6769 allLTypes = false;
6770 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
6771 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00006772 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00006773
Eli Friedman3d815e72008-08-22 00:56:42 +00006774 if (allLTypes) return lhs;
6775 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00006776
6777 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
6778 EPI.ExtInfo = einfo;
6779 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00006780 }
6781
6782 if (lproto) allRTypes = false;
6783 if (rproto) allLTypes = false;
6784
Douglas Gregor72564e72009-02-26 23:50:07 +00006785 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00006786 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00006787 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00006788 if (proto->isVariadic()) return QualType();
6789 // Check that the types are compatible with the types that
6790 // would result from default argument promotions (C99 6.7.5.3p15).
6791 // The only types actually affected are promotable integer
6792 // types and floats, which would be passed as a different
6793 // type depending on whether the prototype is visible.
6794 unsigned proto_nargs = proto->getNumArgs();
6795 for (unsigned i = 0; i < proto_nargs; ++i) {
6796 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00006797
Eli Friedmanc586d5d2012-08-30 00:44:15 +00006798 // Look at the converted type of enum types, since that is the type used
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00006799 // to pass enum values.
Eli Friedmanc586d5d2012-08-30 00:44:15 +00006800 if (const EnumType *Enum = argTy->getAs<EnumType>()) {
6801 argTy = Enum->getDecl()->getIntegerType();
6802 if (argTy.isNull())
6803 return QualType();
6804 }
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00006805
Eli Friedman3d815e72008-08-22 00:56:42 +00006806 if (argTy->isPromotableIntegerType() ||
6807 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
6808 return QualType();
6809 }
6810
6811 if (allLTypes) return lhs;
6812 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00006813
6814 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
6815 EPI.ExtInfo = einfo;
Eli Friedman3d815e72008-08-22 00:56:42 +00006816 return getFunctionType(retType, proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00006817 proto->getNumArgs(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00006818 }
6819
6820 if (allLTypes) return lhs;
6821 if (allRTypes) return rhs;
John McCall8cc246c2010-12-15 01:06:38 +00006822 return getFunctionNoProtoType(retType, einfo);
Eli Friedman3d815e72008-08-22 00:56:42 +00006823}
6824
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006825QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor447234d2010-07-29 15:18:02 +00006826 bool OfBlockPointer,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006827 bool Unqualified, bool BlockReturnType) {
Bill Wendling43d69752007-12-03 07:33:35 +00006828 // C++ [expr]: If an expression initially has the type "reference to T", the
6829 // type is adjusted to "T" prior to any further analysis, the expression
6830 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00006831 // expression is an lvalue unless the reference is an rvalue reference and
6832 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00006833 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
6834 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor447234d2010-07-29 15:18:02 +00006835
6836 if (Unqualified) {
6837 LHS = LHS.getUnqualifiedType();
6838 RHS = RHS.getUnqualifiedType();
6839 }
Douglas Gregor0e709ab2010-02-03 21:02:30 +00006840
Eli Friedman3d815e72008-08-22 00:56:42 +00006841 QualType LHSCan = getCanonicalType(LHS),
6842 RHSCan = getCanonicalType(RHS);
6843
6844 // If two types are identical, they are compatible.
6845 if (LHSCan == RHSCan)
6846 return LHS;
6847
John McCall0953e762009-09-24 19:53:00 +00006848 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00006849 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6850 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00006851 if (LQuals != RQuals) {
6852 // If any of these qualifiers are different, we have a type
6853 // mismatch.
6854 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCallf85e1932011-06-15 23:02:42 +00006855 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
6856 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall0953e762009-09-24 19:53:00 +00006857 return QualType();
6858
6859 // Exactly one GC qualifier difference is allowed: __strong is
6860 // okay if the other type has no GC qualifier but is an Objective
6861 // C object pointer (i.e. implicitly strong by default). We fix
6862 // this by pretending that the unqualified type was actually
6863 // qualified __strong.
6864 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6865 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6866 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6867
6868 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6869 return QualType();
6870
6871 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
6872 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
6873 }
6874 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
6875 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
6876 }
Eli Friedman3d815e72008-08-22 00:56:42 +00006877 return QualType();
John McCall0953e762009-09-24 19:53:00 +00006878 }
6879
6880 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00006881
Eli Friedman852d63b2009-06-01 01:22:52 +00006882 Type::TypeClass LHSClass = LHSCan->getTypeClass();
6883 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00006884
Chris Lattner1adb8832008-01-14 05:45:46 +00006885 // We want to consider the two function types to be the same for these
6886 // comparisons, just force one to the other.
6887 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
6888 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00006889
6890 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00006891 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
6892 LHSClass = Type::ConstantArray;
6893 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
6894 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00006895
John McCallc12c5bb2010-05-15 11:32:37 +00006896 // ObjCInterfaces are just specialized ObjCObjects.
6897 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
6898 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
6899
Nate Begeman213541a2008-04-18 23:10:10 +00006900 // Canonicalize ExtVector -> Vector.
6901 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
6902 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00006903
Chris Lattnera36a61f2008-04-07 05:43:21 +00006904 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00006905 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00006906 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00006907 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00006908 // Compatibility is based on the underlying type, not the promotion
6909 // type.
John McCall183700f2009-09-21 23:43:11 +00006910 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Fariborz Jahanianb918d6b2012-02-06 19:06:20 +00006911 QualType TINT = ETy->getDecl()->getIntegerType();
6912 if (!TINT.isNull() && hasSameType(TINT, RHSCan.getUnqualifiedType()))
Eli Friedman3d815e72008-08-22 00:56:42 +00006913 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00006914 }
John McCall183700f2009-09-21 23:43:11 +00006915 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Fariborz Jahanianb918d6b2012-02-06 19:06:20 +00006916 QualType TINT = ETy->getDecl()->getIntegerType();
6917 if (!TINT.isNull() && hasSameType(TINT, LHSCan.getUnqualifiedType()))
Eli Friedman3d815e72008-08-22 00:56:42 +00006918 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00006919 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00006920 // allow block pointer type to match an 'id' type.
Fariborz Jahanian41963632012-01-26 17:08:50 +00006921 if (OfBlockPointer && !BlockReturnType) {
6922 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
6923 return LHS;
6924 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
6925 return RHS;
6926 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00006927
Eli Friedman3d815e72008-08-22 00:56:42 +00006928 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00006929 }
Eli Friedman3d815e72008-08-22 00:56:42 +00006930
Steve Naroff4a746782008-01-09 22:43:08 +00006931 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00006932 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00006933#define TYPE(Class, Base)
6934#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00006935#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00006936#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
6937#define DEPENDENT_TYPE(Class, Base) case Type::Class:
6938#include "clang/AST/TypeNodes.def"
David Blaikieb219cfc2011-09-23 05:06:16 +00006939 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregor72564e72009-02-26 23:50:07 +00006940
Sebastian Redl7c80bd62009-03-16 23:22:08 +00006941 case Type::LValueReference:
6942 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00006943 case Type::MemberPointer:
David Blaikieb219cfc2011-09-23 05:06:16 +00006944 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregor72564e72009-02-26 23:50:07 +00006945
John McCallc12c5bb2010-05-15 11:32:37 +00006946 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00006947 case Type::IncompleteArray:
6948 case Type::VariableArray:
6949 case Type::FunctionProto:
6950 case Type::ExtVector:
David Blaikieb219cfc2011-09-23 05:06:16 +00006951 llvm_unreachable("Types are eliminated above");
Douglas Gregor72564e72009-02-26 23:50:07 +00006952
Chris Lattner1adb8832008-01-14 05:45:46 +00006953 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00006954 {
6955 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00006956 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
6957 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006958 if (Unqualified) {
6959 LHSPointee = LHSPointee.getUnqualifiedType();
6960 RHSPointee = RHSPointee.getUnqualifiedType();
6961 }
6962 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
6963 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006964 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00006965 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00006966 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00006967 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00006968 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00006969 return getPointerType(ResultType);
6970 }
Steve Naroffc0febd52008-12-10 17:49:55 +00006971 case Type::BlockPointer:
6972 {
6973 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00006974 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
6975 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006976 if (Unqualified) {
6977 LHSPointee = LHSPointee.getUnqualifiedType();
6978 RHSPointee = RHSPointee.getUnqualifiedType();
6979 }
6980 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
6981 Unqualified);
Steve Naroffc0febd52008-12-10 17:49:55 +00006982 if (ResultType.isNull()) return QualType();
6983 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
6984 return LHS;
6985 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
6986 return RHS;
6987 return getBlockPointerType(ResultType);
6988 }
Eli Friedmanb001de72011-10-06 23:00:33 +00006989 case Type::Atomic:
6990 {
6991 // Merge two pointer types, while trying to preserve typedef info
6992 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
6993 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
6994 if (Unqualified) {
6995 LHSValue = LHSValue.getUnqualifiedType();
6996 RHSValue = RHSValue.getUnqualifiedType();
6997 }
6998 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
6999 Unqualified);
7000 if (ResultType.isNull()) return QualType();
7001 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7002 return LHS;
7003 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7004 return RHS;
7005 return getAtomicType(ResultType);
7006 }
Chris Lattner1adb8832008-01-14 05:45:46 +00007007 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00007008 {
7009 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7010 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7011 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7012 return QualType();
7013
7014 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7015 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor447234d2010-07-29 15:18:02 +00007016 if (Unqualified) {
7017 LHSElem = LHSElem.getUnqualifiedType();
7018 RHSElem = RHSElem.getUnqualifiedType();
7019 }
7020
7021 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00007022 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00007023 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7024 return LHS;
7025 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7026 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00007027 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7028 ArrayType::ArraySizeModifier(), 0);
7029 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7030 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00007031 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7032 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00007033 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7034 return LHS;
7035 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7036 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00007037 if (LVAT) {
7038 // FIXME: This isn't correct! But tricky to implement because
7039 // the array's size has to be the size of LHS, but the type
7040 // has to be different.
7041 return LHS;
7042 }
7043 if (RVAT) {
7044 // FIXME: This isn't correct! But tricky to implement because
7045 // the array's size has to be the size of RHS, but the type
7046 // has to be different.
7047 return RHS;
7048 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00007049 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7050 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00007051 return getIncompleteArrayType(ResultType,
7052 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00007053 }
Chris Lattner1adb8832008-01-14 05:45:46 +00007054 case Type::FunctionNoProto:
Douglas Gregor447234d2010-07-29 15:18:02 +00007055 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregor72564e72009-02-26 23:50:07 +00007056 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00007057 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00007058 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00007059 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00007060 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00007061 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00007062 case Type::Complex:
7063 // Distinct complex types are incompatible.
7064 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00007065 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00007066 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00007067 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7068 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00007069 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00007070 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00007071 case Type::ObjCObject: {
7072 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00007073 // FIXME: This should be type compatibility, e.g. whether
7074 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00007075 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7076 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7077 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00007078 return LHS;
7079
Eli Friedman3d815e72008-08-22 00:56:42 +00007080 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00007081 }
Steve Naroff14108da2009-07-10 23:34:53 +00007082 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00007083 if (OfBlockPointer) {
7084 if (canAssignObjCInterfacesInBlockPointer(
7085 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00007086 RHS->getAs<ObjCObjectPointerType>(),
7087 BlockReturnType))
David Blaikie7530c032012-01-17 06:56:22 +00007088 return LHS;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00007089 return QualType();
7090 }
John McCall183700f2009-09-21 23:43:11 +00007091 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7092 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00007093 return LHS;
7094
Steve Naroffbc76dd02008-12-10 22:14:21 +00007095 return QualType();
David Blaikie7530c032012-01-17 06:56:22 +00007096 }
Steve Naroffec0550f2007-10-15 20:41:53 +00007097 }
Douglas Gregor72564e72009-02-26 23:50:07 +00007098
David Blaikie7530c032012-01-17 06:56:22 +00007099 llvm_unreachable("Invalid Type::Class!");
Steve Naroffec0550f2007-10-15 20:41:53 +00007100}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00007101
Fariborz Jahanian78213e42011-09-28 21:52:05 +00007102bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7103 const FunctionProtoType *FromFunctionType,
7104 const FunctionProtoType *ToFunctionType) {
7105 if (FromFunctionType->hasAnyConsumedArgs() !=
7106 ToFunctionType->hasAnyConsumedArgs())
7107 return false;
7108 FunctionProtoType::ExtProtoInfo FromEPI =
7109 FromFunctionType->getExtProtoInfo();
7110 FunctionProtoType::ExtProtoInfo ToEPI =
7111 ToFunctionType->getExtProtoInfo();
7112 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
7113 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
7114 ArgIdx != NumArgs; ++ArgIdx) {
7115 if (FromEPI.ConsumedArguments[ArgIdx] !=
7116 ToEPI.ConsumedArguments[ArgIdx])
7117 return false;
7118 }
7119 return true;
7120}
7121
Fariborz Jahanian2390a722010-05-19 21:37:30 +00007122/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7123/// 'RHS' attributes and returns the merged version; including for function
7124/// return types.
7125QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7126 QualType LHSCan = getCanonicalType(LHS),
7127 RHSCan = getCanonicalType(RHS);
7128 // If two types are identical, they are compatible.
7129 if (LHSCan == RHSCan)
7130 return LHS;
7131 if (RHSCan->isFunctionType()) {
7132 if (!LHSCan->isFunctionType())
7133 return QualType();
7134 QualType OldReturnType =
7135 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
7136 QualType NewReturnType =
7137 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
7138 QualType ResReturnType =
7139 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7140 if (ResReturnType.isNull())
7141 return QualType();
7142 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7143 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7144 // In either case, use OldReturnType to build the new function type.
7145 const FunctionType *F = LHS->getAs<FunctionType>();
7146 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalle23cf432010-12-14 08:05:40 +00007147 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7148 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00007149 QualType ResultType
7150 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00007151 FPT->getNumArgs(), EPI);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00007152 return ResultType;
7153 }
7154 }
7155 return QualType();
7156 }
7157
7158 // If the qualifiers are different, the types can still be merged.
7159 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7160 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7161 if (LQuals != RQuals) {
7162 // If any of these qualifiers are different, we have a type mismatch.
7163 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7164 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7165 return QualType();
7166
7167 // Exactly one GC qualifier difference is allowed: __strong is
7168 // okay if the other type has no GC qualifier but is an Objective
7169 // C object pointer (i.e. implicitly strong by default). We fix
7170 // this by pretending that the unqualified type was actually
7171 // qualified __strong.
7172 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7173 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7174 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7175
7176 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7177 return QualType();
7178
7179 if (GC_L == Qualifiers::Strong)
7180 return LHS;
7181 if (GC_R == Qualifiers::Strong)
7182 return RHS;
7183 return QualType();
7184 }
7185
7186 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7187 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7188 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7189 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7190 if (ResQT == LHSBaseQT)
7191 return LHS;
7192 if (ResQT == RHSBaseQT)
7193 return RHS;
7194 }
7195 return QualType();
7196}
7197
Chris Lattner5426bf62008-04-07 07:01:58 +00007198//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00007199// Integer Predicates
7200//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00007201
Jay Foad4ba2a172011-01-12 09:06:06 +00007202unsigned ASTContext::getIntWidth(QualType T) const {
John McCallf4c73712011-01-19 06:33:43 +00007203 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00007204 T = ET->getDecl()->getIntegerType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00007205 if (T->isBooleanType())
7206 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00007207 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00007208 return (unsigned)getTypeSize(T);
7209}
7210
Abramo Bagnara762f1592012-09-09 10:21:24 +00007211QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregorf6094622010-07-23 15:58:24 +00007212 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00007213
7214 // Turn <4 x signed int> -> <4 x unsigned int>
7215 if (const VectorType *VTy = T->getAs<VectorType>())
7216 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsone86d78c2010-11-10 21:56:12 +00007217 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattner6a2b9262009-10-17 20:33:28 +00007218
7219 // For enums, we return the unsigned version of the base type.
7220 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00007221 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00007222
7223 const BuiltinType *BTy = T->getAs<BuiltinType>();
7224 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00007225 switch (BTy->getKind()) {
7226 case BuiltinType::Char_S:
7227 case BuiltinType::SChar:
7228 return UnsignedCharTy;
7229 case BuiltinType::Short:
7230 return UnsignedShortTy;
7231 case BuiltinType::Int:
7232 return UnsignedIntTy;
7233 case BuiltinType::Long:
7234 return UnsignedLongTy;
7235 case BuiltinType::LongLong:
7236 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00007237 case BuiltinType::Int128:
7238 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00007239 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00007240 llvm_unreachable("Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00007241 }
7242}
7243
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00007244ASTMutationListener::~ASTMutationListener() { }
7245
Chris Lattner86df27b2009-06-14 00:45:47 +00007246
7247//===----------------------------------------------------------------------===//
7248// Builtin Type Computation
7249//===----------------------------------------------------------------------===//
7250
7251/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattner33daae62010-10-01 22:42:38 +00007252/// pointer over the consumed characters. This returns the resultant type. If
7253/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7254/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7255/// a vector of "i*".
Chris Lattner14e0e742010-10-01 22:53:11 +00007256///
7257/// RequiresICE is filled in on return to indicate whether the value is required
7258/// to be an Integer Constant Expression.
Jay Foad4ba2a172011-01-12 09:06:06 +00007259static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00007260 ASTContext::GetBuiltinTypeError &Error,
Chris Lattner14e0e742010-10-01 22:53:11 +00007261 bool &RequiresICE,
Chris Lattner33daae62010-10-01 22:42:38 +00007262 bool AllowTypeModifiers) {
Chris Lattner86df27b2009-06-14 00:45:47 +00007263 // Modifiers.
7264 int HowLong = 0;
7265 bool Signed = false, Unsigned = false;
Chris Lattner14e0e742010-10-01 22:53:11 +00007266 RequiresICE = false;
Chris Lattner393bd8e2010-10-01 07:13:18 +00007267
Chris Lattner33daae62010-10-01 22:42:38 +00007268 // Read the prefixed modifiers first.
Chris Lattner86df27b2009-06-14 00:45:47 +00007269 bool Done = false;
7270 while (!Done) {
7271 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00007272 default: Done = true; --Str; break;
Chris Lattner393bd8e2010-10-01 07:13:18 +00007273 case 'I':
Chris Lattner14e0e742010-10-01 22:53:11 +00007274 RequiresICE = true;
Chris Lattner393bd8e2010-10-01 07:13:18 +00007275 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007276 case 'S':
7277 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7278 assert(!Signed && "Can't use 'S' modifier multiple times!");
7279 Signed = true;
7280 break;
7281 case 'U':
7282 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7283 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7284 Unsigned = true;
7285 break;
7286 case 'L':
7287 assert(HowLong <= 2 && "Can't have LLLL modifier");
7288 ++HowLong;
7289 break;
7290 }
7291 }
7292
7293 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00007294
Chris Lattner86df27b2009-06-14 00:45:47 +00007295 // Read the base type.
7296 switch (*Str++) {
David Blaikieb219cfc2011-09-23 05:06:16 +00007297 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattner86df27b2009-06-14 00:45:47 +00007298 case 'v':
7299 assert(HowLong == 0 && !Signed && !Unsigned &&
7300 "Bad modifiers used with 'v'!");
7301 Type = Context.VoidTy;
7302 break;
7303 case 'f':
7304 assert(HowLong == 0 && !Signed && !Unsigned &&
7305 "Bad modifiers used with 'f'!");
7306 Type = Context.FloatTy;
7307 break;
7308 case 'd':
7309 assert(HowLong < 2 && !Signed && !Unsigned &&
7310 "Bad modifiers used with 'd'!");
7311 if (HowLong)
7312 Type = Context.LongDoubleTy;
7313 else
7314 Type = Context.DoubleTy;
7315 break;
7316 case 's':
7317 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7318 if (Unsigned)
7319 Type = Context.UnsignedShortTy;
7320 else
7321 Type = Context.ShortTy;
7322 break;
7323 case 'i':
7324 if (HowLong == 3)
7325 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7326 else if (HowLong == 2)
7327 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7328 else if (HowLong == 1)
7329 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7330 else
7331 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7332 break;
7333 case 'c':
7334 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7335 if (Signed)
7336 Type = Context.SignedCharTy;
7337 else if (Unsigned)
7338 Type = Context.UnsignedCharTy;
7339 else
7340 Type = Context.CharTy;
7341 break;
7342 case 'b': // boolean
7343 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7344 Type = Context.BoolTy;
7345 break;
7346 case 'z': // size_t.
7347 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7348 Type = Context.getSizeType();
7349 break;
7350 case 'F':
7351 Type = Context.getCFConstantStringType();
7352 break;
Fariborz Jahanianba8bda02010-11-09 21:38:20 +00007353 case 'G':
7354 Type = Context.getObjCIdType();
7355 break;
7356 case 'H':
7357 Type = Context.getObjCSelType();
7358 break;
Fariborz Jahanianf7992132013-01-04 18:45:40 +00007359 case 'M':
7360 Type = Context.getObjCSuperType();
7361 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007362 case 'a':
7363 Type = Context.getBuiltinVaListType();
7364 assert(!Type.isNull() && "builtin va list type not initialized!");
7365 break;
7366 case 'A':
7367 // This is a "reference" to a va_list; however, what exactly
7368 // this means depends on how va_list is defined. There are two
7369 // different kinds of va_list: ones passed by value, and ones
7370 // passed by reference. An example of a by-value va_list is
7371 // x86, where va_list is a char*. An example of by-ref va_list
7372 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7373 // we want this argument to be a char*&; for x86-64, we want
7374 // it to be a __va_list_tag*.
7375 Type = Context.getBuiltinVaListType();
7376 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattner14e0e742010-10-01 22:53:11 +00007377 if (Type->isArrayType())
Chris Lattner86df27b2009-06-14 00:45:47 +00007378 Type = Context.getArrayDecayedType(Type);
Chris Lattner14e0e742010-10-01 22:53:11 +00007379 else
Chris Lattner86df27b2009-06-14 00:45:47 +00007380 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00007381 break;
7382 case 'V': {
7383 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00007384 unsigned NumElements = strtoul(Str, &End, 10);
7385 assert(End != Str && "Missing vector size");
Chris Lattner86df27b2009-06-14 00:45:47 +00007386 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00007387
Chris Lattner14e0e742010-10-01 22:53:11 +00007388 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7389 RequiresICE, false);
7390 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattner33daae62010-10-01 22:42:38 +00007391
7392 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner788b0fd2010-06-23 06:00:24 +00007393 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00007394 VectorType::GenericVector);
Chris Lattner86df27b2009-06-14 00:45:47 +00007395 break;
7396 }
Douglas Gregorb4bc99b2012-06-07 18:08:25 +00007397 case 'E': {
7398 char *End;
7399
7400 unsigned NumElements = strtoul(Str, &End, 10);
7401 assert(End != Str && "Missing vector size");
7402
7403 Str = End;
7404
7405 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7406 false);
7407 Type = Context.getExtVectorType(ElementType, NumElements);
7408 break;
7409 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00007410 case 'X': {
Chris Lattner14e0e742010-10-01 22:53:11 +00007411 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7412 false);
7413 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregord3a23b22009-09-28 21:45:01 +00007414 Type = Context.getComplexType(ElementType);
7415 break;
Fariborz Jahaniancc075e42011-08-23 23:33:09 +00007416 }
7417 case 'Y' : {
7418 Type = Context.getPointerDiffType();
7419 break;
7420 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00007421 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00007422 Type = Context.getFILEType();
7423 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00007424 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00007425 return QualType();
7426 }
Mike Stumpfd612db2009-07-28 23:47:15 +00007427 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00007428 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00007429 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00007430 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00007431 else
7432 Type = Context.getjmp_bufType();
7433
Mike Stumpfd612db2009-07-28 23:47:15 +00007434 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00007435 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00007436 return QualType();
7437 }
7438 break;
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +00007439 case 'K':
7440 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7441 Type = Context.getucontext_tType();
7442
7443 if (Type.isNull()) {
7444 Error = ASTContext::GE_Missing_ucontext;
7445 return QualType();
7446 }
7447 break;
Eli Friedman6902e412012-11-27 02:58:24 +00007448 case 'p':
7449 Type = Context.getProcessIDType();
7450 break;
Mike Stump782fa302009-07-28 02:25:19 +00007451 }
Mike Stump1eb44332009-09-09 15:08:12 +00007452
Chris Lattner33daae62010-10-01 22:42:38 +00007453 // If there are modifiers and if we're allowed to parse them, go for it.
7454 Done = !AllowTypeModifiers;
Chris Lattner86df27b2009-06-14 00:45:47 +00007455 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00007456 switch (char c = *Str++) {
Chris Lattner33daae62010-10-01 22:42:38 +00007457 default: Done = true; --Str; break;
7458 case '*':
7459 case '&': {
7460 // Both pointers and references can have their pointee types
7461 // qualified with an address space.
7462 char *End;
7463 unsigned AddrSpace = strtoul(Str, &End, 10);
7464 if (End != Str && AddrSpace != 0) {
7465 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7466 Str = End;
7467 }
7468 if (c == '*')
7469 Type = Context.getPointerType(Type);
7470 else
7471 Type = Context.getLValueReferenceType(Type);
7472 break;
7473 }
7474 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7475 case 'C':
7476 Type = Type.withConst();
7477 break;
7478 case 'D':
7479 Type = Context.getVolatileType(Type);
7480 break;
Ted Kremenek18932a02012-01-20 21:40:12 +00007481 case 'R':
7482 Type = Type.withRestrict();
7483 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007484 }
7485 }
Chris Lattner393bd8e2010-10-01 07:13:18 +00007486
Chris Lattner14e0e742010-10-01 22:53:11 +00007487 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner393bd8e2010-10-01 07:13:18 +00007488 "Integer constant 'I' type must be an integer");
Mike Stump1eb44332009-09-09 15:08:12 +00007489
Chris Lattner86df27b2009-06-14 00:45:47 +00007490 return Type;
7491}
7492
7493/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattner33daae62010-10-01 22:42:38 +00007494QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattner14e0e742010-10-01 22:53:11 +00007495 GetBuiltinTypeError &Error,
Jay Foad4ba2a172011-01-12 09:06:06 +00007496 unsigned *IntegerConstantArgs) const {
Chris Lattner33daae62010-10-01 22:42:38 +00007497 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump1eb44332009-09-09 15:08:12 +00007498
Chris Lattner5f9e2722011-07-23 10:55:15 +00007499 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00007500
Chris Lattner14e0e742010-10-01 22:53:11 +00007501 bool RequiresICE = false;
Chris Lattner86df27b2009-06-14 00:45:47 +00007502 Error = GE_None;
Chris Lattner14e0e742010-10-01 22:53:11 +00007503 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7504 RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00007505 if (Error != GE_None)
7506 return QualType();
Chris Lattner14e0e742010-10-01 22:53:11 +00007507
7508 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7509
Chris Lattner86df27b2009-06-14 00:45:47 +00007510 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattner14e0e742010-10-01 22:53:11 +00007511 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00007512 if (Error != GE_None)
7513 return QualType();
7514
Chris Lattner14e0e742010-10-01 22:53:11 +00007515 // If this argument is required to be an IntegerConstantExpression and the
7516 // caller cares, fill in the bitmask we return.
7517 if (RequiresICE && IntegerConstantArgs)
7518 *IntegerConstantArgs |= 1 << ArgTypes.size();
7519
Chris Lattner86df27b2009-06-14 00:45:47 +00007520 // Do array -> pointer decay. The builtin should use the decayed type.
7521 if (Ty->isArrayType())
7522 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00007523
Chris Lattner86df27b2009-06-14 00:45:47 +00007524 ArgTypes.push_back(Ty);
7525 }
7526
7527 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7528 "'.' should only occur at end of builtin type list!");
7529
John McCall00ccbef2010-12-21 00:44:39 +00007530 FunctionType::ExtInfo EI;
7531 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7532
7533 bool Variadic = (TypeStr[0] == '.');
7534
7535 // We really shouldn't be making a no-proto type here, especially in C++.
7536 if (ArgTypes.empty() && Variadic)
7537 return getFunctionNoProtoType(ResType, EI);
Douglas Gregorce056bc2010-02-21 22:15:06 +00007538
John McCalle23cf432010-12-14 08:05:40 +00007539 FunctionProtoType::ExtProtoInfo EPI;
John McCall00ccbef2010-12-21 00:44:39 +00007540 EPI.ExtInfo = EI;
7541 EPI.Variadic = Variadic;
John McCalle23cf432010-12-14 08:05:40 +00007542
7543 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattner86df27b2009-06-14 00:45:47 +00007544}
Eli Friedmana95d7572009-08-19 07:44:53 +00007545
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007546GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
7547 GVALinkage External = GVA_StrongExternal;
7548
7549 Linkage L = FD->getLinkage();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007550 switch (L) {
7551 case NoLinkage:
7552 case InternalLinkage:
7553 case UniqueExternalLinkage:
7554 return GVA_Internal;
7555
7556 case ExternalLinkage:
7557 switch (FD->getTemplateSpecializationKind()) {
7558 case TSK_Undeclared:
7559 case TSK_ExplicitSpecialization:
7560 External = GVA_StrongExternal;
7561 break;
7562
7563 case TSK_ExplicitInstantiationDefinition:
7564 return GVA_ExplicitTemplateInstantiation;
7565
7566 case TSK_ExplicitInstantiationDeclaration:
7567 case TSK_ImplicitInstantiation:
7568 External = GVA_TemplateInstantiation;
7569 break;
7570 }
7571 }
7572
7573 if (!FD->isInlined())
7574 return External;
7575
David Blaikie4e4d0842012-03-11 07:00:24 +00007576 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007577 // GNU or C99 inline semantics. Determine whether this symbol should be
7578 // externally visible.
7579 if (FD->isInlineDefinitionExternallyVisible())
7580 return External;
7581
7582 // C99 inline semantics, where the symbol is not externally visible.
7583 return GVA_C99Inline;
7584 }
7585
7586 // C++0x [temp.explicit]p9:
7587 // [ Note: The intent is that an inline function that is the subject of
7588 // an explicit instantiation declaration will still be implicitly
7589 // instantiated when used so that the body can be considered for
7590 // inlining, but that no out-of-line copy of the inline function would be
7591 // generated in the translation unit. -- end note ]
7592 if (FD->getTemplateSpecializationKind()
7593 == TSK_ExplicitInstantiationDeclaration)
7594 return GVA_C99Inline;
7595
7596 return GVA_CXXInline;
7597}
7598
7599GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
7600 // If this is a static data member, compute the kind of template
7601 // specialization. Otherwise, this variable is not part of a
7602 // template.
7603 TemplateSpecializationKind TSK = TSK_Undeclared;
7604 if (VD->isStaticDataMember())
7605 TSK = VD->getTemplateSpecializationKind();
7606
7607 Linkage L = VD->getLinkage();
Rafael Espindola62a833e2013-01-02 04:19:07 +00007608 assert (!(L == ExternalLinkage && getLangOpts().CPlusPlus &&
7609 VD->getType()->getLinkage() == UniqueExternalLinkage));
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007610
7611 switch (L) {
7612 case NoLinkage:
7613 case InternalLinkage:
7614 case UniqueExternalLinkage:
7615 return GVA_Internal;
7616
7617 case ExternalLinkage:
7618 switch (TSK) {
7619 case TSK_Undeclared:
7620 case TSK_ExplicitSpecialization:
7621 return GVA_StrongExternal;
7622
7623 case TSK_ExplicitInstantiationDeclaration:
7624 llvm_unreachable("Variable should not be instantiated");
7625 // Fall through to treat this like any other instantiation.
7626
7627 case TSK_ExplicitInstantiationDefinition:
7628 return GVA_ExplicitTemplateInstantiation;
7629
7630 case TSK_ImplicitInstantiation:
7631 return GVA_TemplateInstantiation;
7632 }
7633 }
7634
David Blaikie7530c032012-01-17 06:56:22 +00007635 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007636}
7637
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +00007638bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007639 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7640 if (!VD->isFileVarDecl())
7641 return false;
Argyrios Kyrtzidis144b38a2011-09-13 21:35:00 +00007642 } else if (!isa<FunctionDecl>(D))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007643 return false;
7644
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00007645 // Weak references don't produce any output by themselves.
7646 if (D->hasAttr<WeakRefAttr>())
7647 return false;
7648
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007649 // Aliases and used decls are required.
7650 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7651 return true;
7652
7653 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7654 // Forward declarations aren't required.
Sean Hunt10620eb2011-05-06 20:44:56 +00007655 if (!FD->doesThisDeclarationHaveABody())
Nick Lewyckydce67a72011-07-18 05:26:13 +00007656 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007657
7658 // Constructors and destructors are required.
7659 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7660 return true;
7661
John McCalld5617ee2013-01-25 22:31:03 +00007662 // The key function for a class is required. This rule only comes
7663 // into play when inline functions can be key functions, though.
7664 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7665 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7666 const CXXRecordDecl *RD = MD->getParent();
7667 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7668 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
7669 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7670 return true;
7671 }
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007672 }
7673 }
7674
7675 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7676
7677 // static, static inline, always_inline, and extern inline functions can
7678 // always be deferred. Normal inline functions can be deferred in C99/C++.
7679 // Implicit template instantiations can also be deferred in C++.
7680 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev3a5aca82012-02-02 06:06:34 +00007681 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007682 return false;
7683 return true;
7684 }
Douglas Gregor94da1582011-09-10 00:22:34 +00007685
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007686 const VarDecl *VD = cast<VarDecl>(D);
7687 assert(VD->isFileVarDecl() && "Expected file scoped var");
7688
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00007689 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7690 return false;
7691
Richard Smith5f9a7e32012-11-12 21:38:00 +00007692 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007693 GVALinkage L = GetGVALinkageForVariable(VD);
Richard Smith5f9a7e32012-11-12 21:38:00 +00007694 if (L != GVA_Internal && L != GVA_TemplateInstantiation)
7695 return true;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007696
Richard Smith5f9a7e32012-11-12 21:38:00 +00007697 // Variables that have destruction with side-effects are required.
7698 if (VD->getType().isDestructedType())
7699 return true;
7700
7701 // Variables that have initialization with side-effects are required.
7702 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
7703 return true;
7704
7705 return false;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007706}
Charles Davis071cc7d2010-08-16 03:33:14 +00007707
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007708CallingConv ASTContext::getDefaultCXXMethodCallConv(bool isVariadic) {
Charles Davisee743f92010-11-09 18:04:24 +00007709 // Pass through to the C++ ABI object
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007710 return ABI->getDefaultMethodCallConv(isVariadic);
7711}
7712
7713CallingConv ASTContext::getCanonicalCallConv(CallingConv CC) const {
John McCallb8b2c9d2013-01-25 22:30:49 +00007714 if (CC == CC_C && !LangOpts.MRTD &&
7715 getTargetInfo().getCXXABI().isMemberFunctionCCDefault())
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007716 return CC_Default;
7717 return CC;
Charles Davisee743f92010-11-09 18:04:24 +00007718}
7719
Jay Foad4ba2a172011-01-12 09:06:06 +00007720bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlssondae0cb52010-11-25 01:51:53 +00007721 // Pass through to the C++ ABI object
7722 return ABI->isNearlyEmpty(RD);
7723}
7724
Peter Collingbourne14110472011-01-13 18:57:25 +00007725MangleContext *ASTContext::createMangleContext() {
John McCallb8b2c9d2013-01-25 22:30:49 +00007726 switch (Target->getCXXABI().getKind()) {
Tim Northoverc264e162013-01-31 12:13:10 +00007727 case TargetCXXABI::GenericAArch64:
John McCallb8b2c9d2013-01-25 22:30:49 +00007728 case TargetCXXABI::GenericItanium:
7729 case TargetCXXABI::GenericARM:
7730 case TargetCXXABI::iOS:
Peter Collingbourne14110472011-01-13 18:57:25 +00007731 return createItaniumMangleContext(*this, getDiagnostics());
John McCallb8b2c9d2013-01-25 22:30:49 +00007732 case TargetCXXABI::Microsoft:
Peter Collingbourne14110472011-01-13 18:57:25 +00007733 return createMicrosoftMangleContext(*this, getDiagnostics());
7734 }
David Blaikieb219cfc2011-09-23 05:06:16 +00007735 llvm_unreachable("Unsupported ABI");
Peter Collingbourne14110472011-01-13 18:57:25 +00007736}
7737
Charles Davis071cc7d2010-08-16 03:33:14 +00007738CXXABI::~CXXABI() {}
Ted Kremenekba29bd22011-04-28 04:53:38 +00007739
7740size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek0c8cd1a2011-07-27 18:41:12 +00007741 return ASTRecordLayouts.getMemorySize()
7742 + llvm::capacity_in_bytes(ObjCLayouts)
7743 + llvm::capacity_in_bytes(KeyFunctions)
7744 + llvm::capacity_in_bytes(ObjCImpls)
7745 + llvm::capacity_in_bytes(BlockVarCopyInits)
7746 + llvm::capacity_in_bytes(DeclAttrs)
7747 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
7748 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
7749 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
7750 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
7751 + llvm::capacity_in_bytes(OverriddenMethods)
7752 + llvm::capacity_in_bytes(Types)
Francois Pichetaf0f4d02011-08-14 03:52:19 +00007753 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet0d95f0d2011-08-14 14:28:49 +00007754 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekba29bd22011-04-28 04:53:38 +00007755}
Ted Kremenekd211cb72011-10-06 05:00:56 +00007756
David Blaikie66cff722012-11-14 01:52:05 +00007757void ASTContext::addUnnamedTag(const TagDecl *Tag) {
7758 // FIXME: This mangling should be applied to function local classes too
7759 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl() ||
7760 !isa<CXXRecordDecl>(Tag->getParent()) || Tag->getLinkage() != ExternalLinkage)
7761 return;
7762
7763 std::pair<llvm::DenseMap<const DeclContext *, unsigned>::iterator, bool> P =
7764 UnnamedMangleContexts.insert(std::make_pair(Tag->getParent(), 0));
7765 UnnamedMangleNumbers.insert(std::make_pair(Tag, P.first->second++));
7766}
7767
7768int ASTContext::getUnnamedTagManglingNumber(const TagDecl *Tag) const {
7769 llvm::DenseMap<const TagDecl *, unsigned>::const_iterator I =
7770 UnnamedMangleNumbers.find(Tag);
7771 return I != UnnamedMangleNumbers.end() ? I->second : -1;
7772}
7773
Douglas Gregor9e8c92a2012-02-20 19:44:39 +00007774unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
7775 CXXRecordDecl *Lambda = CallOperator->getParent();
7776 return LambdaMangleContexts[Lambda->getDeclContext()]
7777 .getManglingNumber(CallOperator);
7778}
7779
7780
Ted Kremenekd211cb72011-10-06 05:00:56 +00007781void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
7782 ParamIndices[D] = index;
7783}
7784
7785unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
7786 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
7787 assert(I != ParamIndices.end() &&
7788 "ParmIndices lacks entry set by ParmVarDecl");
7789 return I->second;
7790}