blob: 170cc0298b3a716c368ce418d5516c54b87fb120 [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.
Dmitri Gribenko6fd7d302013-04-10 15:35:17 +0000144 RawComment CommentAtDeclLoc(
145 SourceMgr, SourceRange(DeclLoc), false,
146 LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenkoa444f182012-07-17 22:01:09 +0000147 BeforeThanCompare<RawComment> Compare(SourceMgr);
148 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
149 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
150 if (!Found && RawComments.size() >= 2) {
151 MaybeBeforeDecl--;
152 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
153 }
154
155 if (Found) {
156 Comment = MaybeBeforeDecl + 1;
157 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
158 &CommentAtDeclLoc, Compare));
159 } else {
160 // Slow path.
161 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
162 &CommentAtDeclLoc, Compare);
163 }
164 }
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000165
166 // Decompose the location for the declaration and find the beginning of the
167 // file buffer.
168 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
169
170 // First check whether we have a trailing comment.
171 if (Comment != RawComments.end() &&
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000172 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
Dmitri Gribenko9c006762012-07-06 23:27:33 +0000173 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D))) {
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000174 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000175 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000176 // Check that Doxygen trailing comment comes after the declaration, starts
177 // on the same line and in the same file as the declaration.
178 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
179 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
180 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
181 CommentBeginDecomp.second)) {
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000182 return *Comment;
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000183 }
184 }
185
186 // The comment just after the declaration was not a trailing comment.
187 // Let's look at the previous comment.
188 if (Comment == RawComments.begin())
189 return NULL;
190 --Comment;
191
192 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000193 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000194 return NULL;
195
196 // Decompose the end of the comment.
197 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000198 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000199
200 // If the comment and the declaration aren't in the same file, then they
201 // aren't related.
202 if (DeclLocDecomp.first != CommentEndDecomp.first)
203 return NULL;
204
205 // Get the corresponding buffer.
206 bool Invalid = false;
207 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
208 &Invalid).data();
209 if (Invalid)
210 return NULL;
211
212 // Extract text between the comment and declaration.
213 StringRef Text(Buffer + CommentEndDecomp.second,
214 DeclLocDecomp.second - CommentEndDecomp.second);
215
Dmitri Gribenko8bdb58a2012-06-27 23:43:37 +0000216 // There should be no other declarations or preprocessor directives between
217 // comment and declaration.
Dmitri Gribenkoabd56c82012-07-13 01:06:46 +0000218 if (Text.find_first_of(",;{}#@") != StringRef::npos)
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000219 return NULL;
220
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000221 return *Comment;
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000222}
223
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000224namespace {
225/// If we have a 'templated' declaration for a template, adjust 'D' to
226/// refer to the actual template.
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000227/// If we have an implicit instantiation, adjust 'D' to refer to template.
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000228const Decl *adjustDeclToTemplate(const Decl *D) {
Douglas Gregorcd81df22012-08-13 16:37:30 +0000229 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000230 // Is this function declaration part of a function template?
Douglas Gregorcd81df22012-08-13 16:37:30 +0000231 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000232 return FTD;
233
234 // Nothing to do if function is not an implicit instantiation.
235 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
236 return D;
237
238 // Function is an implicit instantiation of a function template?
239 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
240 return FTD;
241
242 // Function is instantiated from a member definition of a class template?
243 if (const FunctionDecl *MemberDecl =
244 FD->getInstantiatedFromMemberFunction())
245 return MemberDecl;
246
247 return D;
Douglas Gregorcd81df22012-08-13 16:37:30 +0000248 }
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000249 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
250 // Static data member is instantiated from a member definition of a class
251 // template?
252 if (VD->isStaticDataMember())
253 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
254 return MemberDecl;
255
256 return D;
257 }
258 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
259 // Is this class declaration part of a class template?
260 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
261 return CTD;
262
263 // Class is an implicit instantiation of a class template or partial
264 // specialization?
265 if (const ClassTemplateSpecializationDecl *CTSD =
266 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
267 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
268 return D;
269 llvm::PointerUnion<ClassTemplateDecl *,
270 ClassTemplatePartialSpecializationDecl *>
271 PU = CTSD->getSpecializedTemplateOrPartial();
272 return PU.is<ClassTemplateDecl*>() ?
273 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
274 static_cast<const Decl*>(
275 PU.get<ClassTemplatePartialSpecializationDecl *>());
276 }
277
278 // Class is instantiated from a member definition of a class template?
279 if (const MemberSpecializationInfo *Info =
280 CRD->getMemberSpecializationInfo())
281 return Info->getInstantiatedFrom();
282
283 return D;
284 }
285 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
286 // Enum is instantiated from a member definition of a class template?
287 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
288 return MemberDecl;
289
290 return D;
291 }
292 // FIXME: Adjust alias templates?
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000293 return D;
294}
295} // unnamed namespace
296
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000297const RawComment *ASTContext::getRawCommentForAnyRedecl(
298 const Decl *D,
299 const Decl **OriginalDecl) const {
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000300 D = adjustDeclToTemplate(D);
Douglas Gregorcd81df22012-08-13 16:37:30 +0000301
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000302 // Check whether we have cached a comment for this declaration already.
303 {
304 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
305 RedeclComments.find(D);
306 if (Pos != RedeclComments.end()) {
307 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000308 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
309 if (OriginalDecl)
310 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000311 return Raw.getRaw();
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000312 }
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000313 }
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000314 }
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000315
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000316 // Search for comments attached to declarations in the redeclaration chain.
317 const RawComment *RC = NULL;
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000318 const Decl *OriginalDeclForRC = NULL;
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000319 for (Decl::redecl_iterator I = D->redecls_begin(),
320 E = D->redecls_end();
321 I != E; ++I) {
322 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
323 RedeclComments.find(*I);
324 if (Pos != RedeclComments.end()) {
325 const RawCommentAndCacheFlags &Raw = Pos->second;
326 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
327 RC = Raw.getRaw();
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000328 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000329 break;
330 }
331 } else {
332 RC = getRawCommentForDeclNoCache(*I);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000333 OriginalDeclForRC = *I;
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000334 RawCommentAndCacheFlags Raw;
335 if (RC) {
336 Raw.setRaw(RC);
337 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
338 } else
339 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000340 Raw.setOriginalDecl(*I);
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000341 RedeclComments[*I] = Raw;
342 if (RC)
343 break;
344 }
345 }
346
Dmitri Gribenko8376f592012-06-28 16:25:36 +0000347 // If we found a comment, it should be a documentation comment.
348 assert(!RC || RC->isDocumentation());
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000349
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000350 if (OriginalDecl)
351 *OriginalDecl = OriginalDeclForRC;
352
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000353 // Update cache for every declaration in the redeclaration chain.
354 RawCommentAndCacheFlags Raw;
355 Raw.setRaw(RC);
356 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000357 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000358
359 for (Decl::redecl_iterator I = D->redecls_begin(),
360 E = D->redecls_end();
361 I != E; ++I) {
362 RawCommentAndCacheFlags &R = RedeclComments[*I];
363 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
364 R = Raw;
365 }
366
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000367 return RC;
368}
369
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000370static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
371 SmallVectorImpl<const NamedDecl *> &Redeclared) {
372 const DeclContext *DC = ObjCMethod->getDeclContext();
373 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
374 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
375 if (!ID)
376 return;
377 // Add redeclared method here.
Douglas Gregord3297242013-01-16 23:00:23 +0000378 for (ObjCInterfaceDecl::known_extensions_iterator
379 Ext = ID->known_extensions_begin(),
380 ExtEnd = ID->known_extensions_end();
381 Ext != ExtEnd; ++Ext) {
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000382 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregord3297242013-01-16 23:00:23 +0000383 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000384 ObjCMethod->isInstanceMethod()))
385 Redeclared.push_back(RedeclaredMethod);
386 }
387 }
388}
389
Fariborz Jahanian749ace62012-10-11 23:52:50 +0000390comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
391 const Decl *D) const {
392 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
393 ThisDeclInfo->CommentDecl = D;
394 ThisDeclInfo->IsFilled = false;
395 ThisDeclInfo->fill();
396 ThisDeclInfo->CommentDecl = FC->getDecl();
397 comments::FullComment *CFC =
398 new (*this) comments::FullComment(FC->getBlocks(),
399 ThisDeclInfo);
400 return CFC;
401
402}
403
Dmitri Gribenko19523542012-09-29 11:40:46 +0000404comments::FullComment *ASTContext::getCommentForDecl(
405 const Decl *D,
406 const Preprocessor *PP) const {
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000407 D = adjustDeclToTemplate(D);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000408
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000409 const Decl *Canonical = D->getCanonicalDecl();
410 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
411 ParsedComments.find(Canonical);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000412
413 if (Pos != ParsedComments.end()) {
Fariborz Jahanian749ace62012-10-11 23:52:50 +0000414 if (Canonical != D) {
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000415 comments::FullComment *FC = Pos->second;
Fariborz Jahanian749ace62012-10-11 23:52:50 +0000416 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000417 return CFC;
418 }
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000419 return Pos->second;
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000420 }
421
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000422 const Decl *OriginalDecl;
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000423
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000424 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000425 if (!RC) {
426 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko1e905da2012-11-03 14:24:57 +0000427 SmallVector<const NamedDecl*, 8> Overridden;
Fariborz Jahanianc328d9c2013-01-12 00:28:34 +0000428 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian23799e32013-01-25 23:08:39 +0000429 if (OMD && OMD->isPropertyAccessor())
430 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
431 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
432 return cloneFullComment(FC, D);
Fariborz Jahanianc328d9c2013-01-12 00:28:34 +0000433 if (OMD)
Dmitri Gribenko1e905da2012-11-03 14:24:57 +0000434 addRedeclaredMethods(OMD, Overridden);
435 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian23799e32013-01-25 23:08:39 +0000436 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
437 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
438 return cloneFullComment(FC, D);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000439 }
Fariborz Jahanian41170b52013-01-25 22:48:32 +0000440 else if (const TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Dmitri Gribenkod1e5c0d2013-01-27 21:18:39 +0000441 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian23799e32013-01-25 23:08:39 +0000442 // does not have one of its own.
Fariborz Jahanian41170b52013-01-25 22:48:32 +0000443 QualType QT = TD->getUnderlyingType();
Dmitri Gribenkod1e5c0d2013-01-27 21:18:39 +0000444 if (const TagType *TT = QT->getAs<TagType>())
445 if (const Decl *TD = TT->getDecl())
446 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian23799e32013-01-25 23:08:39 +0000447 return cloneFullComment(FC, D);
Fariborz Jahanian41170b52013-01-25 22:48:32 +0000448 }
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000449 return NULL;
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000450 }
451
Dmitri Gribenko4b41c652012-08-22 18:12:19 +0000452 // If the RawComment was attached to other redeclaration of this Decl, we
453 // should parse the comment in context of that other Decl. This is important
454 // because comments can contain references to parameter names which can be
455 // different across redeclarations.
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000456 if (D != OriginalDecl)
Dmitri Gribenko19523542012-09-29 11:40:46 +0000457 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000458
Dmitri Gribenko19523542012-09-29 11:40:46 +0000459 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000460 ParsedComments[Canonical] = FC;
461 return FC;
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000462}
463
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000464void
465ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
466 TemplateTemplateParmDecl *Parm) {
467 ID.AddInteger(Parm->getDepth());
468 ID.AddInteger(Parm->getPosition());
Douglas Gregor61c4d282011-01-05 15:48:55 +0000469 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000470
471 TemplateParameterList *Params = Parm->getTemplateParameters();
472 ID.AddInteger(Params->size());
473 for (TemplateParameterList::const_iterator P = Params->begin(),
474 PEnd = Params->end();
475 P != PEnd; ++P) {
476 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
477 ID.AddInteger(0);
478 ID.AddBoolean(TTP->isParameterPack());
479 continue;
480 }
481
482 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
483 ID.AddInteger(1);
Douglas Gregor61c4d282011-01-05 15:48:55 +0000484 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman9e9c4542012-03-07 01:09:33 +0000485 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000486 if (NTTP->isExpandedParameterPack()) {
487 ID.AddBoolean(true);
488 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman9e9c4542012-03-07 01:09:33 +0000489 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
490 QualType T = NTTP->getExpansionType(I);
491 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
492 }
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000493 } else
494 ID.AddBoolean(false);
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000495 continue;
496 }
497
498 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
499 ID.AddInteger(2);
500 Profile(ID, TTP);
501 }
502}
503
504TemplateTemplateParmDecl *
505ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad4ba2a172011-01-12 09:06:06 +0000506 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000507 // Check if we already have a canonical template template parameter.
508 llvm::FoldingSetNodeID ID;
509 CanonicalTemplateTemplateParm::Profile(ID, TTP);
510 void *InsertPos = 0;
511 CanonicalTemplateTemplateParm *Canonical
512 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
513 if (Canonical)
514 return Canonical->getParam();
515
516 // Build a canonical template parameter list.
517 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000518 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000519 CanonParams.reserve(Params->size());
520 for (TemplateParameterList::const_iterator P = Params->begin(),
521 PEnd = Params->end();
522 P != PEnd; ++P) {
523 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
524 CanonParams.push_back(
525 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnara344577e2011-03-06 15:48:19 +0000526 SourceLocation(),
527 SourceLocation(),
528 TTP->getDepth(),
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000529 TTP->getIndex(), 0, false,
530 TTP->isParameterPack()));
531 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000532 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
533 QualType T = getCanonicalType(NTTP->getType());
534 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
535 NonTypeTemplateParmDecl *Param;
536 if (NTTP->isExpandedParameterPack()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000537 SmallVector<QualType, 2> ExpandedTypes;
538 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000539 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
540 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
541 ExpandedTInfos.push_back(
542 getTrivialTypeSourceInfo(ExpandedTypes.back()));
543 }
544
545 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000546 SourceLocation(),
547 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000548 NTTP->getDepth(),
549 NTTP->getPosition(), 0,
550 T,
551 TInfo,
552 ExpandedTypes.data(),
553 ExpandedTypes.size(),
554 ExpandedTInfos.data());
555 } else {
556 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000557 SourceLocation(),
558 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000559 NTTP->getDepth(),
560 NTTP->getPosition(), 0,
561 T,
562 NTTP->isParameterPack(),
563 TInfo);
564 }
565 CanonParams.push_back(Param);
566
567 } else
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000568 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
569 cast<TemplateTemplateParmDecl>(*P)));
570 }
571
572 TemplateTemplateParmDecl *CanonTTP
573 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
574 SourceLocation(), TTP->getDepth(),
Douglas Gregor61c4d282011-01-05 15:48:55 +0000575 TTP->getPosition(),
576 TTP->isParameterPack(),
577 0,
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000578 TemplateParameterList::Create(*this, SourceLocation(),
579 SourceLocation(),
580 CanonParams.data(),
581 CanonParams.size(),
582 SourceLocation()));
583
584 // Get the new insert position for the node we care about.
585 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
586 assert(Canonical == 0 && "Shouldn't be in the map!");
587 (void)Canonical;
588
589 // Create the canonical template template parameter entry.
590 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
591 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
592 return CanonTTP;
593}
594
Charles Davis071cc7d2010-08-16 03:33:14 +0000595CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCallee79a4c2010-08-21 22:46:04 +0000596 if (!LangOpts.CPlusPlus) return 0;
597
John McCallb8b2c9d2013-01-25 22:30:49 +0000598 switch (T.getCXXABI().getKind()) {
599 case TargetCXXABI::GenericARM:
600 case TargetCXXABI::iOS:
John McCallee79a4c2010-08-21 22:46:04 +0000601 return CreateARMCXXABI(*this);
Tim Northoverc264e162013-01-31 12:13:10 +0000602 case TargetCXXABI::GenericAArch64: // Same as Itanium at this level
John McCallb8b2c9d2013-01-25 22:30:49 +0000603 case TargetCXXABI::GenericItanium:
Charles Davis071cc7d2010-08-16 03:33:14 +0000604 return CreateItaniumCXXABI(*this);
John McCallb8b2c9d2013-01-25 22:30:49 +0000605 case TargetCXXABI::Microsoft:
Charles Davis20cf7172010-08-19 02:18:14 +0000606 return CreateMicrosoftCXXABI(*this);
607 }
David Blaikie7530c032012-01-17 06:56:22 +0000608 llvm_unreachable("Invalid CXXABI type!");
Charles Davis071cc7d2010-08-16 03:33:14 +0000609}
610
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000611static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000612 const LangOptions &LOpts) {
613 if (LOpts.FakeAddressSpaceMap) {
614 // The fake address space map must have a distinct entry for each
615 // language-specific address space.
616 static const unsigned FakeAddrSpaceMap[] = {
617 1, // opencl_global
618 2, // opencl_local
Peter Collingbourne4dc34eb2012-05-20 21:08:35 +0000619 3, // opencl_constant
620 4, // cuda_device
621 5, // cuda_constant
622 6 // cuda_shared
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000623 };
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000624 return &FakeAddrSpaceMap;
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000625 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000626 return &T.getAddressSpaceMap();
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000627 }
628}
629
Douglas Gregor3e3cd932011-09-01 20:23:19 +0000630ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000631 const TargetInfo *t,
Daniel Dunbare91593e2008-08-11 04:54:23 +0000632 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000633 Builtin::Context &builtins,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000634 unsigned size_reserve,
635 bool DelayInitialization)
636 : FunctionProtoTypes(this_()),
637 TemplateSpecializationTypes(this_()),
638 DependentTemplateSpecializationTypes(this_()),
639 SubstTemplateTemplateParmPacks(this_()),
640 GlobalNestedNameSpecifier(0),
641 Int128Decl(0), UInt128Decl(0),
Meador Ingec5613b22012-06-16 03:34:49 +0000642 BuiltinVaListDecl(0),
Douglas Gregora6ea10e2012-01-17 18:09:05 +0000643 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Fariborz Jahanian96171302012-08-30 18:49:41 +0000644 BOOLDecl(0),
Douglas Gregore97179c2011-09-08 01:46:34 +0000645 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000646 FILEDecl(0),
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +0000647 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
648 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
649 cudaConfigureCallDecl(0),
Douglas Gregore6649772011-12-03 00:30:27 +0000650 NullTypeSourceInfo(QualType()),
651 FirstLocalImport(), LastLocalImport(),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000652 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregor30c42402011-09-27 22:38:19 +0000653 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000654 Idents(idents), Selectors(sels),
655 BuiltinInfo(builtins),
656 DeclarationNames(*this),
Douglas Gregor30c42402011-09-27 22:38:19 +0000657 ExternalSource(0), Listener(0),
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000658 Comments(SM), CommentsLoaded(false),
Dmitri Gribenko6ebf0912013-02-22 14:21:27 +0000659 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000660 LastSDM(0, 0),
Fariborz Jahanianf7992132013-01-04 18:45:40 +0000661 UniqueBlockByRefTypeID(0)
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000662{
Mike Stump1eb44332009-09-09 15:08:12 +0000663 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +0000664 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000665
666 if (!DelayInitialization) {
667 assert(t && "No target supplied for ASTContext initialization");
668 InitBuiltinTypes(*t);
669 }
Daniel Dunbare91593e2008-08-11 04:54:23 +0000670}
671
Reid Spencer5f016e22007-07-11 17:01:13 +0000672ASTContext::~ASTContext() {
Ted Kremenek3478eb62010-02-11 07:12:28 +0000673 // Release the DenseMaps associated with DeclContext objects.
674 // FIXME: Is this the ideal solution?
675 ReleaseDeclContextMaps();
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000676
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000677 // Call all of the deallocation functions.
678 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
679 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor00545312010-05-23 18:26:36 +0000680
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000681 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000682 // because they can contain DenseMaps.
683 for (llvm::DenseMap<const ObjCContainerDecl*,
684 const ASTRecordLayout*>::iterator
685 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
686 // Increment in loop to prevent using deallocated memory.
687 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
688 R->Destroy(*this);
689
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000690 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
691 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
692 // Increment in loop to prevent using deallocated memory.
693 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
694 R->Destroy(*this);
695 }
Douglas Gregor63200642010-08-30 16:49:28 +0000696
697 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
698 AEnd = DeclAttrs.end();
699 A != AEnd; ++A)
700 A->second->~AttrVec();
701}
Douglas Gregorab452ba2009-03-26 23:50:42 +0000702
Douglas Gregor00545312010-05-23 18:26:36 +0000703void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
704 Deallocations.push_back(std::make_pair(Callback, Data));
705}
706
Mike Stump1eb44332009-09-09 15:08:12 +0000707void
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000708ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregor2cf26342009-04-09 22:27:44 +0000709 ExternalSource.reset(Source.take());
710}
711
Reid Spencer5f016e22007-07-11 17:01:13 +0000712void ASTContext::PrintStats() const {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000713 llvm::errs() << "\n*** AST Context Stats:\n";
714 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000715
Douglas Gregordbe833d2009-05-26 14:40:08 +0000716 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000717#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000718#define ABSTRACT_TYPE(Name, Parent)
719#include "clang/AST/TypeNodes.def"
720 0 // Extra
721 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000722
Reid Spencer5f016e22007-07-11 17:01:13 +0000723 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
724 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000725 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000726 }
727
Douglas Gregordbe833d2009-05-26 14:40:08 +0000728 unsigned Idx = 0;
729 unsigned TotalBytes = 0;
730#define TYPE(Name, Parent) \
731 if (counts[Idx]) \
Chandler Carruthcd92a652011-07-04 05:32:14 +0000732 llvm::errs() << " " << counts[Idx] << " " << #Name \
733 << " types\n"; \
Douglas Gregordbe833d2009-05-26 14:40:08 +0000734 TotalBytes += counts[Idx] * sizeof(Name##Type); \
735 ++Idx;
736#define ABSTRACT_TYPE(Name, Parent)
737#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000738
Chandler Carruthcd92a652011-07-04 05:32:14 +0000739 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
740
Douglas Gregor4923aa22010-07-02 20:37:36 +0000741 // Implicit special member functions.
Chandler Carruthcd92a652011-07-04 05:32:14 +0000742 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
743 << NumImplicitDefaultConstructors
744 << " implicit default constructors created\n";
745 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
746 << NumImplicitCopyConstructors
747 << " implicit copy constructors created\n";
David Blaikie4e4d0842012-03-11 07:00:24 +0000748 if (getLangOpts().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000749 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
750 << NumImplicitMoveConstructors
751 << " implicit move constructors created\n";
752 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
753 << NumImplicitCopyAssignmentOperators
754 << " implicit copy assignment operators created\n";
David Blaikie4e4d0842012-03-11 07:00:24 +0000755 if (getLangOpts().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000756 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
757 << NumImplicitMoveAssignmentOperators
758 << " implicit move assignment operators created\n";
759 llvm::errs() << NumImplicitDestructorsDeclared << "/"
760 << NumImplicitDestructors
761 << " implicit destructors created\n";
762
Douglas Gregor2cf26342009-04-09 22:27:44 +0000763 if (ExternalSource.get()) {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000764 llvm::errs() << "\n";
Douglas Gregor2cf26342009-04-09 22:27:44 +0000765 ExternalSource->PrintStats();
766 }
Chandler Carruthcd92a652011-07-04 05:32:14 +0000767
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000768 BumpAlloc.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000769}
770
Douglas Gregor772eeae2011-08-12 06:49:56 +0000771TypedefDecl *ASTContext::getInt128Decl() const {
772 if (!Int128Decl) {
773 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
774 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
775 getTranslationUnitDecl(),
776 SourceLocation(),
777 SourceLocation(),
778 &Idents.get("__int128_t"),
779 TInfo);
780 }
781
782 return Int128Decl;
783}
784
785TypedefDecl *ASTContext::getUInt128Decl() const {
786 if (!UInt128Decl) {
787 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
788 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
789 getTranslationUnitDecl(),
790 SourceLocation(),
791 SourceLocation(),
792 &Idents.get("__uint128_t"),
793 TInfo);
794 }
795
796 return UInt128Decl;
797}
Reid Spencer5f016e22007-07-11 17:01:13 +0000798
John McCalle27ec8a2009-10-23 23:03:21 +0000799void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000800 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000801 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000802 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000803}
804
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000805void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
806 assert((!this->Target || this->Target == &Target) &&
807 "Incorrect target reinitialization");
Reid Spencer5f016e22007-07-11 17:01:13 +0000808 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000809
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000810 this->Target = &Target;
811
812 ABI.reset(createCXXABI(Target));
813 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
814
Reid Spencer5f016e22007-07-11 17:01:13 +0000815 // C99 6.2.5p19.
816 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000817
Reid Spencer5f016e22007-07-11 17:01:13 +0000818 // C99 6.2.5p2.
819 InitBuiltinType(BoolTy, BuiltinType::Bool);
820 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000821 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000822 InitBuiltinType(CharTy, BuiltinType::Char_S);
823 else
824 InitBuiltinType(CharTy, BuiltinType::Char_U);
825 // C99 6.2.5p4.
826 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
827 InitBuiltinType(ShortTy, BuiltinType::Short);
828 InitBuiltinType(IntTy, BuiltinType::Int);
829 InitBuiltinType(LongTy, BuiltinType::Long);
830 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000831
Reid Spencer5f016e22007-07-11 17:01:13 +0000832 // C99 6.2.5p6.
833 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
834 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
835 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
836 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
837 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000838
Reid Spencer5f016e22007-07-11 17:01:13 +0000839 // C99 6.2.5p10.
840 InitBuiltinType(FloatTy, BuiltinType::Float);
841 InitBuiltinType(DoubleTy, BuiltinType::Double);
842 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000843
Chris Lattner2df9ced2009-04-30 02:43:43 +0000844 // GNU extension, 128-bit integers.
845 InitBuiltinType(Int128Ty, BuiltinType::Int128);
846 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
847
Abramo Bagnarae75bb612012-09-09 10:13:32 +0000848 if (LangOpts.CPlusPlus && LangOpts.WChar) { // C++ 3.9.1p5
Eli Friedmand3d77cd2011-04-30 19:24:24 +0000849 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattner3f59c972010-12-25 23:25:43 +0000850 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
851 else // -fshort-wchar makes wchar_t be unsigned.
852 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
Abramo Bagnarae75bb612012-09-09 10:13:32 +0000853 } else // C99 (or C++ using -fno-wchar)
Chris Lattner3a250322009-02-26 23:43:47 +0000854 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000855
James Molloy392da482012-05-04 10:55:22 +0000856 WIntTy = getFromTargetType(Target.getWIntType());
857
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000858 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
859 InitBuiltinType(Char16Ty, BuiltinType::Char16);
860 else // C99
861 Char16Ty = getFromTargetType(Target.getChar16Type());
862
863 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
864 InitBuiltinType(Char32Ty, BuiltinType::Char32);
865 else // C99
866 Char32Ty = getFromTargetType(Target.getChar32Type());
867
Douglas Gregor898574e2008-12-05 23:32:09 +0000868 // Placeholder type for type-dependent expressions whose type is
869 // completely unknown. No code should ever check a type against
870 // DependentTy and users should never see it; however, it is here to
871 // help diagnose failures to properly check for type-dependent
872 // expressions.
873 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000874
John McCall2a984ca2010-10-12 00:20:44 +0000875 // Placeholder type for functions.
876 InitBuiltinType(OverloadTy, BuiltinType::Overload);
877
John McCall864c0412011-04-26 20:42:42 +0000878 // Placeholder type for bound members.
879 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
880
John McCall3c3b7f92011-10-25 17:37:35 +0000881 // Placeholder type for pseudo-objects.
882 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
883
John McCall1de4d4e2011-04-07 08:22:57 +0000884 // "any" type; useful for debugger-like clients.
885 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
886
John McCall0ddaeb92011-10-17 18:09:15 +0000887 // Placeholder type for unbridged ARC casts.
888 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
889
Eli Friedmana6c66ce2012-08-31 00:14:07 +0000890 // Placeholder type for builtin functions.
891 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
892
Reid Spencer5f016e22007-07-11 17:01:13 +0000893 // C99 6.2.5p11.
894 FloatComplexTy = getComplexType(FloatTy);
895 DoubleComplexTy = getComplexType(DoubleTy);
896 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000897
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000898 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000899 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
900 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000901 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeib13621d2012-12-18 14:38:23 +0000902
903 if (LangOpts.OpenCL) {
904 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
905 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
906 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
907 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
908 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
909 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
Guy Benyeie6b9d802013-01-20 12:31:11 +0000910
Guy Benyei21f18c42013-02-07 10:55:47 +0000911 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyeie6b9d802013-01-20 12:31:11 +0000912 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Guy Benyeib13621d2012-12-18 14:38:23 +0000913 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000914
915 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian93a49942012-04-16 21:03:30 +0000916 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
917 SignedCharTy : BoolTy);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000918
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000919 ObjCConstantStringType = QualType();
Fariborz Jahanianf7992132013-01-04 18:45:40 +0000920
921 ObjCSuperType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000922
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000923 // void * type
924 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000925
926 // nullptr type (C++0x 2.14.7)
927 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000928
929 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
930 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingefb40e3f2012-07-01 15:57:25 +0000931
932 // Builtin type used to help define __builtin_va_list.
933 VaListTagTy = QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000934}
935
David Blaikied6471f72011-09-25 23:23:43 +0000936DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +0000937 return SourceMgr.getDiagnostics();
938}
939
Douglas Gregor63200642010-08-30 16:49:28 +0000940AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
941 AttrVec *&Result = DeclAttrs[D];
942 if (!Result) {
943 void *Mem = Allocate(sizeof(AttrVec));
944 Result = new (Mem) AttrVec;
945 }
946
947 return *Result;
948}
949
950/// \brief Erase the attributes corresponding to the given declaration.
951void ASTContext::eraseDeclAttrs(const Decl *D) {
952 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
953 if (Pos != DeclAttrs.end()) {
954 Pos->second->~AttrVec();
955 DeclAttrs.erase(Pos);
956 }
957}
958
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000959MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000960ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000961 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000962 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000963 = InstantiatedFromStaticDataMember.find(Var);
964 if (Pos == InstantiatedFromStaticDataMember.end())
965 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000966
Douglas Gregor7caa6822009-07-24 20:34:43 +0000967 return Pos->second;
968}
969
Mike Stump1eb44332009-09-09 15:08:12 +0000970void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000971ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000972 TemplateSpecializationKind TSK,
973 SourceLocation PointOfInstantiation) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000974 assert(Inst->isStaticDataMember() && "Not a static data member");
975 assert(Tmpl->isStaticDataMember() && "Not a static data member");
976 assert(!InstantiatedFromStaticDataMember[Inst] &&
977 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000978 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000979 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000980}
981
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000982FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
983 const FunctionDecl *FD){
984 assert(FD && "Specialization is 0");
985 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet0d95f0d2011-08-14 14:28:49 +0000986 = ClassScopeSpecializationPattern.find(FD);
987 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000988 return 0;
989
990 return Pos->second;
991}
992
993void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
994 FunctionDecl *Pattern) {
995 assert(FD && "Specialization is 0");
996 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet0d95f0d2011-08-14 14:28:49 +0000997 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000998}
999
John McCall7ba107a2009-11-18 02:36:19 +00001000NamedDecl *
John McCalled976492009-12-04 22:46:56 +00001001ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +00001002 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +00001003 = InstantiatedFromUsingDecl.find(UUD);
1004 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +00001005 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001006
Anders Carlsson0d8df782009-08-29 19:37:28 +00001007 return Pos->second;
1008}
1009
1010void
John McCalled976492009-12-04 22:46:56 +00001011ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1012 assert((isa<UsingDecl>(Pattern) ||
1013 isa<UnresolvedUsingValueDecl>(Pattern) ||
1014 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1015 "pattern decl is not a using decl");
1016 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1017 InstantiatedFromUsingDecl[Inst] = Pattern;
1018}
1019
1020UsingShadowDecl *
1021ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1022 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1023 = InstantiatedFromUsingShadowDecl.find(Inst);
1024 if (Pos == InstantiatedFromUsingShadowDecl.end())
1025 return 0;
1026
1027 return Pos->second;
1028}
1029
1030void
1031ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1032 UsingShadowDecl *Pattern) {
1033 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1034 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00001035}
1036
Anders Carlssond8b285f2009-09-01 04:26:58 +00001037FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1038 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1039 = InstantiatedFromUnnamedFieldDecl.find(Field);
1040 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1041 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001042
Anders Carlssond8b285f2009-09-01 04:26:58 +00001043 return Pos->second;
1044}
1045
1046void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1047 FieldDecl *Tmpl) {
1048 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1049 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1050 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1051 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +00001052
Anders Carlssond8b285f2009-09-01 04:26:58 +00001053 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1054}
1055
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +00001056bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
1057 const FieldDecl *LastFD) const {
1058 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001059 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +00001060}
1061
Fariborz Jahanian340fa242011-05-02 17:20:56 +00001062bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
1063 const FieldDecl *LastFD) const {
1064 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001065 FD->getBitWidthValue(*this) == 0 &&
1066 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanian340fa242011-05-02 17:20:56 +00001067}
1068
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +00001069bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
1070 const FieldDecl *LastFD) const {
1071 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001072 FD->getBitWidthValue(*this) &&
1073 LastFD->getBitWidthValue(*this));
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +00001074}
1075
Chad Rosierdd7fddb2011-08-04 23:34:15 +00001076bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +00001077 const FieldDecl *LastFD) const {
1078 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001079 LastFD->getBitWidthValue(*this));
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +00001080}
1081
Chad Rosierdd7fddb2011-08-04 23:34:15 +00001082bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +00001083 const FieldDecl *LastFD) const {
1084 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001085 FD->getBitWidthValue(*this));
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +00001086}
1087
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001088ASTContext::overridden_cxx_method_iterator
1089ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1090 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001091 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001092 if (Pos == OverriddenMethods.end())
1093 return 0;
1094
1095 return Pos->second.begin();
1096}
1097
1098ASTContext::overridden_cxx_method_iterator
1099ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1100 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001101 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001102 if (Pos == OverriddenMethods.end())
1103 return 0;
1104
1105 return Pos->second.end();
1106}
1107
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +00001108unsigned
1109ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1110 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001111 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +00001112 if (Pos == OverriddenMethods.end())
1113 return 0;
1114
1115 return Pos->second.size();
1116}
1117
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001118void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1119 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001120 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001121 OverriddenMethods[Method].push_back(Overridden);
1122}
1123
Dmitri Gribenko1e905da2012-11-03 14:24:57 +00001124void ASTContext::getOverriddenMethods(
1125 const NamedDecl *D,
1126 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001127 assert(D);
1128
1129 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisbc0a2bb2012-10-09 20:08:43 +00001130 Overridden.append(CXXMethod->begin_overridden_methods(),
1131 CXXMethod->end_overridden_methods());
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001132 return;
1133 }
1134
1135 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1136 if (!Method)
1137 return;
1138
Argyrios Kyrtzidis740ae672012-10-09 18:19:01 +00001139 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1140 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisbc0a2bb2012-10-09 20:08:43 +00001141 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001142}
1143
Douglas Gregore6649772011-12-03 00:30:27 +00001144void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1145 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1146 assert(!Import->isFromASTFile() && "Non-local import declaration");
1147 if (!FirstLocalImport) {
1148 FirstLocalImport = Import;
1149 LastLocalImport = Import;
1150 return;
1151 }
1152
1153 LastLocalImport->NextLocalImport = Import;
1154 LastLocalImport = Import;
1155}
1156
Chris Lattner464175b2007-07-18 17:52:12 +00001157//===----------------------------------------------------------------------===//
1158// Type Sizing and Analysis
1159//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +00001160
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001161/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1162/// scalar floating point type.
1163const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +00001164 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001165 assert(BT && "Not a floating point type!");
1166 switch (BT->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001167 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001168 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001169 case BuiltinType::Float: return Target->getFloatFormat();
1170 case BuiltinType::Double: return Target->getDoubleFormat();
1171 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001172 }
1173}
1174
Ken Dyck8b752f12010-01-27 17:10:57 +00001175/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +00001176/// specified decl. Note that bitfields do not have a valid alignment, so
1177/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +00001178/// If @p RefAsPointee, references are treated like their underlying type
1179/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad4ba2a172011-01-12 09:06:06 +00001180CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001181 unsigned Align = Target->getCharWidth();
Eli Friedmandcdafb62009-02-22 02:56:25 +00001182
John McCall4081a5c2010-10-08 18:24:19 +00001183 bool UseAlignAttrOnly = false;
1184 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1185 Align = AlignFromAttr;
Eli Friedmandcdafb62009-02-22 02:56:25 +00001186
John McCall4081a5c2010-10-08 18:24:19 +00001187 // __attribute__((aligned)) can increase or decrease alignment
1188 // *except* on a struct or struct member, where it only increases
1189 // alignment unless 'packed' is also specified.
1190 //
Peter Collingbourne82d0b0a2011-09-29 18:04:28 +00001191 // It is an error for alignas to decrease alignment, so we can
John McCall4081a5c2010-10-08 18:24:19 +00001192 // ignore that possibility; Sema should diagnose it.
1193 if (isa<FieldDecl>(D)) {
1194 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1195 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1196 } else {
1197 UseAlignAttrOnly = true;
1198 }
1199 }
Fariborz Jahanian78a7d7d2011-05-05 21:19:14 +00001200 else if (isa<FieldDecl>(D))
1201 UseAlignAttrOnly =
1202 D->hasAttr<PackedAttr>() ||
1203 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall4081a5c2010-10-08 18:24:19 +00001204
John McCallba4f5d52011-01-20 07:57:12 +00001205 // If we're using the align attribute only, just ignore everything
1206 // else about the declaration and its type.
John McCall4081a5c2010-10-08 18:24:19 +00001207 if (UseAlignAttrOnly) {
John McCallba4f5d52011-01-20 07:57:12 +00001208 // do nothing
1209
John McCall4081a5c2010-10-08 18:24:19 +00001210 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00001211 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001212 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00001213 if (RefAsPointee)
1214 T = RT->getPointeeType();
1215 else
1216 T = getPointerType(RT->getPointeeType());
1217 }
1218 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall3b657512011-01-19 10:06:00 +00001219 // Adjust alignments of declarations with array type by the
1220 // large-array alignment on the target.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001221 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall3b657512011-01-19 10:06:00 +00001222 const ArrayType *arrayType;
1223 if (MinWidth && (arrayType = getAsArrayType(T))) {
1224 if (isa<VariableArrayType>(arrayType))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001225 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall3b657512011-01-19 10:06:00 +00001226 else if (isa<ConstantArrayType>(arrayType) &&
1227 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001228 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedmandcdafb62009-02-22 02:56:25 +00001229
John McCall3b657512011-01-19 10:06:00 +00001230 // Walk through any array types while we're at it.
1231 T = getBaseElementType(arrayType);
1232 }
Chad Rosier9f1210c2011-07-26 07:03:04 +00001233 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedmandcdafb62009-02-22 02:56:25 +00001234 }
John McCallba4f5d52011-01-20 07:57:12 +00001235
1236 // Fields can be subject to extra alignment constraints, like if
1237 // the field is packed, the struct is packed, or the struct has a
1238 // a max-field-alignment constraint (#pragma pack). So calculate
1239 // the actual alignment of the field within the struct, and then
1240 // (as we're expected to) constrain that by the alignment of the type.
1241 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
1242 // So calculate the alignment of the field.
1243 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
1244
1245 // Start with the record's overall alignment.
Ken Dyckdac54c12011-02-15 02:32:40 +00001246 unsigned fieldAlign = toBits(layout.getAlignment());
John McCallba4f5d52011-01-20 07:57:12 +00001247
1248 // Use the GCD of that and the offset within the record.
1249 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
1250 if (offset > 0) {
1251 // Alignment is always a power of 2, so the GCD will be a power of 2,
1252 // which means we get to do this crazy thing instead of Euclid's.
1253 uint64_t lowBitOfOffset = offset & (~offset + 1);
1254 if (lowBitOfOffset < fieldAlign)
1255 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
1256 }
1257
1258 Align = std::min(Align, fieldAlign);
Charles Davis05f62472010-02-23 04:52:00 +00001259 }
Chris Lattneraf707ab2009-01-24 21:53:27 +00001260 }
Eli Friedmandcdafb62009-02-22 02:56:25 +00001261
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001262 return toCharUnitsFromBits(Align);
Chris Lattneraf707ab2009-01-24 21:53:27 +00001263}
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001264
John McCall929bbfb2012-08-21 04:10:00 +00001265// getTypeInfoDataSizeInChars - Return the size of a type, in
1266// chars. If the type is a record, its data size is returned. This is
1267// the size of the memcpy that's performed when assigning this type
1268// using a trivial copy/move assignment operator.
1269std::pair<CharUnits, CharUnits>
1270ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1271 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1272
1273 // In C++, objects can sometimes be allocated into the tail padding
1274 // of a base-class subobject. We decide whether that's possible
1275 // during class layout, so here we can just trust the layout results.
1276 if (getLangOpts().CPlusPlus) {
1277 if (const RecordType *RT = T->getAs<RecordType>()) {
1278 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1279 sizeAndAlign.first = layout.getDataSize();
1280 }
1281 }
1282
1283 return sizeAndAlign;
1284}
1285
John McCallea1471e2010-05-20 01:18:31 +00001286std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +00001287ASTContext::getTypeInfoInChars(const Type *T) const {
John McCallea1471e2010-05-20 01:18:31 +00001288 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001289 return std::make_pair(toCharUnitsFromBits(Info.first),
1290 toCharUnitsFromBits(Info.second));
John McCallea1471e2010-05-20 01:18:31 +00001291}
1292
1293std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +00001294ASTContext::getTypeInfoInChars(QualType T) const {
John McCallea1471e2010-05-20 01:18:31 +00001295 return getTypeInfoInChars(T.getTypePtr());
1296}
1297
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001298std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1299 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1300 if (it != MemoizedTypeInfo.end())
1301 return it->second;
1302
1303 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1304 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1305 return Info;
1306}
1307
1308/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1309/// method does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +00001310///
1311/// FIXME: Pointers into different addr spaces could have different sizes and
1312/// alignment requirements: getPointerInfo should take an AddrSpace, this
1313/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +00001314std::pair<uint64_t, unsigned>
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001315ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5e301002009-02-27 18:32:39 +00001316 uint64_t Width=0;
1317 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +00001318 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +00001319#define TYPE(Class, Base)
1320#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +00001321#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +00001322#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1323#include "clang/AST/TypeNodes.def"
John McCalld3d49bb2011-06-28 16:49:23 +00001324 llvm_unreachable("Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +00001325
Chris Lattner692233e2007-07-13 22:27:08 +00001326 case Type::FunctionNoProto:
1327 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +00001328 // GCC extension: alignof(function) = 32 bits
1329 Width = 0;
1330 Align = 32;
1331 break;
1332
Douglas Gregor72564e72009-02-26 23:50:07 +00001333 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +00001334 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +00001335 Width = 0;
1336 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1337 break;
1338
Steve Narofffb22d962007-08-30 01:06:46 +00001339 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001340 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001341
Chris Lattner98be4942008-03-05 18:54:05 +00001342 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarafea966a2011-12-13 11:23:52 +00001343 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001344 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1345 "Overflow in array type bit size evaluation");
Abramo Bagnarafea966a2011-12-13 11:23:52 +00001346 Width = EltInfo.first*Size;
Chris Lattner030d8842007-07-19 22:06:24 +00001347 Align = EltInfo.second;
Argyrios Kyrtzidiscd88b412011-04-26 21:05:39 +00001348 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattner030d8842007-07-19 22:06:24 +00001349 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +00001350 }
Nate Begeman213541a2008-04-18 23:10:10 +00001351 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +00001352 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +00001353 const VectorType *VT = cast<VectorType>(T);
1354 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1355 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +00001356 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +00001357 // If the alignment is not a power of 2, round up to the next power of 2.
1358 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +00001359 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +00001360 Align = llvm::NextPowerOf2(Align);
1361 Width = llvm::RoundUpToAlignment(Width, Align);
1362 }
Chad Rosierf9e9af72012-07-13 23:57:43 +00001363 // Adjust the alignment based on the target max.
1364 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1365 if (TargetVectorAlign && TargetVectorAlign < Align)
1366 Align = TargetVectorAlign;
Chris Lattner030d8842007-07-19 22:06:24 +00001367 break;
1368 }
Chris Lattner5d2a6302007-07-18 18:26:58 +00001369
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001370 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +00001371 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001372 default: llvm_unreachable("Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +00001373 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +00001374 // GCC extension: alignof(void) = 8 bits.
1375 Width = 0;
1376 Align = 8;
1377 break;
1378
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001379 case BuiltinType::Bool:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001380 Width = Target->getBoolWidth();
1381 Align = Target->getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001382 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001383 case BuiltinType::Char_S:
1384 case BuiltinType::Char_U:
1385 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001386 case BuiltinType::SChar:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001387 Width = Target->getCharWidth();
1388 Align = Target->getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001389 break;
Chris Lattner3f59c972010-12-25 23:25:43 +00001390 case BuiltinType::WChar_S:
1391 case BuiltinType::WChar_U:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001392 Width = Target->getWCharWidth();
1393 Align = Target->getWCharAlign();
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00001394 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001395 case BuiltinType::Char16:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001396 Width = Target->getChar16Width();
1397 Align = Target->getChar16Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001398 break;
1399 case BuiltinType::Char32:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001400 Width = Target->getChar32Width();
1401 Align = Target->getChar32Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001402 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001403 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001404 case BuiltinType::Short:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001405 Width = Target->getShortWidth();
1406 Align = Target->getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001407 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001408 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001409 case BuiltinType::Int:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001410 Width = Target->getIntWidth();
1411 Align = Target->getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001412 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001413 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001414 case BuiltinType::Long:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001415 Width = Target->getLongWidth();
1416 Align = Target->getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001417 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001418 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001419 case BuiltinType::LongLong:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001420 Width = Target->getLongLongWidth();
1421 Align = Target->getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001422 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +00001423 case BuiltinType::Int128:
1424 case BuiltinType::UInt128:
1425 Width = 128;
1426 Align = 128; // int128_t is 128-bit aligned on all targets.
1427 break;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001428 case BuiltinType::Half:
1429 Width = Target->getHalfWidth();
1430 Align = Target->getHalfAlign();
1431 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001432 case BuiltinType::Float:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001433 Width = Target->getFloatWidth();
1434 Align = Target->getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001435 break;
1436 case BuiltinType::Double:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001437 Width = Target->getDoubleWidth();
1438 Align = Target->getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001439 break;
1440 case BuiltinType::LongDouble:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001441 Width = Target->getLongDoubleWidth();
1442 Align = Target->getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001443 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001444 case BuiltinType::NullPtr:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001445 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1446 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +00001447 break;
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +00001448 case BuiltinType::ObjCId:
1449 case BuiltinType::ObjCClass:
1450 case BuiltinType::ObjCSel:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001451 Width = Target->getPointerWidth(0);
1452 Align = Target->getPointerAlign(0);
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +00001453 break;
Guy Benyei21f18c42013-02-07 10:55:47 +00001454 case BuiltinType::OCLSampler:
1455 // Samplers are modeled as integers.
1456 Width = Target->getIntWidth();
1457 Align = Target->getIntAlign();
1458 break;
Guy Benyeie6b9d802013-01-20 12:31:11 +00001459 case BuiltinType::OCLEvent:
Guy Benyeib13621d2012-12-18 14:38:23 +00001460 case BuiltinType::OCLImage1d:
1461 case BuiltinType::OCLImage1dArray:
1462 case BuiltinType::OCLImage1dBuffer:
1463 case BuiltinType::OCLImage2d:
1464 case BuiltinType::OCLImage2dArray:
1465 case BuiltinType::OCLImage3d:
1466 // Currently these types are pointers to opaque types.
1467 Width = Target->getPointerWidth(0);
1468 Align = Target->getPointerAlign(0);
1469 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001470 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +00001471 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001472 case Type::ObjCObjectPointer:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001473 Width = Target->getPointerWidth(0);
1474 Align = Target->getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001475 break;
Steve Naroff485eeff2008-09-24 15:05:44 +00001476 case Type::BlockPointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001477 unsigned AS = getTargetAddressSpace(
1478 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001479 Width = Target->getPointerWidth(AS);
1480 Align = Target->getPointerAlign(AS);
Steve Naroff485eeff2008-09-24 15:05:44 +00001481 break;
1482 }
Sebastian Redl5d484e82009-11-23 17:18:46 +00001483 case Type::LValueReference:
1484 case Type::RValueReference: {
1485 // alignof and sizeof should never enter this code path here, so we go
1486 // the pointer route.
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001487 unsigned AS = getTargetAddressSpace(
1488 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001489 Width = Target->getPointerWidth(AS);
1490 Align = Target->getPointerAlign(AS);
Sebastian Redl5d484e82009-11-23 17:18:46 +00001491 break;
1492 }
Chris Lattnerf72a4432008-03-08 08:34:58 +00001493 case Type::Pointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001494 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001495 Width = Target->getPointerWidth(AS);
1496 Align = Target->getPointerAlign(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +00001497 break;
1498 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00001499 case Type::MemberPointer: {
Charles Davis071cc7d2010-08-16 03:33:14 +00001500 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Reid Kleckner84e9ab42013-03-28 20:02:56 +00001501 llvm::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson1cca74e2009-05-17 02:06:04 +00001502 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +00001503 }
Chris Lattner5d2a6302007-07-18 18:26:58 +00001504 case Type::Complex: {
1505 // Complex types have the same alignment as their elements, but twice the
1506 // size.
Mike Stump1eb44332009-09-09 15:08:12 +00001507 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +00001508 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001509 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +00001510 Align = EltInfo.second;
1511 break;
1512 }
John McCallc12c5bb2010-05-15 11:32:37 +00001513 case Type::ObjCObject:
1514 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +00001515 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001516 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +00001517 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001518 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001519 Align = toBits(Layout.getAlignment());
Devang Patel44a3dde2008-06-04 21:54:36 +00001520 break;
1521 }
Douglas Gregor72564e72009-02-26 23:50:07 +00001522 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00001523 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001524 const TagType *TT = cast<TagType>(T);
1525
1526 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor22ce41d2011-04-20 17:29:44 +00001527 Width = 8;
1528 Align = 8;
Chris Lattner8389eab2008-08-09 21:35:13 +00001529 break;
1530 }
Mike Stump1eb44332009-09-09 15:08:12 +00001531
Daniel Dunbar1d751182008-11-08 05:48:37 +00001532 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +00001533 return getTypeInfo(ET->getDecl()->getIntegerType());
1534
Daniel Dunbar1d751182008-11-08 05:48:37 +00001535 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +00001536 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001537 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001538 Align = toBits(Layout.getAlignment());
Chris Lattnerdc0d73e2007-07-23 22:46:22 +00001539 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001540 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001541
Chris Lattner9fcfe922009-10-22 05:17:15 +00001542 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +00001543 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1544 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +00001545
Richard Smith34b41d92011-02-20 03:19:35 +00001546 case Type::Auto: {
1547 const AutoType *A = cast<AutoType>(T);
1548 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gaydc856af2011-02-22 20:00:16 +00001549 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith34b41d92011-02-20 03:19:35 +00001550 }
1551
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001552 case Type::Paren:
1553 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1554
Douglas Gregor18857642009-04-30 17:32:17 +00001555 case Type::Typedef: {
Richard Smith162e1c12011-04-15 14:24:37 +00001556 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregordf1367a2010-08-27 00:11:28 +00001557 std::pair<uint64_t, unsigned> Info
1558 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattnerc1de52d2011-02-19 22:55:41 +00001559 // If the typedef has an aligned attribute on it, it overrides any computed
1560 // alignment we have. This violates the GCC documentation (which says that
1561 // attribute(aligned) can only round up) but matches its implementation.
1562 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1563 Align = AttrAlign;
1564 else
1565 Align = Info.second;
Douglas Gregordf1367a2010-08-27 00:11:28 +00001566 Width = Info.first;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001567 break;
Chris Lattner71763312008-04-06 22:05:18 +00001568 }
Douglas Gregor18857642009-04-30 17:32:17 +00001569
1570 case Type::TypeOfExpr:
1571 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1572 .getTypePtr());
1573
1574 case Type::TypeOf:
1575 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1576
Anders Carlsson395b4752009-06-24 19:06:50 +00001577 case Type::Decltype:
1578 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1579 .getTypePtr());
1580
Sean Huntca63c202011-05-24 22:41:36 +00001581 case Type::UnaryTransform:
1582 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1583
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001584 case Type::Elaborated:
1585 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +00001586
John McCall9d156a72011-01-06 01:58:22 +00001587 case Type::Attributed:
1588 return getTypeInfo(
1589 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1590
Richard Smith3e4c6c42011-05-05 21:57:07 +00001591 case Type::TemplateSpecialization: {
Mike Stump1eb44332009-09-09 15:08:12 +00001592 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +00001593 "Cannot request the size of a dependent type");
Richard Smith3e4c6c42011-05-05 21:57:07 +00001594 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1595 // A type alias template specialization may refer to a typedef with the
1596 // aligned attribute on it.
1597 if (TST->isTypeAlias())
1598 return getTypeInfo(TST->getAliasedType().getTypePtr());
1599 else
1600 return getTypeInfo(getCanonicalType(T));
1601 }
1602
Eli Friedmanb001de72011-10-06 23:00:33 +00001603 case Type::Atomic: {
John McCall9eda3ab2013-03-07 21:37:17 +00001604 // Start with the base type information.
Eli Friedman2be46072011-10-14 20:59:01 +00001605 std::pair<uint64_t, unsigned> Info
1606 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1607 Width = Info.first;
1608 Align = Info.second;
John McCall9eda3ab2013-03-07 21:37:17 +00001609
1610 // If the size of the type doesn't exceed the platform's max
1611 // atomic promotion width, make the size and alignment more
1612 // favorable to atomic operations:
1613 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1614 // Round the size up to a power of 2.
1615 if (!llvm::isPowerOf2_64(Width))
1616 Width = llvm::NextPowerOf2(Width);
1617
1618 // Set the alignment equal to the size.
Eli Friedman2be46072011-10-14 20:59:01 +00001619 Align = static_cast<unsigned>(Width);
1620 }
Eli Friedmanb001de72011-10-06 23:00:33 +00001621 }
1622
Douglas Gregor18857642009-04-30 17:32:17 +00001623 }
Mike Stump1eb44332009-09-09 15:08:12 +00001624
Eli Friedman2be46072011-10-14 20:59:01 +00001625 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001626 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +00001627}
1628
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001629/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1630CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1631 return CharUnits::fromQuantity(BitSize / getCharWidth());
1632}
1633
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001634/// toBits - Convert a size in characters to a size in characters.
1635int64_t ASTContext::toBits(CharUnits CharSize) const {
1636 return CharSize.getQuantity() * getCharWidth();
1637}
1638
Ken Dyckbdc601b2009-12-22 14:23:30 +00001639/// getTypeSizeInChars - Return the size of the specified type, in characters.
1640/// This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001641CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001642 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +00001643}
Jay Foad4ba2a172011-01-12 09:06:06 +00001644CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001645 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +00001646}
1647
Ken Dyck16e20cc2010-01-26 17:25:18 +00001648/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +00001649/// characters. This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001650CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001651 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001652}
Jay Foad4ba2a172011-01-12 09:06:06 +00001653CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001654 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001655}
1656
Chris Lattner34ebde42009-01-27 18:08:34 +00001657/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1658/// type for the current target in bits. This can be different than the ABI
1659/// alignment in cases where it is beneficial for performance to overalign
1660/// a data type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001661unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattner34ebde42009-01-27 18:08:34 +00001662 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +00001663
1664 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +00001665 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +00001666 T = CT->getElementType().getTypePtr();
1667 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosiercde7a1d2012-03-21 20:20:47 +00001668 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1669 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman1eed6022009-05-25 21:27:19 +00001670 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1671
Chris Lattner34ebde42009-01-27 18:08:34 +00001672 return ABIAlign;
1673}
1674
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001675/// DeepCollectObjCIvars -
1676/// This routine first collects all declared, but not synthesized, ivars in
1677/// super class and then collects all ivars, including those synthesized for
1678/// current class. This routine is used for implementation of current class
1679/// when all ivars, declared and synthesized are known.
Fariborz Jahanian98200742009-05-12 18:14:29 +00001680///
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001681void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1682 bool leafClass,
Jordy Rosedb8264e2011-07-22 02:08:32 +00001683 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001684 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1685 DeepCollectObjCIvars(SuperClass, false, Ivars);
1686 if (!leafClass) {
1687 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1688 E = OI->ivar_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001689 Ivars.push_back(*I);
Chad Rosier30601782011-08-17 23:08:45 +00001690 } else {
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001691 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosedb8264e2011-07-22 02:08:32 +00001692 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001693 Iv= Iv->getNextIvar())
1694 Ivars.push_back(Iv);
1695 }
Fariborz Jahanian98200742009-05-12 18:14:29 +00001696}
1697
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001698/// CollectInheritedProtocols - Collect all protocols in current class and
1699/// those inherited by it.
1700void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001701 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001702 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001703 // We can use protocol_iterator here instead of
1704 // all_referenced_protocol_iterator since we are walking all categories.
1705 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1706 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001707 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001708 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001709 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001710 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001711 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001712 CollectInheritedProtocols(*P, Protocols);
1713 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001714 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001715
1716 // Categories of this Interface.
Douglas Gregord3297242013-01-16 23:00:23 +00001717 for (ObjCInterfaceDecl::visible_categories_iterator
1718 Cat = OI->visible_categories_begin(),
1719 CatEnd = OI->visible_categories_end();
1720 Cat != CatEnd; ++Cat) {
1721 CollectInheritedProtocols(*Cat, Protocols);
1722 }
1723
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001724 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1725 while (SD) {
1726 CollectInheritedProtocols(SD, Protocols);
1727 SD = SD->getSuperClass();
1728 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001729 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001730 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001731 PE = OC->protocol_end(); P != PE; ++P) {
1732 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001733 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001734 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1735 PE = Proto->protocol_end(); P != PE; ++P)
1736 CollectInheritedProtocols(*P, Protocols);
1737 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001738 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001739 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1740 PE = OP->protocol_end(); P != PE; ++P) {
1741 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001742 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001743 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1744 PE = Proto->protocol_end(); P != PE; ++P)
1745 CollectInheritedProtocols(*P, Protocols);
1746 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001747 }
1748}
1749
Jay Foad4ba2a172011-01-12 09:06:06 +00001750unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001751 unsigned count = 0;
1752 // Count ivars declared in class extension.
Douglas Gregord3297242013-01-16 23:00:23 +00001753 for (ObjCInterfaceDecl::known_extensions_iterator
1754 Ext = OI->known_extensions_begin(),
1755 ExtEnd = OI->known_extensions_end();
1756 Ext != ExtEnd; ++Ext) {
1757 count += Ext->ivar_size();
1758 }
1759
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001760 // Count ivar defined in this class's implementation. This
1761 // includes synthesized ivars.
1762 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001763 count += ImplDecl->ivar_size();
1764
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001765 return count;
1766}
1767
Argyrios Kyrtzidis8deabc12012-02-03 05:58:16 +00001768bool ASTContext::isSentinelNullExpr(const Expr *E) {
1769 if (!E)
1770 return false;
1771
1772 // nullptr_t is always treated as null.
1773 if (E->getType()->isNullPtrType()) return true;
1774
1775 if (E->getType()->isAnyPointerType() &&
1776 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1777 Expr::NPC_ValueDependentIsNull))
1778 return true;
1779
1780 // Unfortunately, __null has type 'int'.
1781 if (isa<GNUNullExpr>(E)) return true;
1782
1783 return false;
1784}
1785
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +00001786/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1787ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1788 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1789 I = ObjCImpls.find(D);
1790 if (I != ObjCImpls.end())
1791 return cast<ObjCImplementationDecl>(I->second);
1792 return 0;
1793}
1794/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1795ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1796 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1797 I = ObjCImpls.find(D);
1798 if (I != ObjCImpls.end())
1799 return cast<ObjCCategoryImplDecl>(I->second);
1800 return 0;
1801}
1802
1803/// \brief Set the implementation of ObjCInterfaceDecl.
1804void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1805 ObjCImplementationDecl *ImplD) {
1806 assert(IFaceD && ImplD && "Passed null params");
1807 ObjCImpls[IFaceD] = ImplD;
1808}
1809/// \brief Set the implementation of ObjCCategoryDecl.
1810void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1811 ObjCCategoryImplDecl *ImplD) {
1812 assert(CatD && ImplD && "Passed null params");
1813 ObjCImpls[CatD] = ImplD;
1814}
1815
Dmitri Gribenkob35cc2d2013-02-03 13:23:21 +00001816const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
1817 const NamedDecl *ND) const {
1818 if (const ObjCInterfaceDecl *ID =
1819 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001820 return ID;
Dmitri Gribenkob35cc2d2013-02-03 13:23:21 +00001821 if (const ObjCCategoryDecl *CD =
1822 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001823 return CD->getClassInterface();
Dmitri Gribenkob35cc2d2013-02-03 13:23:21 +00001824 if (const ObjCImplDecl *IMD =
1825 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001826 return IMD->getClassInterface();
1827
1828 return 0;
1829}
1830
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001831/// \brief Get the copy initialization expression of VarDecl,or NULL if
1832/// none exists.
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001833Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001834 assert(VD && "Passed null params");
1835 assert(VD->hasAttr<BlocksAttr>() &&
1836 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001837 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001838 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001839 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1840}
1841
1842/// \brief Set the copy inialization expression of a block var decl.
1843void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1844 assert(VD && Init && "Passed null params");
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001845 assert(VD->hasAttr<BlocksAttr>() &&
1846 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001847 BlockVarCopyInits[VD] = Init;
1848}
1849
John McCalla93c9342009-12-07 02:54:59 +00001850TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001851 unsigned DataSize) const {
John McCall109de5e2009-10-21 00:23:54 +00001852 if (!DataSize)
1853 DataSize = TypeLoc::getFullDataSizeForType(T);
1854 else
1855 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001856 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001857
John McCalla93c9342009-12-07 02:54:59 +00001858 TypeSourceInfo *TInfo =
1859 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1860 new (TInfo) TypeSourceInfo(T);
1861 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001862}
1863
John McCalla93c9342009-12-07 02:54:59 +00001864TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001865 SourceLocation L) const {
John McCalla93c9342009-12-07 02:54:59 +00001866 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregorc21c7e92011-01-25 19:13:18 +00001867 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCalla4eb74d2009-10-23 21:14:09 +00001868 return DI;
1869}
1870
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001871const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001872ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001873 return getObjCLayout(D, 0);
1874}
1875
1876const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001877ASTContext::getASTObjCImplementationLayout(
1878 const ObjCImplementationDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001879 return getObjCLayout(D->getClassInterface(), D);
1880}
1881
Chris Lattnera7674d82007-07-13 22:13:22 +00001882//===----------------------------------------------------------------------===//
1883// Type creation/memoization methods
1884//===----------------------------------------------------------------------===//
1885
Jay Foad4ba2a172011-01-12 09:06:06 +00001886QualType
John McCall3b657512011-01-19 10:06:00 +00001887ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1888 unsigned fastQuals = quals.getFastQualifiers();
1889 quals.removeFastQualifiers();
John McCall0953e762009-09-24 19:53:00 +00001890
1891 // Check if we've already instantiated this type.
1892 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001893 ExtQuals::Profile(ID, baseType, quals);
1894 void *insertPos = 0;
1895 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1896 assert(eq->getQualifiers() == quals);
1897 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001898 }
1899
John McCall3b657512011-01-19 10:06:00 +00001900 // If the base type is not canonical, make the appropriate canonical type.
1901 QualType canon;
1902 if (!baseType->isCanonicalUnqualified()) {
1903 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall200fa532012-02-08 00:46:36 +00001904 canonSplit.Quals.addConsistentQualifiers(quals);
1905 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00001906
1907 // Re-find the insert position.
1908 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1909 }
1910
1911 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1912 ExtQualNodes.InsertNode(eq, insertPos);
1913 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001914}
1915
Jay Foad4ba2a172011-01-12 09:06:06 +00001916QualType
1917ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001918 QualType CanT = getCanonicalType(T);
1919 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001920 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001921
John McCall0953e762009-09-24 19:53:00 +00001922 // If we are composing extended qualifiers together, merge together
1923 // into one ExtQuals node.
1924 QualifierCollector Quals;
1925 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001926
John McCall0953e762009-09-24 19:53:00 +00001927 // If this type already has an address space specified, it cannot get
1928 // another one.
1929 assert(!Quals.hasAddressSpace() &&
1930 "Type cannot be in multiple addr spaces!");
1931 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001932
John McCall0953e762009-09-24 19:53:00 +00001933 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001934}
1935
Chris Lattnerb7d25532009-02-18 22:53:11 +00001936QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001937 Qualifiers::GC GCAttr) const {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001938 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001939 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001940 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001941
John McCall7f040a92010-12-24 02:08:15 +00001942 if (const PointerType *ptr = T->getAs<PointerType>()) {
1943 QualType Pointee = ptr->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001944 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001945 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1946 return getPointerType(ResultType);
1947 }
1948 }
Mike Stump1eb44332009-09-09 15:08:12 +00001949
John McCall0953e762009-09-24 19:53:00 +00001950 // If we are composing extended qualifiers together, merge together
1951 // into one ExtQuals node.
1952 QualifierCollector Quals;
1953 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001954
John McCall0953e762009-09-24 19:53:00 +00001955 // If this type already has an ObjCGC specified, it cannot get
1956 // another one.
1957 assert(!Quals.hasObjCGCAttr() &&
1958 "Type cannot have multiple ObjCGCs!");
1959 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001960
John McCall0953e762009-09-24 19:53:00 +00001961 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001962}
Chris Lattnera7674d82007-07-13 22:13:22 +00001963
John McCalle6a365d2010-12-19 02:44:49 +00001964const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1965 FunctionType::ExtInfo Info) {
1966 if (T->getExtInfo() == Info)
1967 return T;
1968
1969 QualType Result;
1970 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1971 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1972 } else {
1973 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1974 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1975 EPI.ExtInfo = Info;
Jordan Rosebea522f2013-03-08 21:51:21 +00001976 Result = getFunctionType(FPT->getResultType(),
1977 ArrayRef<QualType>(FPT->arg_type_begin(),
1978 FPT->getNumArgs()),
1979 EPI);
John McCalle6a365d2010-12-19 02:44:49 +00001980 }
1981
1982 return cast<FunctionType>(Result.getTypePtr());
1983}
1984
Reid Spencer5f016e22007-07-11 17:01:13 +00001985/// getComplexType - Return the uniqued reference to the type for a complex
1986/// number with the specified element type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001987QualType ASTContext::getComplexType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001988 // Unique pointers, to guarantee there is only one pointer of a particular
1989 // structure.
1990 llvm::FoldingSetNodeID ID;
1991 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001992
Reid Spencer5f016e22007-07-11 17:01:13 +00001993 void *InsertPos = 0;
1994 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1995 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001996
Reid Spencer5f016e22007-07-11 17:01:13 +00001997 // If the pointee type isn't canonical, this won't be a canonical type either,
1998 // so fill in the canonical type field.
1999 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002000 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002001 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00002002
Reid Spencer5f016e22007-07-11 17:01:13 +00002003 // Get the new insert position for the node we care about.
2004 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002005 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002006 }
John McCall6b304a02009-09-24 23:30:46 +00002007 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00002008 Types.push_back(New);
2009 ComplexTypes.InsertNode(New, InsertPos);
2010 return QualType(New, 0);
2011}
2012
Reid Spencer5f016e22007-07-11 17:01:13 +00002013/// getPointerType - Return the uniqued reference to the type for a pointer to
2014/// the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002015QualType ASTContext::getPointerType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002016 // Unique pointers, to guarantee there is only one pointer of a particular
2017 // structure.
2018 llvm::FoldingSetNodeID ID;
2019 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00002020
Reid Spencer5f016e22007-07-11 17:01:13 +00002021 void *InsertPos = 0;
2022 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2023 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002024
Reid Spencer5f016e22007-07-11 17:01:13 +00002025 // If the pointee type isn't canonical, this won't be a canonical type either,
2026 // so fill in the canonical type field.
2027 QualType Canonical;
Bob Wilsonc90cc932013-03-15 17:12:43 +00002028 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002029 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00002030
Bob Wilsonc90cc932013-03-15 17:12:43 +00002031 // Get the new insert position for the node we care about.
2032 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2033 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2034 }
John McCall6b304a02009-09-24 23:30:46 +00002035 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00002036 Types.push_back(New);
2037 PointerTypes.InsertNode(New, InsertPos);
2038 return QualType(New, 0);
2039}
2040
Mike Stump1eb44332009-09-09 15:08:12 +00002041/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00002042/// a pointer to the specified block.
Jay Foad4ba2a172011-01-12 09:06:06 +00002043QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff296e8d52008-08-28 19:20:44 +00002044 assert(T->isFunctionType() && "block of function types only");
2045 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00002046 // structure.
2047 llvm::FoldingSetNodeID ID;
2048 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00002049
Steve Naroff5618bd42008-08-27 16:04:49 +00002050 void *InsertPos = 0;
2051 if (BlockPointerType *PT =
2052 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2053 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002054
2055 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00002056 // type either so fill in the canonical type field.
2057 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002058 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00002059 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00002060
Steve Naroff5618bd42008-08-27 16:04:49 +00002061 // Get the new insert position for the node we care about.
2062 BlockPointerType *NewIP =
2063 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002064 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00002065 }
John McCall6b304a02009-09-24 23:30:46 +00002066 BlockPointerType *New
2067 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00002068 Types.push_back(New);
2069 BlockPointerTypes.InsertNode(New, InsertPos);
2070 return QualType(New, 0);
2071}
2072
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002073/// getLValueReferenceType - Return the uniqued reference to the type for an
2074/// lvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002075QualType
2076ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor9625e442011-05-21 22:16:50 +00002077 assert(getCanonicalType(T) != OverloadTy &&
2078 "Unresolved overloaded function type");
2079
Reid Spencer5f016e22007-07-11 17:01:13 +00002080 // Unique pointers, to guarantee there is only one pointer of a particular
2081 // structure.
2082 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00002083 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00002084
2085 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002086 if (LValueReferenceType *RT =
2087 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002088 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002089
John McCall54e14c42009-10-22 22:37:11 +00002090 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2091
Reid Spencer5f016e22007-07-11 17:01:13 +00002092 // If the referencee type isn't canonical, this won't be a canonical type
2093 // either, so fill in the canonical type field.
2094 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00002095 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2096 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2097 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002098
Reid Spencer5f016e22007-07-11 17:01:13 +00002099 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002100 LValueReferenceType *NewIP =
2101 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002102 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002103 }
2104
John McCall6b304a02009-09-24 23:30:46 +00002105 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00002106 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2107 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00002108 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002109 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00002110
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002111 return QualType(New, 0);
2112}
2113
2114/// getRValueReferenceType - Return the uniqued reference to the type for an
2115/// rvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002116QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002117 // Unique pointers, to guarantee there is only one pointer of a particular
2118 // structure.
2119 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00002120 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002121
2122 void *InsertPos = 0;
2123 if (RValueReferenceType *RT =
2124 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2125 return QualType(RT, 0);
2126
John McCall54e14c42009-10-22 22:37:11 +00002127 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2128
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002129 // If the referencee type isn't canonical, this won't be a canonical type
2130 // either, so fill in the canonical type field.
2131 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00002132 if (InnerRef || !T.isCanonical()) {
2133 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2134 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002135
2136 // Get the new insert position for the node we care about.
2137 RValueReferenceType *NewIP =
2138 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002139 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002140 }
2141
John McCall6b304a02009-09-24 23:30:46 +00002142 RValueReferenceType *New
2143 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002144 Types.push_back(New);
2145 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002146 return QualType(New, 0);
2147}
2148
Sebastian Redlf30208a2009-01-24 21:16:55 +00002149/// getMemberPointerType - Return the uniqued reference to the type for a
2150/// member pointer to the specified type, in the specified class.
Jay Foad4ba2a172011-01-12 09:06:06 +00002151QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redlf30208a2009-01-24 21:16:55 +00002152 // Unique pointers, to guarantee there is only one pointer of a particular
2153 // structure.
2154 llvm::FoldingSetNodeID ID;
2155 MemberPointerType::Profile(ID, T, Cls);
2156
2157 void *InsertPos = 0;
2158 if (MemberPointerType *PT =
2159 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2160 return QualType(PT, 0);
2161
2162 // If the pointee or class type isn't canonical, this won't be a canonical
2163 // type either, so fill in the canonical type field.
2164 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00002165 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00002166 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2167
2168 // Get the new insert position for the node we care about.
2169 MemberPointerType *NewIP =
2170 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002171 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redlf30208a2009-01-24 21:16:55 +00002172 }
John McCall6b304a02009-09-24 23:30:46 +00002173 MemberPointerType *New
2174 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00002175 Types.push_back(New);
2176 MemberPointerTypes.InsertNode(New, InsertPos);
2177 return QualType(New, 0);
2178}
2179
Mike Stump1eb44332009-09-09 15:08:12 +00002180/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00002181/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002182QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00002183 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00002184 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002185 unsigned IndexTypeQuals) const {
Sebastian Redl923d56d2009-11-05 15:52:31 +00002186 assert((EltTy->isDependentType() ||
2187 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00002188 "Constant array of VLAs is illegal!");
2189
Chris Lattner38aeec72009-05-13 04:12:56 +00002190 // Convert the array size into a canonical width matching the pointer size for
2191 // the target.
2192 llvm::APInt ArySize(ArySizeIn);
Jay Foad9f71a8f2010-12-07 08:25:34 +00002193 ArySize =
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002194 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump1eb44332009-09-09 15:08:12 +00002195
Reid Spencer5f016e22007-07-11 17:01:13 +00002196 llvm::FoldingSetNodeID ID;
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002197 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00002198
Reid Spencer5f016e22007-07-11 17:01:13 +00002199 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002200 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002201 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002202 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002203
John McCall3b657512011-01-19 10:06:00 +00002204 // If the element type isn't canonical or has qualifiers, this won't
2205 // be a canonical type either, so fill in the canonical type field.
2206 QualType Canon;
2207 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2208 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00002209 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002210 ASM, IndexTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00002211 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00002212
Reid Spencer5f016e22007-07-11 17:01:13 +00002213 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00002214 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002215 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002216 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002217 }
Mike Stump1eb44332009-09-09 15:08:12 +00002218
John McCall6b304a02009-09-24 23:30:46 +00002219 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002220 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002221 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002222 Types.push_back(New);
2223 return QualType(New, 0);
2224}
2225
John McCallce889032011-01-18 08:40:38 +00002226/// getVariableArrayDecayedType - Turns the given type, which may be
2227/// variably-modified, into the corresponding type with all the known
2228/// sizes replaced with [*].
2229QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2230 // Vastly most common case.
2231 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002232
John McCallce889032011-01-18 08:40:38 +00002233 QualType result;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002234
John McCallce889032011-01-18 08:40:38 +00002235 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00002236 const Type *ty = split.Ty;
John McCallce889032011-01-18 08:40:38 +00002237 switch (ty->getTypeClass()) {
2238#define TYPE(Class, Base)
2239#define ABSTRACT_TYPE(Class, Base)
2240#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2241#include "clang/AST/TypeNodes.def"
2242 llvm_unreachable("didn't desugar past all non-canonical types?");
2243
2244 // These types should never be variably-modified.
2245 case Type::Builtin:
2246 case Type::Complex:
2247 case Type::Vector:
2248 case Type::ExtVector:
2249 case Type::DependentSizedExtVector:
2250 case Type::ObjCObject:
2251 case Type::ObjCInterface:
2252 case Type::ObjCObjectPointer:
2253 case Type::Record:
2254 case Type::Enum:
2255 case Type::UnresolvedUsing:
2256 case Type::TypeOfExpr:
2257 case Type::TypeOf:
2258 case Type::Decltype:
Sean Huntca63c202011-05-24 22:41:36 +00002259 case Type::UnaryTransform:
John McCallce889032011-01-18 08:40:38 +00002260 case Type::DependentName:
2261 case Type::InjectedClassName:
2262 case Type::TemplateSpecialization:
2263 case Type::DependentTemplateSpecialization:
2264 case Type::TemplateTypeParm:
2265 case Type::SubstTemplateTypeParmPack:
Richard Smith34b41d92011-02-20 03:19:35 +00002266 case Type::Auto:
John McCallce889032011-01-18 08:40:38 +00002267 case Type::PackExpansion:
2268 llvm_unreachable("type should never be variably-modified");
2269
2270 // These types can be variably-modified but should never need to
2271 // further decay.
2272 case Type::FunctionNoProto:
2273 case Type::FunctionProto:
2274 case Type::BlockPointer:
2275 case Type::MemberPointer:
2276 return type;
2277
2278 // These types can be variably-modified. All these modifications
2279 // preserve structure except as noted by comments.
2280 // TODO: if we ever care about optimizing VLAs, there are no-op
2281 // optimizations available here.
2282 case Type::Pointer:
2283 result = getPointerType(getVariableArrayDecayedType(
2284 cast<PointerType>(ty)->getPointeeType()));
2285 break;
2286
2287 case Type::LValueReference: {
2288 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2289 result = getLValueReferenceType(
2290 getVariableArrayDecayedType(lv->getPointeeType()),
2291 lv->isSpelledAsLValue());
2292 break;
2293 }
2294
2295 case Type::RValueReference: {
2296 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2297 result = getRValueReferenceType(
2298 getVariableArrayDecayedType(lv->getPointeeType()));
2299 break;
2300 }
2301
Eli Friedmanb001de72011-10-06 23:00:33 +00002302 case Type::Atomic: {
2303 const AtomicType *at = cast<AtomicType>(ty);
2304 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2305 break;
2306 }
2307
John McCallce889032011-01-18 08:40:38 +00002308 case Type::ConstantArray: {
2309 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2310 result = getConstantArrayType(
2311 getVariableArrayDecayedType(cat->getElementType()),
2312 cat->getSize(),
2313 cat->getSizeModifier(),
2314 cat->getIndexTypeCVRQualifiers());
2315 break;
2316 }
2317
2318 case Type::DependentSizedArray: {
2319 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2320 result = getDependentSizedArrayType(
2321 getVariableArrayDecayedType(dat->getElementType()),
2322 dat->getSizeExpr(),
2323 dat->getSizeModifier(),
2324 dat->getIndexTypeCVRQualifiers(),
2325 dat->getBracketsRange());
2326 break;
2327 }
2328
2329 // Turn incomplete types into [*] types.
2330 case Type::IncompleteArray: {
2331 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2332 result = getVariableArrayType(
2333 getVariableArrayDecayedType(iat->getElementType()),
2334 /*size*/ 0,
2335 ArrayType::Normal,
2336 iat->getIndexTypeCVRQualifiers(),
2337 SourceRange());
2338 break;
2339 }
2340
2341 // Turn VLA types into [*] types.
2342 case Type::VariableArray: {
2343 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2344 result = getVariableArrayType(
2345 getVariableArrayDecayedType(vat->getElementType()),
2346 /*size*/ 0,
2347 ArrayType::Star,
2348 vat->getIndexTypeCVRQualifiers(),
2349 vat->getBracketsRange());
2350 break;
2351 }
2352 }
2353
2354 // Apply the top-level qualifiers from the original.
John McCall200fa532012-02-08 00:46:36 +00002355 return getQualifiedType(result, split.Quals);
John McCallce889032011-01-18 08:40:38 +00002356}
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002357
Steve Naroffbdbf7b02007-08-30 18:14:25 +00002358/// getVariableArrayType - Returns a non-unique reference to the type for a
2359/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002360QualType ASTContext::getVariableArrayType(QualType EltTy,
2361 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00002362 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002363 unsigned IndexTypeQuals,
Jay Foad4ba2a172011-01-12 09:06:06 +00002364 SourceRange Brackets) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00002365 // Since we don't unique expressions, it isn't possible to unique VLA's
2366 // that have an expression provided for their size.
John McCall3b657512011-01-19 10:06:00 +00002367 QualType Canon;
Douglas Gregor715e9c82010-05-23 16:10:32 +00002368
John McCall3b657512011-01-19 10:06:00 +00002369 // Be sure to pull qualifiers off the element type.
2370 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2371 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00002372 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002373 IndexTypeQuals, Brackets);
John McCall200fa532012-02-08 00:46:36 +00002374 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor715e9c82010-05-23 16:10:32 +00002375 }
2376
John McCall6b304a02009-09-24 23:30:46 +00002377 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002378 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002379
2380 VariableArrayTypes.push_back(New);
2381 Types.push_back(New);
2382 return QualType(New, 0);
2383}
2384
Douglas Gregor898574e2008-12-05 23:32:09 +00002385/// getDependentSizedArrayType - Returns a non-unique reference to
2386/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00002387/// type.
John McCall3b657512011-01-19 10:06:00 +00002388QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2389 Expr *numElements,
Douglas Gregor898574e2008-12-05 23:32:09 +00002390 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00002391 unsigned elementTypeQuals,
2392 SourceRange brackets) const {
2393 assert((!numElements || numElements->isTypeDependent() ||
2394 numElements->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00002395 "Size must be type- or value-dependent!");
2396
John McCall3b657512011-01-19 10:06:00 +00002397 // Dependently-sized array types that do not have a specified number
2398 // of elements will have their sizes deduced from a dependent
2399 // initializer. We do no canonicalization here at all, which is okay
2400 // because they can't be used in most locations.
2401 if (!numElements) {
2402 DependentSizedArrayType *newType
2403 = new (*this, TypeAlignment)
2404 DependentSizedArrayType(*this, elementType, QualType(),
2405 numElements, ASM, elementTypeQuals,
2406 brackets);
2407 Types.push_back(newType);
2408 return QualType(newType, 0);
2409 }
2410
2411 // Otherwise, we actually build a new type every time, but we
2412 // also build a canonical type.
2413
2414 SplitQualType canonElementType = getCanonicalType(elementType).split();
2415
2416 void *insertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00002417 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00002418 DependentSizedArrayType::Profile(ID, *this,
John McCall200fa532012-02-08 00:46:36 +00002419 QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002420 ASM, elementTypeQuals, numElements);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002421
John McCall3b657512011-01-19 10:06:00 +00002422 // Look for an existing type with these properties.
2423 DependentSizedArrayType *canonTy =
2424 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002425
John McCall3b657512011-01-19 10:06:00 +00002426 // If we don't have one, build one.
2427 if (!canonTy) {
2428 canonTy = new (*this, TypeAlignment)
John McCall200fa532012-02-08 00:46:36 +00002429 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002430 QualType(), numElements, ASM, elementTypeQuals,
2431 brackets);
2432 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2433 Types.push_back(canonTy);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002434 }
2435
John McCall3b657512011-01-19 10:06:00 +00002436 // Apply qualifiers from the element type to the array.
2437 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall200fa532012-02-08 00:46:36 +00002438 canonElementType.Quals);
Mike Stump1eb44332009-09-09 15:08:12 +00002439
John McCall3b657512011-01-19 10:06:00 +00002440 // If we didn't need extra canonicalization for the element type,
2441 // then just use that as our result.
John McCall200fa532012-02-08 00:46:36 +00002442 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall3b657512011-01-19 10:06:00 +00002443 return canon;
2444
2445 // Otherwise, we need to build a type which follows the spelling
2446 // of the element type.
2447 DependentSizedArrayType *sugaredType
2448 = new (*this, TypeAlignment)
2449 DependentSizedArrayType(*this, elementType, canon, numElements,
2450 ASM, elementTypeQuals, brackets);
2451 Types.push_back(sugaredType);
2452 return QualType(sugaredType, 0);
Douglas Gregor898574e2008-12-05 23:32:09 +00002453}
2454
John McCall3b657512011-01-19 10:06:00 +00002455QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanc5773c42008-02-15 18:16:39 +00002456 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00002457 unsigned elementTypeQuals) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00002458 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00002459 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002460
John McCall3b657512011-01-19 10:06:00 +00002461 void *insertPos = 0;
2462 if (IncompleteArrayType *iat =
2463 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2464 return QualType(iat, 0);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002465
2466 // If the element type isn't canonical, this won't be a canonical type
John McCall3b657512011-01-19 10:06:00 +00002467 // either, so fill in the canonical type field. We also have to pull
2468 // qualifiers off the element type.
2469 QualType canon;
Eli Friedmanc5773c42008-02-15 18:16:39 +00002470
John McCall3b657512011-01-19 10:06:00 +00002471 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2472 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall200fa532012-02-08 00:46:36 +00002473 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002474 ASM, elementTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00002475 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002476
2477 // Get the new insert position for the node we care about.
John McCall3b657512011-01-19 10:06:00 +00002478 IncompleteArrayType *existing =
2479 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2480 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00002481 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00002482
John McCall3b657512011-01-19 10:06:00 +00002483 IncompleteArrayType *newType = new (*this, TypeAlignment)
2484 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002485
John McCall3b657512011-01-19 10:06:00 +00002486 IncompleteArrayTypes.InsertNode(newType, insertPos);
2487 Types.push_back(newType);
2488 return QualType(newType, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00002489}
2490
Steve Naroff73322922007-07-18 18:00:27 +00002491/// getVectorType - Return the unique reference to a vector type of
2492/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00002493QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad4ba2a172011-01-12 09:06:06 +00002494 VectorType::VectorKind VecKind) const {
John McCall3b657512011-01-19 10:06:00 +00002495 assert(vecType->isBuiltinType());
Mike Stump1eb44332009-09-09 15:08:12 +00002496
Reid Spencer5f016e22007-07-11 17:01:13 +00002497 // Check if we've already instantiated a vector of this type.
2498 llvm::FoldingSetNodeID ID;
Bob Wilsone86d78c2010-11-10 21:56:12 +00002499 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner788b0fd2010-06-23 06:00:24 +00002500
Reid Spencer5f016e22007-07-11 17:01:13 +00002501 void *InsertPos = 0;
2502 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2503 return QualType(VTP, 0);
2504
2505 // If the element type isn't canonical, this won't be a canonical type either,
2506 // so fill in the canonical type field.
2507 QualType Canonical;
Douglas Gregor255210e2010-08-06 10:14:59 +00002508 if (!vecType.isCanonical()) {
Bob Wilson231da7e2010-11-16 00:32:20 +00002509 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump1eb44332009-09-09 15:08:12 +00002510
Reid Spencer5f016e22007-07-11 17:01:13 +00002511 // Get the new insert position for the node we care about.
2512 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002513 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002514 }
John McCall6b304a02009-09-24 23:30:46 +00002515 VectorType *New = new (*this, TypeAlignment)
Bob Wilsone86d78c2010-11-10 21:56:12 +00002516 VectorType(vecType, NumElts, Canonical, VecKind);
Reid Spencer5f016e22007-07-11 17:01:13 +00002517 VectorTypes.InsertNode(New, InsertPos);
2518 Types.push_back(New);
2519 return QualType(New, 0);
2520}
2521
Nate Begeman213541a2008-04-18 23:10:10 +00002522/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00002523/// the specified element type and size. VectorType must be a built-in type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002524QualType
2525ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor4ac01402011-06-15 16:02:29 +00002526 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump1eb44332009-09-09 15:08:12 +00002527
Steve Naroff73322922007-07-18 18:00:27 +00002528 // Check if we've already instantiated a vector of this type.
2529 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00002530 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsone86d78c2010-11-10 21:56:12 +00002531 VectorType::GenericVector);
Steve Naroff73322922007-07-18 18:00:27 +00002532 void *InsertPos = 0;
2533 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2534 return QualType(VTP, 0);
2535
2536 // If the element type isn't canonical, this won't be a canonical type either,
2537 // so fill in the canonical type field.
2538 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002539 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00002540 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00002541
Steve Naroff73322922007-07-18 18:00:27 +00002542 // Get the new insert position for the node we care about.
2543 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002544 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00002545 }
John McCall6b304a02009-09-24 23:30:46 +00002546 ExtVectorType *New = new (*this, TypeAlignment)
2547 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00002548 VectorTypes.InsertNode(New, InsertPos);
2549 Types.push_back(New);
2550 return QualType(New, 0);
2551}
2552
Jay Foad4ba2a172011-01-12 09:06:06 +00002553QualType
2554ASTContext::getDependentSizedExtVectorType(QualType vecType,
2555 Expr *SizeExpr,
2556 SourceLocation AttrLoc) const {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002557 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00002558 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002559 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002560
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002561 void *InsertPos = 0;
2562 DependentSizedExtVectorType *Canon
2563 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2564 DependentSizedExtVectorType *New;
2565 if (Canon) {
2566 // We already have a canonical version of this array type; use it as
2567 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00002568 New = new (*this, TypeAlignment)
2569 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2570 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002571 } else {
2572 QualType CanonVecTy = getCanonicalType(vecType);
2573 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00002574 New = new (*this, TypeAlignment)
2575 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2576 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002577
2578 DependentSizedExtVectorType *CanonCheck
2579 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2580 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2581 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002582 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2583 } else {
2584 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2585 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00002586 New = new (*this, TypeAlignment)
2587 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002588 }
2589 }
Mike Stump1eb44332009-09-09 15:08:12 +00002590
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00002591 Types.push_back(New);
2592 return QualType(New, 0);
2593}
2594
Douglas Gregor72564e72009-02-26 23:50:07 +00002595/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00002596///
Jay Foad4ba2a172011-01-12 09:06:06 +00002597QualType
2598ASTContext::getFunctionNoProtoType(QualType ResultTy,
2599 const FunctionType::ExtInfo &Info) const {
Roman Divackycfe9af22011-03-01 17:40:53 +00002600 const CallingConv DefaultCC = Info.getCC();
2601 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2602 CC_X86StdCall : DefaultCC;
Reid Spencer5f016e22007-07-11 17:01:13 +00002603 // Unique functions, to guarantee there is only one function of a particular
2604 // structure.
2605 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00002606 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00002607
Reid Spencer5f016e22007-07-11 17:01:13 +00002608 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002609 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00002610 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002611 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002612
Reid Spencer5f016e22007-07-11 17:01:13 +00002613 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00002614 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00002615 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00002616 Canonical =
2617 getFunctionNoProtoType(getCanonicalType(ResultTy),
2618 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump1eb44332009-09-09 15:08:12 +00002619
Reid Spencer5f016e22007-07-11 17:01:13 +00002620 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002621 FunctionNoProtoType *NewIP =
2622 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002623 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002624 }
Mike Stump1eb44332009-09-09 15:08:12 +00002625
Roman Divackycfe9af22011-03-01 17:40:53 +00002626 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall6b304a02009-09-24 23:30:46 +00002627 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divackycfe9af22011-03-01 17:40:53 +00002628 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00002629 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00002630 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002631 return QualType(New, 0);
2632}
2633
Douglas Gregor02dd7982013-01-17 23:36:45 +00002634/// \brief Determine whether \p T is canonical as the result type of a function.
2635static bool isCanonicalResultType(QualType T) {
2636 return T.isCanonical() &&
2637 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2638 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2639}
2640
Reid Spencer5f016e22007-07-11 17:01:13 +00002641/// getFunctionType - Return a normal function type with a typed argument
2642/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad4ba2a172011-01-12 09:06:06 +00002643QualType
Jordan Rosebea522f2013-03-08 21:51:21 +00002644ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad4ba2a172011-01-12 09:06:06 +00002645 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rosebea522f2013-03-08 21:51:21 +00002646 size_t NumArgs = ArgArray.size();
2647
Reid Spencer5f016e22007-07-11 17:01:13 +00002648 // Unique functions, to guarantee there is only one function of a particular
2649 // structure.
2650 llvm::FoldingSetNodeID ID;
Jordan Rosebea522f2013-03-08 21:51:21 +00002651 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
2652 *this);
Reid Spencer5f016e22007-07-11 17:01:13 +00002653
2654 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002655 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00002656 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002657 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00002658
2659 // Determine whether the type being created is already canonical or not.
Richard Smitheefb3d52012-02-10 09:58:53 +00002660 bool isCanonical =
Douglas Gregor02dd7982013-01-17 23:36:45 +00002661 EPI.ExceptionSpecType == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smitheefb3d52012-02-10 09:58:53 +00002662 !EPI.HasTrailingReturn;
Reid Spencer5f016e22007-07-11 17:01:13 +00002663 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002664 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00002665 isCanonical = false;
2666
Roman Divackycfe9af22011-03-01 17:40:53 +00002667 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2668 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2669 CC_X86StdCall : DefaultCC;
John McCalle23cf432010-12-14 08:05:40 +00002670
Reid Spencer5f016e22007-07-11 17:01:13 +00002671 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00002672 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002673 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00002674 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002675 SmallVector<QualType, 16> CanonicalArgs;
Reid Spencer5f016e22007-07-11 17:01:13 +00002676 CanonicalArgs.reserve(NumArgs);
2677 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002678 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00002679
John McCalle23cf432010-12-14 08:05:40 +00002680 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smitheefb3d52012-02-10 09:58:53 +00002681 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002682 CanonicalEPI.ExceptionSpecType = EST_None;
2683 CanonicalEPI.NumExceptions = 0;
John McCalle23cf432010-12-14 08:05:40 +00002684 CanonicalEPI.ExtInfo
2685 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2686
Douglas Gregor02dd7982013-01-17 23:36:45 +00002687 // Result types do not have ARC lifetime qualifiers.
2688 QualType CanResultTy = getCanonicalType(ResultTy);
2689 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2690 Qualifiers Qs = CanResultTy.getQualifiers();
2691 Qs.removeObjCLifetime();
2692 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2693 }
2694
Jordan Rosebea522f2013-03-08 21:51:21 +00002695 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl465226e2009-05-27 22:11:52 +00002696
Reid Spencer5f016e22007-07-11 17:01:13 +00002697 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002698 FunctionProtoType *NewIP =
2699 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002700 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002701 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002702
John McCallf85e1932011-06-15 23:02:42 +00002703 // FunctionProtoType objects are allocated with extra bytes after
2704 // them for three variable size arrays at the end:
2705 // - parameter types
2706 // - exception types
2707 // - consumed-arguments flags
2708 // Instead of the exception types, there could be a noexcept
Richard Smithb9d0b762012-07-27 04:22:15 +00002709 // expression, or information used to resolve the exception
2710 // specification.
John McCalle23cf432010-12-14 08:05:40 +00002711 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redl60618fa2011-03-12 11:50:43 +00002712 NumArgs * sizeof(QualType);
Richard Smithb9d0b762012-07-27 04:22:15 +00002713 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redl60618fa2011-03-12 11:50:43 +00002714 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithb9d0b762012-07-27 04:22:15 +00002715 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002716 Size += sizeof(Expr*);
Richard Smithe6975e92012-04-17 00:58:00 +00002717 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smith13bffc52012-04-19 00:08:28 +00002718 Size += 2 * sizeof(FunctionDecl*);
Richard Smithb9d0b762012-07-27 04:22:15 +00002719 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2720 Size += sizeof(FunctionDecl*);
Sebastian Redl60618fa2011-03-12 11:50:43 +00002721 }
John McCallf85e1932011-06-15 23:02:42 +00002722 if (EPI.ConsumedArguments)
2723 Size += NumArgs * sizeof(bool);
2724
John McCalle23cf432010-12-14 08:05:40 +00002725 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divackycfe9af22011-03-01 17:40:53 +00002726 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2727 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Jordan Rosebea522f2013-03-08 21:51:21 +00002728 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00002729 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00002730 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002731 return QualType(FTP, 0);
2732}
2733
John McCall3cb0ebd2010-03-10 03:28:59 +00002734#ifndef NDEBUG
2735static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2736 if (!isa<CXXRecordDecl>(D)) return false;
2737 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2738 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2739 return true;
2740 if (RD->getDescribedClassTemplate() &&
2741 !isa<ClassTemplateSpecializationDecl>(RD))
2742 return true;
2743 return false;
2744}
2745#endif
2746
2747/// getInjectedClassNameType - Return the unique reference to the
2748/// injected class name type for the specified templated declaration.
2749QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00002750 QualType TST) const {
John McCall3cb0ebd2010-03-10 03:28:59 +00002751 assert(NeedsInjectedClassNameType(Decl));
2752 if (Decl->TypeForDecl) {
2753 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregoref96ee02012-01-14 16:38:05 +00002754 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00002755 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2756 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2757 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2758 } else {
John McCallf4c73712011-01-19 06:33:43 +00002759 Type *newType =
John McCall31f17ec2010-04-27 00:57:59 +00002760 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCallf4c73712011-01-19 06:33:43 +00002761 Decl->TypeForDecl = newType;
2762 Types.push_back(newType);
John McCall3cb0ebd2010-03-10 03:28:59 +00002763 }
2764 return QualType(Decl->TypeForDecl, 0);
2765}
2766
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002767/// getTypeDeclType - Return the unique reference to the type for the
2768/// specified type declaration.
Jay Foad4ba2a172011-01-12 09:06:06 +00002769QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00002770 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00002771 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00002772
Richard Smith162e1c12011-04-15 14:24:37 +00002773 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002774 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00002775
John McCallbecb8d52010-03-10 06:48:02 +00002776 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2777 "Template type parameter types are always available.");
2778
John McCall19c85762010-02-16 03:57:14 +00002779 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002780 assert(!Record->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002781 "struct/union has previous declaration");
2782 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002783 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00002784 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002785 assert(!Enum->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002786 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002787 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00002788 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00002789 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCallf4c73712011-01-19 06:33:43 +00002790 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2791 Decl->TypeForDecl = newType;
2792 Types.push_back(newType);
Mike Stump9fdbab32009-07-31 02:02:20 +00002793 } else
John McCallbecb8d52010-03-10 06:48:02 +00002794 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002795
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002796 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002797}
2798
Reid Spencer5f016e22007-07-11 17:01:13 +00002799/// getTypedefType - Return the unique reference to the type for the
Richard Smith162e1c12011-04-15 14:24:37 +00002800/// specified typedef name decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002801QualType
Richard Smith162e1c12011-04-15 14:24:37 +00002802ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2803 QualType Canonical) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002804 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002805
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002806 if (Canonical.isNull())
2807 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCallf4c73712011-01-19 06:33:43 +00002808 TypedefType *newType = new(*this, TypeAlignment)
John McCall6b304a02009-09-24 23:30:46 +00002809 TypedefType(Type::Typedef, Decl, Canonical);
John McCallf4c73712011-01-19 06:33:43 +00002810 Decl->TypeForDecl = newType;
2811 Types.push_back(newType);
2812 return QualType(newType, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002813}
2814
Jay Foad4ba2a172011-01-12 09:06:06 +00002815QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002816 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2817
Douglas Gregoref96ee02012-01-14 16:38:05 +00002818 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002819 if (PrevDecl->TypeForDecl)
2820 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2821
John McCallf4c73712011-01-19 06:33:43 +00002822 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2823 Decl->TypeForDecl = newType;
2824 Types.push_back(newType);
2825 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002826}
2827
Jay Foad4ba2a172011-01-12 09:06:06 +00002828QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002829 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2830
Douglas Gregoref96ee02012-01-14 16:38:05 +00002831 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002832 if (PrevDecl->TypeForDecl)
2833 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2834
John McCallf4c73712011-01-19 06:33:43 +00002835 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2836 Decl->TypeForDecl = newType;
2837 Types.push_back(newType);
2838 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002839}
2840
John McCall9d156a72011-01-06 01:58:22 +00002841QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2842 QualType modifiedType,
2843 QualType equivalentType) {
2844 llvm::FoldingSetNodeID id;
2845 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2846
2847 void *insertPos = 0;
2848 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2849 if (type) return QualType(type, 0);
2850
2851 QualType canon = getCanonicalType(equivalentType);
2852 type = new (*this, TypeAlignment)
2853 AttributedType(canon, attrKind, modifiedType, equivalentType);
2854
2855 Types.push_back(type);
2856 AttributedTypes.InsertNode(type, insertPos);
2857
2858 return QualType(type, 0);
2859}
2860
2861
John McCall49a832b2009-10-18 09:09:24 +00002862/// \brief Retrieve a substitution-result type.
2863QualType
2864ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad4ba2a172011-01-12 09:06:06 +00002865 QualType Replacement) const {
John McCall467b27b2009-10-22 20:10:53 +00002866 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00002867 && "replacement types must always be canonical");
2868
2869 llvm::FoldingSetNodeID ID;
2870 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2871 void *InsertPos = 0;
2872 SubstTemplateTypeParmType *SubstParm
2873 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2874
2875 if (!SubstParm) {
2876 SubstParm = new (*this, TypeAlignment)
2877 SubstTemplateTypeParmType(Parm, Replacement);
2878 Types.push_back(SubstParm);
2879 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2880 }
2881
2882 return QualType(SubstParm, 0);
2883}
2884
Douglas Gregorc3069d62011-01-14 02:55:32 +00002885/// \brief Retrieve a
2886QualType ASTContext::getSubstTemplateTypeParmPackType(
2887 const TemplateTypeParmType *Parm,
2888 const TemplateArgument &ArgPack) {
2889#ifndef NDEBUG
2890 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2891 PEnd = ArgPack.pack_end();
2892 P != PEnd; ++P) {
2893 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2894 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2895 }
2896#endif
2897
2898 llvm::FoldingSetNodeID ID;
2899 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2900 void *InsertPos = 0;
2901 if (SubstTemplateTypeParmPackType *SubstParm
2902 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2903 return QualType(SubstParm, 0);
2904
2905 QualType Canon;
2906 if (!Parm->isCanonicalUnqualified()) {
2907 Canon = getCanonicalType(QualType(Parm, 0));
2908 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2909 ArgPack);
2910 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2911 }
2912
2913 SubstTemplateTypeParmPackType *SubstParm
2914 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2915 ArgPack);
2916 Types.push_back(SubstParm);
2917 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2918 return QualType(SubstParm, 0);
2919}
2920
Douglas Gregorfab9d672009-02-05 23:33:38 +00002921/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00002922/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002923/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00002924QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002925 bool ParameterPack,
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002926 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregorfab9d672009-02-05 23:33:38 +00002927 llvm::FoldingSetNodeID ID;
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002928 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002929 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002930 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00002931 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2932
2933 if (TypeParm)
2934 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002935
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002936 if (TTPDecl) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002937 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002938 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002939
2940 TemplateTypeParmType *TypeCheck
2941 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2942 assert(!TypeCheck && "Template type parameter canonical type broken");
2943 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002944 } else
John McCall6b304a02009-09-24 23:30:46 +00002945 TypeParm = new (*this, TypeAlignment)
2946 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002947
2948 Types.push_back(TypeParm);
2949 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2950
2951 return QualType(TypeParm, 0);
2952}
2953
John McCall3cb0ebd2010-03-10 03:28:59 +00002954TypeSourceInfo *
2955ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2956 SourceLocation NameLoc,
2957 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002958 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002959 assert(!Name.getAsDependentTemplateName() &&
2960 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00002961 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCall3cb0ebd2010-03-10 03:28:59 +00002962
2963 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie39e6ab42013-02-18 22:06:02 +00002964 TemplateSpecializationTypeLoc TL =
2965 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara55d23c92012-02-06 14:41:24 +00002966 TL.setTemplateKeywordLoc(SourceLocation());
John McCall3cb0ebd2010-03-10 03:28:59 +00002967 TL.setTemplateNameLoc(NameLoc);
2968 TL.setLAngleLoc(Args.getLAngleLoc());
2969 TL.setRAngleLoc(Args.getRAngleLoc());
2970 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2971 TL.setArgLocInfo(i, Args[i].getLocInfo());
2972 return DI;
2973}
2974
Mike Stump1eb44332009-09-09 15:08:12 +00002975QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00002976ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00002977 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002978 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002979 assert(!Template.getAsDependentTemplateName() &&
2980 "No dependent template names here!");
2981
John McCalld5532b62009-11-23 01:53:49 +00002982 unsigned NumArgs = Args.size();
2983
Chris Lattner5f9e2722011-07-23 10:55:15 +00002984 SmallVector<TemplateArgument, 4> ArgVec;
John McCall833ca992009-10-29 08:12:44 +00002985 ArgVec.reserve(NumArgs);
2986 for (unsigned i = 0; i != NumArgs; ++i)
2987 ArgVec.push_back(Args[i].getArgument());
2988
John McCall31f17ec2010-04-27 00:57:59 +00002989 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002990 Underlying);
John McCall833ca992009-10-29 08:12:44 +00002991}
2992
Douglas Gregorb70126a2012-02-03 17:16:23 +00002993#ifndef NDEBUG
2994static bool hasAnyPackExpansions(const TemplateArgument *Args,
2995 unsigned NumArgs) {
2996 for (unsigned I = 0; I != NumArgs; ++I)
2997 if (Args[I].isPackExpansion())
2998 return true;
2999
3000 return true;
3001}
3002#endif
3003
John McCall833ca992009-10-29 08:12:44 +00003004QualType
3005ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003006 const TemplateArgument *Args,
3007 unsigned NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003008 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003009 assert(!Template.getAsDependentTemplateName() &&
3010 "No dependent template names here!");
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00003011 // Look through qualified template names.
3012 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3013 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003014
Douglas Gregorb70126a2012-02-03 17:16:23 +00003015 bool IsTypeAlias =
Richard Smith3e4c6c42011-05-05 21:57:07 +00003016 Template.getAsTemplateDecl() &&
3017 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00003018 QualType CanonType;
3019 if (!Underlying.isNull())
3020 CanonType = getCanonicalType(Underlying);
3021 else {
Douglas Gregorb70126a2012-02-03 17:16:23 +00003022 // We can get here with an alias template when the specialization contains
3023 // a pack expansion that does not match up with a parameter pack.
3024 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3025 "Caller must compute aliased type");
3026 IsTypeAlias = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00003027 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3028 NumArgs);
3029 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00003030
Douglas Gregor1275ae02009-07-28 23:00:59 +00003031 // Allocate the (non-canonical) template specialization type, but don't
3032 // try to unique it: these types typically have location information that
3033 // we don't unique and don't want to lose.
Richard Smith3e4c6c42011-05-05 21:57:07 +00003034 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3035 sizeof(TemplateArgument) * NumArgs +
Douglas Gregorb70126a2012-02-03 17:16:23 +00003036 (IsTypeAlias? sizeof(QualType) : 0),
John McCall6b304a02009-09-24 23:30:46 +00003037 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00003038 TemplateSpecializationType *Spec
Douglas Gregorb70126a2012-02-03 17:16:23 +00003039 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3040 IsTypeAlias ? Underlying : QualType());
Mike Stump1eb44332009-09-09 15:08:12 +00003041
Douglas Gregor55f6b142009-02-09 18:46:07 +00003042 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00003043 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00003044}
3045
Mike Stump1eb44332009-09-09 15:08:12 +00003046QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003047ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3048 const TemplateArgument *Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00003049 unsigned NumArgs) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003050 assert(!Template.getAsDependentTemplateName() &&
3051 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00003052
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00003053 // Look through qualified template names.
3054 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3055 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003056
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003057 // Build the canonical template specialization type.
3058 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003059 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003060 CanonArgs.reserve(NumArgs);
3061 for (unsigned I = 0; I != NumArgs; ++I)
3062 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3063
3064 // Determine whether this canonical template specialization type already
3065 // exists.
3066 llvm::FoldingSetNodeID ID;
3067 TemplateSpecializationType::Profile(ID, CanonTemplate,
3068 CanonArgs.data(), NumArgs, *this);
3069
3070 void *InsertPos = 0;
3071 TemplateSpecializationType *Spec
3072 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3073
3074 if (!Spec) {
3075 // Allocate a new canonical template specialization type.
3076 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3077 sizeof(TemplateArgument) * NumArgs),
3078 TypeAlignment);
3079 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3080 CanonArgs.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003081 QualType(), QualType());
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003082 Types.push_back(Spec);
3083 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3084 }
3085
3086 assert(Spec->isDependentType() &&
3087 "Non-dependent template-id type must have a canonical type");
3088 return QualType(Spec, 0);
3089}
3090
3091QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003092ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3093 NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00003094 QualType NamedType) const {
Douglas Gregore4e5b052009-03-19 00:18:19 +00003095 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003096 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003097
3098 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003099 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003100 if (T)
3101 return QualType(T, 0);
3102
Douglas Gregor789b1f62010-02-04 18:10:26 +00003103 QualType Canon = NamedType;
3104 if (!Canon.isCanonical()) {
3105 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003106 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3107 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00003108 (void)CheckT;
3109 }
3110
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003111 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003112 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003113 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003114 return QualType(T, 0);
3115}
3116
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003117QualType
Jay Foad4ba2a172011-01-12 09:06:06 +00003118ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003119 llvm::FoldingSetNodeID ID;
3120 ParenType::Profile(ID, InnerType);
3121
3122 void *InsertPos = 0;
3123 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3124 if (T)
3125 return QualType(T, 0);
3126
3127 QualType Canon = InnerType;
3128 if (!Canon.isCanonical()) {
3129 Canon = getCanonicalType(InnerType);
3130 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3131 assert(!CheckT && "Paren canonical type broken");
3132 (void)CheckT;
3133 }
3134
3135 T = new (*this) ParenType(InnerType, Canon);
3136 Types.push_back(T);
3137 ParenTypes.InsertNode(T, InsertPos);
3138 return QualType(T, 0);
3139}
3140
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003141QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3142 NestedNameSpecifier *NNS,
3143 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00003144 QualType Canon) const {
Douglas Gregord57959a2009-03-27 23:10:48 +00003145 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
3146
3147 if (Canon.isNull()) {
3148 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003149 ElaboratedTypeKeyword CanonKeyword = Keyword;
3150 if (Keyword == ETK_None)
3151 CanonKeyword = ETK_Typename;
3152
3153 if (CanonNNS != NNS || CanonKeyword != Keyword)
3154 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00003155 }
3156
3157 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003158 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00003159
3160 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00003161 DependentNameType *T
3162 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00003163 if (T)
3164 return QualType(T, 0);
3165
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003166 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00003167 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00003168 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00003169 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00003170}
3171
Mike Stump1eb44332009-09-09 15:08:12 +00003172QualType
John McCall33500952010-06-11 00:33:02 +00003173ASTContext::getDependentTemplateSpecializationType(
3174 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003175 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00003176 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00003177 const TemplateArgumentListInfo &Args) const {
John McCall33500952010-06-11 00:33:02 +00003178 // TODO: avoid this copy
Chris Lattner5f9e2722011-07-23 10:55:15 +00003179 SmallVector<TemplateArgument, 16> ArgCopy;
John McCall33500952010-06-11 00:33:02 +00003180 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3181 ArgCopy.push_back(Args[I].getArgument());
3182 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3183 ArgCopy.size(),
3184 ArgCopy.data());
3185}
3186
3187QualType
3188ASTContext::getDependentTemplateSpecializationType(
3189 ElaboratedTypeKeyword Keyword,
3190 NestedNameSpecifier *NNS,
3191 const IdentifierInfo *Name,
3192 unsigned NumArgs,
Jay Foad4ba2a172011-01-12 09:06:06 +00003193 const TemplateArgument *Args) const {
Douglas Gregoraa2187d2011-02-28 00:04:36 +00003194 assert((!NNS || NNS->isDependent()) &&
3195 "nested-name-specifier must be dependent");
Douglas Gregor17343172009-04-01 00:28:59 +00003196
Douglas Gregor789b1f62010-02-04 18:10:26 +00003197 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00003198 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3199 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003200
3201 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00003202 DependentTemplateSpecializationType *T
3203 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003204 if (T)
3205 return QualType(T, 0);
3206
John McCall33500952010-06-11 00:33:02 +00003207 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003208
John McCall33500952010-06-11 00:33:02 +00003209 ElaboratedTypeKeyword CanonKeyword = Keyword;
3210 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3211
3212 bool AnyNonCanonArgs = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003213 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCall33500952010-06-11 00:33:02 +00003214 for (unsigned I = 0; I != NumArgs; ++I) {
3215 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3216 if (!CanonArgs[I].structurallyEquals(Args[I]))
3217 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00003218 }
3219
John McCall33500952010-06-11 00:33:02 +00003220 QualType Canon;
3221 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3222 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3223 Name, NumArgs,
3224 CanonArgs.data());
3225
3226 // Find the insert position again.
3227 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3228 }
3229
3230 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3231 sizeof(TemplateArgument) * NumArgs),
3232 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00003233 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00003234 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00003235 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00003236 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00003237 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00003238}
3239
Douglas Gregorcded4f62011-01-14 17:04:44 +00003240QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikiedc84cd52013-02-20 22:23:23 +00003241 Optional<unsigned> NumExpansions) {
Douglas Gregor7536dd52010-12-20 02:24:11 +00003242 llvm::FoldingSetNodeID ID;
Douglas Gregorcded4f62011-01-14 17:04:44 +00003243 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003244
3245 assert(Pattern->containsUnexpandedParameterPack() &&
3246 "Pack expansions must expand one or more parameter packs");
3247 void *InsertPos = 0;
3248 PackExpansionType *T
3249 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3250 if (T)
3251 return QualType(T, 0);
3252
3253 QualType Canon;
3254 if (!Pattern.isCanonical()) {
Richard Smithd8672ef2012-07-16 00:20:35 +00003255 Canon = getCanonicalType(Pattern);
3256 // The canonical type might not contain an unexpanded parameter pack, if it
3257 // contains an alias template specialization which ignores one of its
3258 // parameters.
3259 if (Canon->containsUnexpandedParameterPack()) {
3260 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003261
Richard Smithd8672ef2012-07-16 00:20:35 +00003262 // Find the insert position again, in case we inserted an element into
3263 // PackExpansionTypes and invalidated our insert position.
3264 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3265 }
Douglas Gregor7536dd52010-12-20 02:24:11 +00003266 }
3267
Douglas Gregorcded4f62011-01-14 17:04:44 +00003268 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003269 Types.push_back(T);
3270 PackExpansionTypes.InsertNode(T, InsertPos);
3271 return QualType(T, 0);
3272}
3273
Chris Lattner88cb27a2008-04-07 04:56:42 +00003274/// CmpProtocolNames - Comparison predicate for sorting protocols
3275/// alphabetically.
3276static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3277 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003278 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00003279}
3280
John McCallc12c5bb2010-05-15 11:32:37 +00003281static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00003282 unsigned NumProtocols) {
3283 if (NumProtocols == 0) return true;
3284
Douglas Gregor61cc2962012-01-02 02:00:30 +00003285 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3286 return false;
3287
John McCall54e14c42009-10-22 22:37:11 +00003288 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregor61cc2962012-01-02 02:00:30 +00003289 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3290 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCall54e14c42009-10-22 22:37:11 +00003291 return false;
3292 return true;
3293}
3294
3295static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00003296 unsigned &NumProtocols) {
3297 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00003298
Chris Lattner88cb27a2008-04-07 04:56:42 +00003299 // Sort protocols, keyed by name.
3300 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3301
Douglas Gregor61cc2962012-01-02 02:00:30 +00003302 // Canonicalize.
3303 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3304 Protocols[I] = Protocols[I]->getCanonicalDecl();
3305
Chris Lattner88cb27a2008-04-07 04:56:42 +00003306 // Remove duplicates.
3307 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3308 NumProtocols = ProtocolsEnd-Protocols;
3309}
3310
John McCallc12c5bb2010-05-15 11:32:37 +00003311QualType ASTContext::getObjCObjectType(QualType BaseType,
3312 ObjCProtocolDecl * const *Protocols,
Jay Foad4ba2a172011-01-12 09:06:06 +00003313 unsigned NumProtocols) const {
John McCallc12c5bb2010-05-15 11:32:37 +00003314 // If the base type is an interface and there aren't any protocols
3315 // to add, then the interface type will do just fine.
3316 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3317 return BaseType;
3318
3319 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003320 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00003321 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003322 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00003323 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3324 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003325
John McCallc12c5bb2010-05-15 11:32:37 +00003326 // Build the canonical type, which has the canonical base type and
3327 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00003328 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00003329 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3330 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3331 if (!ProtocolsSorted) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003332 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer02379412010-04-27 17:12:11 +00003333 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00003334 unsigned UniqueCount = NumProtocols;
3335
John McCall54e14c42009-10-22 22:37:11 +00003336 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00003337 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3338 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00003339 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00003340 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3341 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00003342 }
3343
3344 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00003345 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3346 }
3347
3348 unsigned Size = sizeof(ObjCObjectTypeImpl);
3349 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3350 void *Mem = Allocate(Size, TypeAlignment);
3351 ObjCObjectTypeImpl *T =
3352 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3353
3354 Types.push_back(T);
3355 ObjCObjectTypes.InsertNode(T, InsertPos);
3356 return QualType(T, 0);
3357}
3358
3359/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3360/// the given object type.
Jay Foad4ba2a172011-01-12 09:06:06 +00003361QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCallc12c5bb2010-05-15 11:32:37 +00003362 llvm::FoldingSetNodeID ID;
3363 ObjCObjectPointerType::Profile(ID, ObjectT);
3364
3365 void *InsertPos = 0;
3366 if (ObjCObjectPointerType *QT =
3367 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3368 return QualType(QT, 0);
3369
3370 // Find the canonical object type.
3371 QualType Canonical;
3372 if (!ObjectT.isCanonical()) {
3373 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3374
3375 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00003376 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3377 }
3378
Douglas Gregorfd6a0882010-02-08 22:59:26 +00003379 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00003380 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3381 ObjCObjectPointerType *QType =
3382 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00003383
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003384 Types.push_back(QType);
3385 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00003386 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003387}
Chris Lattner88cb27a2008-04-07 04:56:42 +00003388
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003389/// getObjCInterfaceType - Return the unique reference to the type for the
3390/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregor0af55012011-12-16 03:12:41 +00003391QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3392 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003393 if (Decl->TypeForDecl)
3394 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00003395
Douglas Gregor0af55012011-12-16 03:12:41 +00003396 if (PrevDecl) {
3397 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3398 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3399 return QualType(PrevDecl->TypeForDecl, 0);
3400 }
3401
Douglas Gregor8d2dbbf2011-12-16 16:34:57 +00003402 // Prefer the definition, if there is one.
3403 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3404 Decl = Def;
3405
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003406 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3407 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3408 Decl->TypeForDecl = T;
3409 Types.push_back(T);
3410 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00003411}
3412
Douglas Gregor72564e72009-02-26 23:50:07 +00003413/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3414/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00003415/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00003416/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00003417/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00003418QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003419 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00003420 if (tofExpr->isTypeDependent()) {
3421 llvm::FoldingSetNodeID ID;
3422 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00003423
Douglas Gregorb1975722009-07-30 23:18:24 +00003424 void *InsertPos = 0;
3425 DependentTypeOfExprType *Canon
3426 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3427 if (Canon) {
3428 // We already have a "canonical" version of an identical, dependent
3429 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00003430 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00003431 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00003432 } else {
Douglas Gregorb1975722009-07-30 23:18:24 +00003433 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00003434 Canon
3435 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00003436 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3437 toe = Canon;
3438 }
3439 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003440 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00003441 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00003442 }
Steve Naroff9752f252007-08-01 18:02:17 +00003443 Types.push_back(toe);
3444 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00003445}
3446
Steve Naroff9752f252007-08-01 18:02:17 +00003447/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3448/// TypeOfType AST's. The only motivation to unique these nodes would be
3449/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00003450/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00003451/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00003452QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00003453 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00003454 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00003455 Types.push_back(tot);
3456 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00003457}
3458
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00003459
Anders Carlsson395b4752009-06-24 19:06:50 +00003460/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3461/// DecltypeType AST's. The only motivation to unique these nodes would be
3462/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00003463/// an issue. This doesn't effect the type checker, since it operates
David Blaikie39e02032011-11-06 22:28:03 +00003464/// on canonical types (which are always unique).
Douglas Gregorf8af9822012-02-12 18:42:33 +00003465QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003466 DecltypeType *dt;
Douglas Gregor561f8122011-07-01 01:22:09 +00003467
3468 // C++0x [temp.type]p2:
3469 // If an expression e involves a template parameter, decltype(e) denotes a
3470 // unique dependent type. Two such decltype-specifiers refer to the same
3471 // type only if their expressions are equivalent (14.5.6.1).
3472 if (e->isInstantiationDependent()) {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003473 llvm::FoldingSetNodeID ID;
3474 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00003475
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003476 void *InsertPos = 0;
3477 DependentDecltypeType *Canon
3478 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3479 if (Canon) {
3480 // We already have a "canonical" version of an equivalent, dependent
3481 // decltype type. Use that as our canonical type.
Richard Smith0d729102012-08-13 20:08:14 +00003482 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003483 QualType((DecltypeType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00003484 } else {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003485 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00003486 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003487 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3488 dt = Canon;
3489 }
3490 } else {
Douglas Gregorf8af9822012-02-12 18:42:33 +00003491 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3492 getCanonicalType(UnderlyingType));
Douglas Gregordd0257c2009-07-08 00:03:05 +00003493 }
Anders Carlsson395b4752009-06-24 19:06:50 +00003494 Types.push_back(dt);
3495 return QualType(dt, 0);
3496}
3497
Sean Huntca63c202011-05-24 22:41:36 +00003498/// getUnaryTransformationType - We don't unique these, since the memory
3499/// savings are minimal and these are rare.
3500QualType ASTContext::getUnaryTransformType(QualType BaseType,
3501 QualType UnderlyingType,
3502 UnaryTransformType::UTTKind Kind)
3503 const {
3504 UnaryTransformType *Ty =
Douglas Gregor69d97752011-05-25 17:51:54 +00003505 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3506 Kind,
3507 UnderlyingType->isDependentType() ?
Peter Collingbourne12fc4b02012-03-05 16:02:06 +00003508 QualType() : getCanonicalType(UnderlyingType));
Sean Huntca63c202011-05-24 22:41:36 +00003509 Types.push_back(Ty);
3510 return QualType(Ty, 0);
3511}
3512
Richard Smith483b9f32011-02-21 20:05:19 +00003513/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith34b41d92011-02-20 03:19:35 +00003514QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smith483b9f32011-02-21 20:05:19 +00003515 void *InsertPos = 0;
3516 if (!DeducedType.isNull()) {
3517 // Look in the folding set for an existing type.
3518 llvm::FoldingSetNodeID ID;
3519 AutoType::Profile(ID, DeducedType);
3520 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3521 return QualType(AT, 0);
3522 }
3523
3524 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
3525 Types.push_back(AT);
3526 if (InsertPos)
3527 AutoTypes.InsertNode(AT, InsertPos);
3528 return QualType(AT, 0);
Richard Smith34b41d92011-02-20 03:19:35 +00003529}
3530
Eli Friedmanb001de72011-10-06 23:00:33 +00003531/// getAtomicType - Return the uniqued reference to the atomic type for
3532/// the given value type.
3533QualType ASTContext::getAtomicType(QualType T) const {
3534 // Unique pointers, to guarantee there is only one pointer of a particular
3535 // structure.
3536 llvm::FoldingSetNodeID ID;
3537 AtomicType::Profile(ID, T);
3538
3539 void *InsertPos = 0;
3540 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3541 return QualType(AT, 0);
3542
3543 // If the atomic value type isn't canonical, this won't be a canonical type
3544 // either, so fill in the canonical type field.
3545 QualType Canonical;
3546 if (!T.isCanonical()) {
3547 Canonical = getAtomicType(getCanonicalType(T));
3548
3549 // Get the new insert position for the node we care about.
3550 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3551 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3552 }
3553 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3554 Types.push_back(New);
3555 AtomicTypes.InsertNode(New, InsertPos);
3556 return QualType(New, 0);
3557}
3558
Richard Smithad762fc2011-04-14 22:09:26 +00003559/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3560QualType ASTContext::getAutoDeductType() const {
3561 if (AutoDeductTy.isNull())
3562 AutoDeductTy = getAutoType(QualType());
3563 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
3564 return AutoDeductTy;
3565}
3566
3567/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3568QualType ASTContext::getAutoRRefDeductType() const {
3569 if (AutoRRefDeductTy.isNull())
3570 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3571 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3572 return AutoRRefDeductTy;
3573}
3574
Reid Spencer5f016e22007-07-11 17:01:13 +00003575/// getTagDeclType - Return the unique reference to the type for the
3576/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad4ba2a172011-01-12 09:06:06 +00003577QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenekd778f882007-11-26 21:16:01 +00003578 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00003579 // FIXME: What is the design on getTagDeclType when it requires casting
3580 // away const? mutable?
3581 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003582}
3583
Mike Stump1eb44332009-09-09 15:08:12 +00003584/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3585/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3586/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00003587CanQualType ASTContext::getSizeType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003588 return getFromTargetType(Target->getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00003589}
3590
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003591/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3592CanQualType ASTContext::getIntMaxType() const {
3593 return getFromTargetType(Target->getIntMaxType());
3594}
3595
3596/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3597CanQualType ASTContext::getUIntMaxType() const {
3598 return getFromTargetType(Target->getUIntMaxType());
3599}
3600
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00003601/// getSignedWCharType - Return the type of "signed wchar_t".
3602/// Used when in C++, as a GCC extension.
3603QualType ASTContext::getSignedWCharType() const {
3604 // FIXME: derive from "Target" ?
3605 return WCharTy;
3606}
3607
3608/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3609/// Used when in C++, as a GCC extension.
3610QualType ASTContext::getUnsignedWCharType() const {
3611 // FIXME: derive from "Target" ?
3612 return UnsignedIntTy;
3613}
3614
Enea Zaffanella9677eb82013-01-26 17:08:37 +00003615QualType ASTContext::getIntPtrType() const {
3616 return getFromTargetType(Target->getIntPtrType());
3617}
3618
3619QualType ASTContext::getUIntPtrType() const {
3620 return getCorrespondingUnsignedType(getIntPtrType());
3621}
3622
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003623/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattner8b9023b2007-07-13 03:05:23 +00003624/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3625QualType ASTContext::getPointerDiffType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003626 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00003627}
3628
Eli Friedman6902e412012-11-27 02:58:24 +00003629/// \brief Return the unique type for "pid_t" defined in
3630/// <sys/types.h>. We need this to compute the correct type for vfork().
3631QualType ASTContext::getProcessIDType() const {
3632 return getFromTargetType(Target->getProcessIDType());
3633}
3634
Chris Lattnere6327742008-04-02 05:18:44 +00003635//===----------------------------------------------------------------------===//
3636// Type Operators
3637//===----------------------------------------------------------------------===//
3638
Jay Foad4ba2a172011-01-12 09:06:06 +00003639CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCall54e14c42009-10-22 22:37:11 +00003640 // Push qualifiers into arrays, and then discard any remaining
3641 // qualifiers.
3642 T = getCanonicalType(T);
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003643 T = getVariableArrayDecayedType(T);
John McCall54e14c42009-10-22 22:37:11 +00003644 const Type *Ty = T.getTypePtr();
John McCall54e14c42009-10-22 22:37:11 +00003645 QualType Result;
3646 if (isa<ArrayType>(Ty)) {
3647 Result = getArrayDecayedType(QualType(Ty,0));
3648 } else if (isa<FunctionType>(Ty)) {
3649 Result = getPointerType(QualType(Ty, 0));
3650 } else {
3651 Result = QualType(Ty, 0);
3652 }
3653
3654 return CanQualType::CreateUnsafe(Result);
3655}
3656
John McCall62c28c82011-01-18 07:41:22 +00003657QualType ASTContext::getUnqualifiedArrayType(QualType type,
3658 Qualifiers &quals) {
3659 SplitQualType splitType = type.getSplitUnqualifiedType();
3660
3661 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3662 // the unqualified desugared type and then drops it on the floor.
3663 // We then have to strip that sugar back off with
3664 // getUnqualifiedDesugaredType(), which is silly.
3665 const ArrayType *AT =
John McCall200fa532012-02-08 00:46:36 +00003666 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall62c28c82011-01-18 07:41:22 +00003667
3668 // If we don't have an array, just use the results in splitType.
Douglas Gregor9dadd942010-05-17 18:45:21 +00003669 if (!AT) {
John McCall200fa532012-02-08 00:46:36 +00003670 quals = splitType.Quals;
3671 return QualType(splitType.Ty, 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003672 }
3673
John McCall62c28c82011-01-18 07:41:22 +00003674 // Otherwise, recurse on the array's element type.
3675 QualType elementType = AT->getElementType();
3676 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3677
3678 // If that didn't change the element type, AT has no qualifiers, so we
3679 // can just use the results in splitType.
3680 if (elementType == unqualElementType) {
3681 assert(quals.empty()); // from the recursive call
John McCall200fa532012-02-08 00:46:36 +00003682 quals = splitType.Quals;
3683 return QualType(splitType.Ty, 0);
John McCall62c28c82011-01-18 07:41:22 +00003684 }
3685
3686 // Otherwise, add in the qualifiers from the outermost type, then
3687 // build the type back up.
John McCall200fa532012-02-08 00:46:36 +00003688 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003689
Douglas Gregor9dadd942010-05-17 18:45:21 +00003690 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003691 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003692 CAT->getSizeModifier(), 0);
3693 }
3694
Douglas Gregor9dadd942010-05-17 18:45:21 +00003695 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003696 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003697 }
3698
Douglas Gregor9dadd942010-05-17 18:45:21 +00003699 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003700 return getVariableArrayType(unqualElementType,
John McCall3fa5cae2010-10-26 07:05:15 +00003701 VAT->getSizeExpr(),
Douglas Gregor9dadd942010-05-17 18:45:21 +00003702 VAT->getSizeModifier(),
3703 VAT->getIndexTypeCVRQualifiers(),
3704 VAT->getBracketsRange());
3705 }
3706
3707 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall62c28c82011-01-18 07:41:22 +00003708 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003709 DSAT->getSizeModifier(), 0,
3710 SourceRange());
3711}
3712
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003713/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3714/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3715/// they point to and return true. If T1 and T2 aren't pointer types
3716/// or pointer-to-member types, or if they are not similar at this
3717/// level, returns false and leaves T1 and T2 unchanged. Top-level
3718/// qualifiers on T1 and T2 are ignored. This function will typically
3719/// be called in a loop that successively "unwraps" pointer and
3720/// pointer-to-member types to compare them at each level.
3721bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3722 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3723 *T2PtrType = T2->getAs<PointerType>();
3724 if (T1PtrType && T2PtrType) {
3725 T1 = T1PtrType->getPointeeType();
3726 T2 = T2PtrType->getPointeeType();
3727 return true;
3728 }
3729
3730 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3731 *T2MPType = T2->getAs<MemberPointerType>();
3732 if (T1MPType && T2MPType &&
3733 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3734 QualType(T2MPType->getClass(), 0))) {
3735 T1 = T1MPType->getPointeeType();
3736 T2 = T2MPType->getPointeeType();
3737 return true;
3738 }
3739
David Blaikie4e4d0842012-03-11 07:00:24 +00003740 if (getLangOpts().ObjC1) {
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003741 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3742 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3743 if (T1OPType && T2OPType) {
3744 T1 = T1OPType->getPointeeType();
3745 T2 = T2OPType->getPointeeType();
3746 return true;
3747 }
3748 }
3749
3750 // FIXME: Block pointers, too?
3751
3752 return false;
3753}
3754
Jay Foad4ba2a172011-01-12 09:06:06 +00003755DeclarationNameInfo
3756ASTContext::getNameForTemplate(TemplateName Name,
3757 SourceLocation NameLoc) const {
John McCall14606042011-06-30 08:33:18 +00003758 switch (Name.getKind()) {
3759 case TemplateName::QualifiedTemplate:
3760 case TemplateName::Template:
Abramo Bagnara25777432010-08-11 22:01:17 +00003761 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCall14606042011-06-30 08:33:18 +00003762 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3763 NameLoc);
Abramo Bagnara25777432010-08-11 22:01:17 +00003764
John McCall14606042011-06-30 08:33:18 +00003765 case TemplateName::OverloadedTemplate: {
3766 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3767 // DNInfo work in progress: CHECKME: what about DNLoc?
3768 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3769 }
3770
3771 case TemplateName::DependentTemplate: {
3772 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnara25777432010-08-11 22:01:17 +00003773 DeclarationName DName;
John McCall80ad16f2009-11-24 18:42:40 +00003774 if (DTN->isIdentifier()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00003775 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3776 return DeclarationNameInfo(DName, NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003777 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00003778 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3779 // DNInfo work in progress: FIXME: source locations?
3780 DeclarationNameLoc DNLoc;
3781 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3782 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3783 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003784 }
3785 }
3786
John McCall14606042011-06-30 08:33:18 +00003787 case TemplateName::SubstTemplateTemplateParm: {
3788 SubstTemplateTemplateParmStorage *subst
3789 = Name.getAsSubstTemplateTemplateParm();
3790 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3791 NameLoc);
3792 }
3793
3794 case TemplateName::SubstTemplateTemplateParmPack: {
3795 SubstTemplateTemplateParmPackStorage *subst
3796 = Name.getAsSubstTemplateTemplateParmPack();
3797 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3798 NameLoc);
3799 }
3800 }
3801
3802 llvm_unreachable("bad template name kind!");
John McCall80ad16f2009-11-24 18:42:40 +00003803}
3804
Jay Foad4ba2a172011-01-12 09:06:06 +00003805TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCall14606042011-06-30 08:33:18 +00003806 switch (Name.getKind()) {
3807 case TemplateName::QualifiedTemplate:
3808 case TemplateName::Template: {
3809 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003810 if (TemplateTemplateParmDecl *TTP
John McCall14606042011-06-30 08:33:18 +00003811 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003812 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3813
3814 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00003815 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003816 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003817
John McCall14606042011-06-30 08:33:18 +00003818 case TemplateName::OverloadedTemplate:
3819 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump1eb44332009-09-09 15:08:12 +00003820
John McCall14606042011-06-30 08:33:18 +00003821 case TemplateName::DependentTemplate: {
3822 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3823 assert(DTN && "Non-dependent template names must refer to template decls.");
3824 return DTN->CanonicalTemplateName;
3825 }
3826
3827 case TemplateName::SubstTemplateTemplateParm: {
3828 SubstTemplateTemplateParmStorage *subst
3829 = Name.getAsSubstTemplateTemplateParm();
3830 return getCanonicalTemplateName(subst->getReplacement());
3831 }
3832
3833 case TemplateName::SubstTemplateTemplateParmPack: {
3834 SubstTemplateTemplateParmPackStorage *subst
3835 = Name.getAsSubstTemplateTemplateParmPack();
3836 TemplateTemplateParmDecl *canonParameter
3837 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3838 TemplateArgument canonArgPack
3839 = getCanonicalTemplateArgument(subst->getArgumentPack());
3840 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3841 }
3842 }
3843
3844 llvm_unreachable("bad template name!");
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003845}
3846
Douglas Gregordb0d4b72009-11-11 23:06:43 +00003847bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3848 X = getCanonicalTemplateName(X);
3849 Y = getCanonicalTemplateName(Y);
3850 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3851}
3852
Mike Stump1eb44332009-09-09 15:08:12 +00003853TemplateArgument
Jay Foad4ba2a172011-01-12 09:06:06 +00003854ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregor1275ae02009-07-28 23:00:59 +00003855 switch (Arg.getKind()) {
3856 case TemplateArgument::Null:
3857 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003858
Douglas Gregor1275ae02009-07-28 23:00:59 +00003859 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00003860 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003861
Douglas Gregord2008e22012-04-06 22:40:38 +00003862 case TemplateArgument::Declaration: {
Eli Friedmand7a6b162012-09-26 02:36:12 +00003863 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
3864 return TemplateArgument(D, Arg.isDeclForReferenceParam());
Douglas Gregord2008e22012-04-06 22:40:38 +00003865 }
Mike Stump1eb44332009-09-09 15:08:12 +00003866
Eli Friedmand7a6b162012-09-26 02:36:12 +00003867 case TemplateArgument::NullPtr:
3868 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
3869 /*isNullPtr*/true);
3870
Douglas Gregor788cd062009-11-11 01:00:40 +00003871 case TemplateArgument::Template:
3872 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregora7fc9012011-01-05 18:58:31 +00003873
3874 case TemplateArgument::TemplateExpansion:
3875 return TemplateArgument(getCanonicalTemplateName(
3876 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregor2be29f42011-01-14 23:41:42 +00003877 Arg.getNumTemplateExpansions());
Douglas Gregora7fc9012011-01-05 18:58:31 +00003878
Douglas Gregor1275ae02009-07-28 23:00:59 +00003879 case TemplateArgument::Integral:
Benjamin Kramer85524372012-06-07 15:09:51 +00003880 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003881
Douglas Gregor1275ae02009-07-28 23:00:59 +00003882 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00003883 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003884
Douglas Gregor1275ae02009-07-28 23:00:59 +00003885 case TemplateArgument::Pack: {
Douglas Gregor87dd6972010-12-20 16:52:59 +00003886 if (Arg.pack_size() == 0)
3887 return Arg;
3888
Douglas Gregor910f8002010-11-07 23:05:16 +00003889 TemplateArgument *CanonArgs
3890 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregor1275ae02009-07-28 23:00:59 +00003891 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003892 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00003893 AEnd = Arg.pack_end();
3894 A != AEnd; (void)++A, ++Idx)
3895 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00003896
Douglas Gregor910f8002010-11-07 23:05:16 +00003897 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregor1275ae02009-07-28 23:00:59 +00003898 }
3899 }
3900
3901 // Silence GCC warning
David Blaikieb219cfc2011-09-23 05:06:16 +00003902 llvm_unreachable("Unhandled template argument kind");
Douglas Gregor1275ae02009-07-28 23:00:59 +00003903}
3904
Douglas Gregord57959a2009-03-27 23:10:48 +00003905NestedNameSpecifier *
Jay Foad4ba2a172011-01-12 09:06:06 +00003906ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump1eb44332009-09-09 15:08:12 +00003907 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00003908 return 0;
3909
3910 switch (NNS->getKind()) {
3911 case NestedNameSpecifier::Identifier:
3912 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00003913 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00003914 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3915 NNS->getAsIdentifier());
3916
3917 case NestedNameSpecifier::Namespace:
3918 // A namespace is canonical; build a nested-name-specifier with
3919 // this namespace and no prefix.
Douglas Gregor14aba762011-02-24 02:36:08 +00003920 return NestedNameSpecifier::Create(*this, 0,
3921 NNS->getAsNamespace()->getOriginalNamespace());
3922
3923 case NestedNameSpecifier::NamespaceAlias:
3924 // A namespace is canonical; build a nested-name-specifier with
3925 // this namespace and no prefix.
3926 return NestedNameSpecifier::Create(*this, 0,
3927 NNS->getAsNamespaceAlias()->getNamespace()
3928 ->getOriginalNamespace());
Douglas Gregord57959a2009-03-27 23:10:48 +00003929
3930 case NestedNameSpecifier::TypeSpec:
3931 case NestedNameSpecifier::TypeSpecWithTemplate: {
3932 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor264bf662010-11-04 00:09:33 +00003933
3934 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3935 // break it apart into its prefix and identifier, then reconsititute those
3936 // as the canonical nested-name-specifier. This is required to canonicalize
3937 // a dependent nested-name-specifier involving typedefs of dependent-name
3938 // types, e.g.,
3939 // typedef typename T::type T1;
3940 // typedef typename T1::type T2;
Eli Friedman16412ef2012-03-03 04:09:56 +00003941 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
3942 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor264bf662010-11-04 00:09:33 +00003943 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor264bf662010-11-04 00:09:33 +00003944
Eli Friedman16412ef2012-03-03 04:09:56 +00003945 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
3946 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
3947 // first place?
John McCall3b657512011-01-19 10:06:00 +00003948 return NestedNameSpecifier::Create(*this, 0, false,
3949 const_cast<Type*>(T.getTypePtr()));
Douglas Gregord57959a2009-03-27 23:10:48 +00003950 }
3951
3952 case NestedNameSpecifier::Global:
3953 // The global specifier is canonical and unique.
3954 return NNS;
3955 }
3956
David Blaikie7530c032012-01-17 06:56:22 +00003957 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregord57959a2009-03-27 23:10:48 +00003958}
3959
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003960
Jay Foad4ba2a172011-01-12 09:06:06 +00003961const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003962 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00003963 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003964 // Handle the common positive case fast.
3965 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3966 return AT;
3967 }
Mike Stump1eb44332009-09-09 15:08:12 +00003968
John McCall0953e762009-09-24 19:53:00 +00003969 // Handle the common negative case fast.
John McCall3b657512011-01-19 10:06:00 +00003970 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003971 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003972
John McCall0953e762009-09-24 19:53:00 +00003973 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003974 // implements C99 6.7.3p8: "If the specification of an array type includes
3975 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00003976
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003977 // If we get here, we either have type qualifiers on the type, or we have
3978 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00003979 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00003980
John McCall3b657512011-01-19 10:06:00 +00003981 SplitQualType split = T.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00003982 Qualifiers qs = split.Quals;
Mike Stump1eb44332009-09-09 15:08:12 +00003983
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003984 // If we have a simple case, just return now.
John McCall200fa532012-02-08 00:46:36 +00003985 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall3b657512011-01-19 10:06:00 +00003986 if (ATy == 0 || qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003987 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00003988
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003989 // Otherwise, we have an array and we have qualifiers on it. Push the
3990 // qualifiers into the array element type and return a new array type.
John McCall3b657512011-01-19 10:06:00 +00003991 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump1eb44332009-09-09 15:08:12 +00003992
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003993 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3994 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3995 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003996 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003997 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3998 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3999 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004000 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00004001
Mike Stump1eb44332009-09-09 15:08:12 +00004002 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00004003 = dyn_cast<DependentSizedArrayType>(ATy))
4004 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00004005 getDependentSizedArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00004006 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00004007 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004008 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004009 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00004010
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004011 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004012 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00004013 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004014 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004015 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004016 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00004017}
4018
Abramo Bagnaraad9689f2012-05-17 12:44:05 +00004019QualType ASTContext::getAdjustedParameterType(QualType T) const {
Douglas Gregor79e6bd32011-07-12 04:42:08 +00004020 // C99 6.7.5.3p7:
4021 // A declaration of a parameter as "array of type" shall be
4022 // adjusted to "qualified pointer to type", where the type
4023 // qualifiers (if any) are those specified within the [ and ] of
4024 // the array type derivation.
4025 if (T->isArrayType())
4026 return getArrayDecayedType(T);
4027
4028 // C99 6.7.5.3p8:
4029 // A declaration of a parameter as "function returning type"
4030 // shall be adjusted to "pointer to function returning type", as
4031 // in 6.3.2.1.
4032 if (T->isFunctionType())
4033 return getPointerType(T);
4034
4035 return T;
4036}
4037
Abramo Bagnaraad9689f2012-05-17 12:44:05 +00004038QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor79e6bd32011-07-12 04:42:08 +00004039 T = getVariableArrayDecayedType(T);
4040 T = getAdjustedParameterType(T);
4041 return T.getUnqualifiedType();
4042}
4043
Chris Lattnere6327742008-04-02 05:18:44 +00004044/// getArrayDecayedType - Return the properly qualified result of decaying the
4045/// specified array type to a pointer. This operation is non-trivial when
4046/// handling typedefs etc. The canonical type of "T" must be an array type,
4047/// this returns a pointer to a properly qualified element of the array.
4048///
4049/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad4ba2a172011-01-12 09:06:06 +00004050QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004051 // Get the element type with 'getAsArrayType' so that we don't lose any
4052 // typedefs in the element type of the array. This also handles propagation
4053 // of type qualifiers from the array type into the element type if present
4054 // (C99 6.7.3p8).
4055 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4056 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00004057
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004058 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00004059
4060 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00004061 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00004062}
4063
John McCall3b657512011-01-19 10:06:00 +00004064QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4065 return getBaseElementType(array->getElementType());
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00004066}
4067
John McCall3b657512011-01-19 10:06:00 +00004068QualType ASTContext::getBaseElementType(QualType type) const {
4069 Qualifiers qs;
4070 while (true) {
4071 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00004072 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall3b657512011-01-19 10:06:00 +00004073 if (!array) break;
Mike Stump1eb44332009-09-09 15:08:12 +00004074
John McCall3b657512011-01-19 10:06:00 +00004075 type = array->getElementType();
John McCall200fa532012-02-08 00:46:36 +00004076 qs.addConsistentQualifiers(split.Quals);
John McCall3b657512011-01-19 10:06:00 +00004077 }
Mike Stump1eb44332009-09-09 15:08:12 +00004078
John McCall3b657512011-01-19 10:06:00 +00004079 return getQualifiedType(type, qs);
Anders Carlsson6183a992008-12-21 03:44:36 +00004080}
4081
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004082/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00004083uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004084ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4085 uint64_t ElementCount = 1;
4086 do {
4087 ElementCount *= CA->getSize().getZExtValue();
Richard Smithd5e83942012-12-06 03:04:50 +00004088 CA = dyn_cast_or_null<ConstantArrayType>(
4089 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004090 } while (CA);
4091 return ElementCount;
4092}
4093
Reid Spencer5f016e22007-07-11 17:01:13 +00004094/// getFloatingRank - Return a relative rank for floating point types.
4095/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00004096static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00004097 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00004098 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00004099
John McCall183700f2009-09-21 23:43:11 +00004100 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4101 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004102 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00004103 case BuiltinType::Half: return HalfRank;
Reid Spencer5f016e22007-07-11 17:01:13 +00004104 case BuiltinType::Float: return FloatRank;
4105 case BuiltinType::Double: return DoubleRank;
4106 case BuiltinType::LongDouble: return LongDoubleRank;
4107 }
4108}
4109
Mike Stump1eb44332009-09-09 15:08:12 +00004110/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4111/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00004112/// 'typeDomain' is a real floating point or complex type.
4113/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00004114QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4115 QualType Domain) const {
4116 FloatingRank EltRank = getFloatingRank(Size);
4117 if (Domain->isComplexType()) {
4118 switch (EltRank) {
David Blaikie561d3ab2012-01-17 02:30:50 +00004119 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Narofff1448a02007-08-27 01:27:54 +00004120 case FloatRank: return FloatComplexTy;
4121 case DoubleRank: return DoubleComplexTy;
4122 case LongDoubleRank: return LongDoubleComplexTy;
4123 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004124 }
Chris Lattner1361b112008-04-06 23:58:54 +00004125
4126 assert(Domain->isRealFloatingType() && "Unknown domain!");
4127 switch (EltRank) {
Joey Gouly19dbb202013-01-23 11:56:20 +00004128 case HalfRank: return HalfTy;
Chris Lattner1361b112008-04-06 23:58:54 +00004129 case FloatRank: return FloatTy;
4130 case DoubleRank: return DoubleTy;
4131 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00004132 }
David Blaikie561d3ab2012-01-17 02:30:50 +00004133 llvm_unreachable("getFloatingRank(): illegal value for rank");
Reid Spencer5f016e22007-07-11 17:01:13 +00004134}
4135
Chris Lattner7cfeb082008-04-06 23:55:33 +00004136/// getFloatingTypeOrder - Compare the rank of the two specified floating
4137/// point types, ignoring the domain of the type (i.e. 'double' ==
4138/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00004139/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00004140int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnera75cea32008-04-06 23:38:49 +00004141 FloatingRank LHSR = getFloatingRank(LHS);
4142 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004143
Chris Lattnera75cea32008-04-06 23:38:49 +00004144 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00004145 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00004146 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00004147 return 1;
4148 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00004149}
4150
Chris Lattnerf52ab252008-04-06 22:59:24 +00004151/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4152/// routine will assert if passed a built-in type that isn't an integer or enum,
4153/// or if it is not canonicalized.
John McCallf4c73712011-01-19 06:33:43 +00004154unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCall467b27b2009-10-22 20:10:53 +00004155 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00004156
Chris Lattnerf52ab252008-04-06 22:59:24 +00004157 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004158 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattner7cfeb082008-04-06 23:55:33 +00004159 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004160 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004161 case BuiltinType::Char_S:
4162 case BuiltinType::Char_U:
4163 case BuiltinType::SChar:
4164 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004165 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004166 case BuiltinType::Short:
4167 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004168 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004169 case BuiltinType::Int:
4170 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004171 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004172 case BuiltinType::Long:
4173 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004174 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004175 case BuiltinType::LongLong:
4176 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004177 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00004178 case BuiltinType::Int128:
4179 case BuiltinType::UInt128:
4180 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00004181 }
4182}
4183
Eli Friedman04e83572009-08-20 04:21:42 +00004184/// \brief Whether this is a promotable bitfield reference according
4185/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4186///
4187/// \returns the type this bit-field will promote to, or NULL if no
4188/// promotion occurs.
Jay Foad4ba2a172011-01-12 09:06:06 +00004189QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregorceafbde2010-05-24 20:13:53 +00004190 if (E->isTypeDependent() || E->isValueDependent())
4191 return QualType();
4192
Eli Friedman04e83572009-08-20 04:21:42 +00004193 FieldDecl *Field = E->getBitField();
4194 if (!Field)
4195 return QualType();
4196
4197 QualType FT = Field->getType();
4198
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004199 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman04e83572009-08-20 04:21:42 +00004200 uint64_t IntSize = getTypeSize(IntTy);
4201 // GCC extension compatibility: if the bit-field size is less than or equal
4202 // to the size of int, it gets promoted no matter what its type is.
4203 // For instance, unsigned long bf : 4 gets promoted to signed int.
4204 if (BitWidth < IntSize)
4205 return IntTy;
4206
4207 if (BitWidth == IntSize)
4208 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4209
4210 // Types bigger than int are not subject to promotions, and therefore act
4211 // like the base type.
4212 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4213 // is ridiculous.
4214 return QualType();
4215}
4216
Eli Friedmana95d7572009-08-19 07:44:53 +00004217/// getPromotedIntegerType - Returns the type that Promotable will
4218/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4219/// integer type.
Jay Foad4ba2a172011-01-12 09:06:06 +00004220QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedmana95d7572009-08-19 07:44:53 +00004221 assert(!Promotable.isNull());
4222 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00004223 if (const EnumType *ET = Promotable->getAs<EnumType>())
4224 return ET->getDecl()->getPromotionType();
Eli Friedman68a2dc42011-10-26 07:22:48 +00004225
4226 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4227 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4228 // (3.9.1) can be converted to a prvalue of the first of the following
4229 // types that can represent all the values of its underlying type:
4230 // int, unsigned int, long int, unsigned long int, long long int, or
4231 // unsigned long long int [...]
4232 // FIXME: Is there some better way to compute this?
4233 if (BT->getKind() == BuiltinType::WChar_S ||
4234 BT->getKind() == BuiltinType::WChar_U ||
4235 BT->getKind() == BuiltinType::Char16 ||
4236 BT->getKind() == BuiltinType::Char32) {
4237 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4238 uint64_t FromSize = getTypeSize(BT);
4239 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4240 LongLongTy, UnsignedLongLongTy };
4241 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4242 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4243 if (FromSize < ToSize ||
4244 (FromSize == ToSize &&
4245 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4246 return PromoteTypes[Idx];
4247 }
4248 llvm_unreachable("char type should fit into long long");
4249 }
4250 }
4251
4252 // At this point, we should have a signed or unsigned integer type.
Eli Friedmana95d7572009-08-19 07:44:53 +00004253 if (Promotable->isSignedIntegerType())
4254 return IntTy;
Eli Friedman5b64e772012-11-15 01:21:59 +00004255 uint64_t PromotableSize = getIntWidth(Promotable);
4256 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedmana95d7572009-08-19 07:44:53 +00004257 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4258 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4259}
4260
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00004261/// \brief Recurses in pointer/array types until it finds an objc retainable
4262/// type and returns its ownership.
4263Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4264 while (!T.isNull()) {
4265 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4266 return T.getObjCLifetime();
4267 if (T->isArrayType())
4268 T = getBaseElementType(T);
4269 else if (const PointerType *PT = T->getAs<PointerType>())
4270 T = PT->getPointeeType();
4271 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis28445f02011-07-01 23:01:46 +00004272 T = RT->getPointeeType();
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00004273 else
4274 break;
4275 }
4276
4277 return Qualifiers::OCL_None;
4278}
4279
Mike Stump1eb44332009-09-09 15:08:12 +00004280/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00004281/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00004282/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00004283int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCallf4c73712011-01-19 06:33:43 +00004284 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4285 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00004286 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004287
Chris Lattnerf52ab252008-04-06 22:59:24 +00004288 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4289 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00004290
Chris Lattner7cfeb082008-04-06 23:55:33 +00004291 unsigned LHSRank = getIntegerRank(LHSC);
4292 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00004293
Chris Lattner7cfeb082008-04-06 23:55:33 +00004294 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4295 if (LHSRank == RHSRank) return 0;
4296 return LHSRank > RHSRank ? 1 : -1;
4297 }
Mike Stump1eb44332009-09-09 15:08:12 +00004298
Chris Lattner7cfeb082008-04-06 23:55:33 +00004299 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4300 if (LHSUnsigned) {
4301 // If the unsigned [LHS] type is larger, return it.
4302 if (LHSRank >= RHSRank)
4303 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004304
Chris Lattner7cfeb082008-04-06 23:55:33 +00004305 // If the signed type can represent all values of the unsigned type, it
4306 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00004307 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00004308 return -1;
4309 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00004310
Chris Lattner7cfeb082008-04-06 23:55:33 +00004311 // If the unsigned [RHS] type is larger, return it.
4312 if (RHSRank >= LHSRank)
4313 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00004314
Chris Lattner7cfeb082008-04-06 23:55:33 +00004315 // If the signed type can represent all values of the unsigned type, it
4316 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00004317 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00004318 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00004319}
Anders Carlsson71993dd2007-08-17 05:31:46 +00004320
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004321static RecordDecl *
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004322CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
4323 DeclContext *DC, IdentifierInfo *Id) {
4324 SourceLocation Loc;
David Blaikie4e4d0842012-03-11 07:00:24 +00004325 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004326 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004327 else
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004328 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004329}
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004330
Mike Stump1eb44332009-09-09 15:08:12 +00004331// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00004332QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson71993dd2007-08-17 05:31:46 +00004333 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00004334 CFConstantStringTypeDecl =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004335 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004336 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00004337 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004338
Anders Carlssonf06273f2007-11-19 00:25:30 +00004339 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00004340
Anders Carlsson71993dd2007-08-17 05:31:46 +00004341 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00004342 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00004343 // int flags;
4344 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00004345 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00004346 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00004347 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00004348 FieldTypes[3] = LongTy;
4349
Anders Carlsson71993dd2007-08-17 05:31:46 +00004350 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00004351 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00004352 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004353 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00004354 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00004355 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00004356 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004357 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004358 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004359 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004360 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00004361 }
4362
Douglas Gregor838db382010-02-11 01:19:42 +00004363 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00004364 }
Mike Stump1eb44332009-09-09 15:08:12 +00004365
Anders Carlsson71993dd2007-08-17 05:31:46 +00004366 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00004367}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004368
Fariborz Jahanianf7992132013-01-04 18:45:40 +00004369QualType ASTContext::getObjCSuperType() const {
4370 if (ObjCSuperType.isNull()) {
4371 RecordDecl *ObjCSuperTypeDecl =
4372 CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get("objc_super"));
4373 TUDecl->addDecl(ObjCSuperTypeDecl);
4374 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4375 }
4376 return ObjCSuperType;
4377}
4378
Douglas Gregor319ac892009-04-23 22:29:11 +00004379void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004380 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00004381 assert(Rec && "Invalid CFConstantStringType");
4382 CFConstantStringTypeDecl = Rec->getDecl();
4383}
4384
Jay Foad4ba2a172011-01-12 09:06:06 +00004385QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpadaaad32009-10-20 02:12:22 +00004386 if (BlockDescriptorType)
4387 return getTagDeclType(BlockDescriptorType);
4388
4389 RecordDecl *T;
4390 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004391 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004392 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00004393 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00004394
4395 QualType FieldTypes[] = {
4396 UnsignedLongTy,
4397 UnsignedLongTy,
4398 };
4399
4400 const char *FieldNames[] = {
4401 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00004402 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00004403 };
4404
4405 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004406 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00004407 SourceLocation(),
4408 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004409 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00004410 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004411 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004412 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004413 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00004414 T->addDecl(Field);
4415 }
4416
Douglas Gregor838db382010-02-11 01:19:42 +00004417 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00004418
4419 BlockDescriptorType = T;
4420
4421 return getTagDeclType(BlockDescriptorType);
4422}
4423
Jay Foad4ba2a172011-01-12 09:06:06 +00004424QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stump083c25e2009-10-22 00:49:09 +00004425 if (BlockDescriptorExtendedType)
4426 return getTagDeclType(BlockDescriptorExtendedType);
4427
4428 RecordDecl *T;
4429 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004430 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004431 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00004432 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00004433
4434 QualType FieldTypes[] = {
4435 UnsignedLongTy,
4436 UnsignedLongTy,
4437 getPointerType(VoidPtrTy),
4438 getPointerType(VoidPtrTy)
4439 };
4440
4441 const char *FieldNames[] = {
4442 "reserved",
4443 "Size",
4444 "CopyFuncPtr",
4445 "DestroyFuncPtr"
4446 };
4447
4448 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004449 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stump083c25e2009-10-22 00:49:09 +00004450 SourceLocation(),
4451 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004452 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00004453 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004454 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004455 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004456 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00004457 T->addDecl(Field);
4458 }
4459
Douglas Gregor838db382010-02-11 01:19:42 +00004460 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00004461
4462 BlockDescriptorExtendedType = T;
4463
4464 return getTagDeclType(BlockDescriptorExtendedType);
4465}
4466
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00004467/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4468/// requires copy/dispose. Note that this must match the logic
4469/// in buildByrefHelpers.
4470bool ASTContext::BlockRequiresCopying(QualType Ty,
4471 const VarDecl *D) {
4472 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4473 const Expr *copyExpr = getBlockVarCopyInits(D);
4474 if (!copyExpr && record->hasTrivialDestructor()) return false;
4475
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004476 return true;
Fariborz Jahaniane38be612010-11-17 00:21:28 +00004477 }
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00004478
4479 if (!Ty->isObjCRetainableType()) return false;
4480
4481 Qualifiers qs = Ty.getQualifiers();
4482
4483 // If we have lifetime, that dominates.
4484 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4485 assert(getLangOpts().ObjCAutoRefCount);
4486
4487 switch (lifetime) {
4488 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4489
4490 // These are just bits as far as the runtime is concerned.
4491 case Qualifiers::OCL_ExplicitNone:
4492 case Qualifiers::OCL_Autoreleasing:
4493 return false;
4494
4495 // Tell the runtime that this is ARC __weak, called by the
4496 // byref routines.
4497 case Qualifiers::OCL_Weak:
4498 // ARC __strong __block variables need to be retained.
4499 case Qualifiers::OCL_Strong:
4500 return true;
4501 }
4502 llvm_unreachable("fell out of lifetime switch!");
4503 }
4504 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4505 Ty->isObjCObjectPointerType());
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004506}
4507
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00004508bool ASTContext::getByrefLifetime(QualType Ty,
4509 Qualifiers::ObjCLifetime &LifeTime,
4510 bool &HasByrefExtendedLayout) const {
4511
4512 if (!getLangOpts().ObjC1 ||
4513 getLangOpts().getGC() != LangOptions::NonGC)
4514 return false;
4515
4516 HasByrefExtendedLayout = false;
Fariborz Jahanian34db84f2012-12-11 19:58:01 +00004517 if (Ty->isRecordType()) {
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00004518 HasByrefExtendedLayout = true;
4519 LifeTime = Qualifiers::OCL_None;
4520 }
4521 else if (getLangOpts().ObjCAutoRefCount)
4522 LifeTime = Ty.getObjCLifetime();
4523 // MRR.
4524 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4525 LifeTime = Qualifiers::OCL_ExplicitNone;
4526 else
4527 LifeTime = Qualifiers::OCL_None;
4528 return true;
4529}
4530
Douglas Gregore97179c2011-09-08 01:46:34 +00004531TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4532 if (!ObjCInstanceTypeDecl)
4533 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4534 getTranslationUnitDecl(),
4535 SourceLocation(),
4536 SourceLocation(),
4537 &Idents.get("instancetype"),
4538 getTrivialTypeSourceInfo(getObjCIdType()));
4539 return ObjCInstanceTypeDecl;
4540}
4541
Anders Carlssone8c49532007-10-29 06:33:42 +00004542// This returns true if a type has been typedefed to BOOL:
4543// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00004544static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00004545 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00004546 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4547 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00004548
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004549 return false;
4550}
4551
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004552/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004553/// purpose.
Jay Foad4ba2a172011-01-12 09:06:06 +00004554CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregorf968d832011-05-27 01:19:52 +00004555 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4556 return CharUnits::Zero();
4557
Ken Dyck199c3d62010-01-11 17:06:35 +00004558 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00004559
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004560 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004561 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004562 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004563 // Treat arrays as pointers, since that's how they're passed in.
4564 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004565 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004566 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00004567}
4568
4569static inline
4570std::string charUnitsToString(const CharUnits &CU) {
4571 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004572}
4573
John McCall6b5a61b2011-02-07 10:33:21 +00004574/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00004575/// declaration.
John McCall6b5a61b2011-02-07 10:33:21 +00004576std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4577 std::string S;
4578
David Chisnall5e530af2009-11-17 19:33:30 +00004579 const BlockDecl *Decl = Expr->getBlockDecl();
4580 QualType BlockTy =
4581 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4582 // Encode result type.
Fariborz Jahanian3d145f62012-11-15 19:02:45 +00004583 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian06cffc02012-11-14 23:11:38 +00004584 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None,
4585 BlockTy->getAs<FunctionType>()->getResultType(),
4586 S, true /*Extended*/);
4587 else
4588 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(),
4589 S);
David Chisnall5e530af2009-11-17 19:33:30 +00004590 // Compute size of all parameters.
4591 // Start with computing size of a pointer in number of bytes.
4592 // FIXME: There might(should) be a better way of doing this computation!
4593 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004594 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4595 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00004596 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00004597 E = Decl->param_end(); PI != E; ++PI) {
4598 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004599 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahanian075a5432012-06-30 00:48:59 +00004600 if (sz.isZero())
4601 continue;
Ken Dyck199c3d62010-01-11 17:06:35 +00004602 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00004603 ParmOffset += sz;
4604 }
4605 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00004606 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00004607 // Block pointer and offset.
4608 S += "@?0";
David Chisnall5e530af2009-11-17 19:33:30 +00004609
4610 // Argument types.
4611 ParmOffset = PtrSize;
4612 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4613 Decl->param_end(); PI != E; ++PI) {
4614 ParmVarDecl *PVDecl = *PI;
4615 QualType PType = PVDecl->getOriginalType();
4616 if (const ArrayType *AT =
4617 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4618 // Use array's original type only if it has known number of
4619 // elements.
4620 if (!isa<ConstantArrayType>(AT))
4621 PType = PVDecl->getType();
4622 } else if (PType->isFunctionType())
4623 PType = PVDecl->getType();
Fariborz Jahanian3d145f62012-11-15 19:02:45 +00004624 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian06cffc02012-11-14 23:11:38 +00004625 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4626 S, true /*Extended*/);
4627 else
4628 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00004629 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004630 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00004631 }
John McCall6b5a61b2011-02-07 10:33:21 +00004632
4633 return S;
David Chisnall5e530af2009-11-17 19:33:30 +00004634}
4635
Douglas Gregorf968d832011-05-27 01:19:52 +00004636bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall5389f482010-12-30 14:05:53 +00004637 std::string& S) {
4638 // Encode result type.
4639 getObjCEncodingForType(Decl->getResultType(), S);
4640 CharUnits ParmOffset;
4641 // Compute size of all parameters.
4642 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4643 E = Decl->param_end(); PI != E; ++PI) {
4644 QualType PType = (*PI)->getType();
4645 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004646 if (sz.isZero())
Fariborz Jahanian7e68ba52012-06-29 22:54:56 +00004647 continue;
4648
David Chisnall5389f482010-12-30 14:05:53 +00004649 assert (sz.isPositive() &&
Douglas Gregorf968d832011-05-27 01:19:52 +00004650 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall5389f482010-12-30 14:05:53 +00004651 ParmOffset += sz;
4652 }
4653 S += charUnitsToString(ParmOffset);
4654 ParmOffset = CharUnits::Zero();
4655
4656 // Argument types.
4657 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4658 E = Decl->param_end(); PI != E; ++PI) {
4659 ParmVarDecl *PVDecl = *PI;
4660 QualType PType = PVDecl->getOriginalType();
4661 if (const ArrayType *AT =
4662 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4663 // Use array's original type only if it has known number of
4664 // elements.
4665 if (!isa<ConstantArrayType>(AT))
4666 PType = PVDecl->getType();
4667 } else if (PType->isFunctionType())
4668 PType = PVDecl->getType();
4669 getObjCEncodingForType(PType, S);
4670 S += charUnitsToString(ParmOffset);
4671 ParmOffset += getObjCEncodingTypeSize(PType);
4672 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004673
4674 return false;
David Chisnall5389f482010-12-30 14:05:53 +00004675}
4676
Bob Wilsondc8dab62011-11-30 01:57:58 +00004677/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4678/// method parameter or return type. If Extended, include class names and
4679/// block object types.
4680void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4681 QualType T, std::string& S,
4682 bool Extended) const {
4683 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4684 getObjCEncodingForTypeQualifier(QT, S);
4685 // Encode parameter type.
4686 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4687 true /*OutermostType*/,
4688 false /*EncodingProperty*/,
4689 false /*StructField*/,
4690 Extended /*EncodeBlockParameters*/,
4691 Extended /*EncodeClassNames*/);
4692}
4693
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004694/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004695/// declaration.
Douglas Gregorf968d832011-05-27 01:19:52 +00004696bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilsondc8dab62011-11-30 01:57:58 +00004697 std::string& S,
4698 bool Extended) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004699 // FIXME: This is not very efficient.
Bob Wilsondc8dab62011-11-30 01:57:58 +00004700 // Encode return type.
4701 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4702 Decl->getResultType(), S, Extended);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004703 // Compute size of all parameters.
4704 // Start with computing size of a pointer in number of bytes.
4705 // FIXME: There might(should) be a better way of doing this computation!
4706 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004707 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004708 // The first two arguments (self and _cmd) are pointers; account for
4709 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00004710 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004711 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004712 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00004713 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004714 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004715 if (sz.isZero())
Fariborz Jahanian7e68ba52012-06-29 22:54:56 +00004716 continue;
4717
Ken Dyck199c3d62010-01-11 17:06:35 +00004718 assert (sz.isPositive() &&
4719 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004720 ParmOffset += sz;
4721 }
Ken Dyck199c3d62010-01-11 17:06:35 +00004722 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004723 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00004724 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00004725
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004726 // Argument types.
4727 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004728 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004729 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004730 const ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00004731 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00004732 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00004733 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4734 // Use array's original type only if it has known number of
4735 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00004736 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00004737 PType = PVDecl->getType();
4738 } else if (PType->isFunctionType())
4739 PType = PVDecl->getType();
Bob Wilsondc8dab62011-11-30 01:57:58 +00004740 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4741 PType, S, Extended);
Ken Dyck199c3d62010-01-11 17:06:35 +00004742 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004743 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004744 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004745
4746 return false;
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004747}
4748
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004749/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004750/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004751/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4752/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00004753/// Property attributes are stored as a comma-delimited C string. The simple
4754/// attributes readonly and bycopy are encoded as single characters. The
4755/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4756/// encoded as single characters, followed by an identifier. Property types
4757/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004758/// these attributes are defined by the following enumeration:
4759/// @code
4760/// enum PropertyAttributes {
4761/// kPropertyReadOnly = 'R', // property is read-only.
4762/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4763/// kPropertyByref = '&', // property is a reference to the value last assigned
4764/// kPropertyDynamic = 'D', // property is dynamic
4765/// kPropertyGetter = 'G', // followed by getter selector name
4766/// kPropertySetter = 'S', // followed by setter selector name
4767/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson0d4cb852012-03-22 17:48:02 +00004768/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004769/// kPropertyWeak = 'W' // 'weak' property
4770/// kPropertyStrong = 'P' // property GC'able
4771/// kPropertyNonAtomic = 'N' // property non-atomic
4772/// };
4773/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00004774void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004775 const Decl *Container,
Jay Foad4ba2a172011-01-12 09:06:06 +00004776 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004777 // Collect information from the property implementation decl(s).
4778 bool Dynamic = false;
4779 ObjCPropertyImplDecl *SynthesizePID = 0;
4780
4781 // FIXME: Duplicated code due to poor abstraction.
4782 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00004783 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004784 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4785 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004786 i = CID->propimpl_begin(), e = CID->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 }
4796 }
4797 } else {
Chris Lattner61710852008-10-05 17:34:18 +00004798 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004799 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004800 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004801 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00004802 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004803 if (PID->getPropertyDecl() == PD) {
4804 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4805 Dynamic = true;
4806 } else {
4807 SynthesizePID = PID;
4808 }
4809 }
Mike Stump1eb44332009-09-09 15:08:12 +00004810 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004811 }
4812 }
4813
4814 // FIXME: This is not very efficient.
4815 S = "T";
4816
4817 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004818 // GCC has some special rules regarding encoding of properties which
4819 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00004820 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004821 true /* outermost type */,
4822 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004823
4824 if (PD->isReadOnly()) {
4825 S += ",R";
4826 } else {
4827 switch (PD->getSetterKind()) {
4828 case ObjCPropertyDecl::Assign: break;
4829 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00004830 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian3a02b442011-08-12 20:47:08 +00004831 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004832 }
4833 }
4834
4835 // It really isn't clear at all what this means, since properties
4836 // are "dynamic by default".
4837 if (Dynamic)
4838 S += ",D";
4839
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004840 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4841 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00004842
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004843 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4844 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004845 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004846 }
4847
4848 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4849 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004850 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004851 }
4852
4853 if (SynthesizePID) {
4854 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4855 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00004856 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004857 }
4858
4859 // FIXME: OBJCGC: weak & strong
4860}
4861
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004862/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00004863/// Another legacy compatibility encoding: 32-bit longs are encoded as
4864/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004865/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4866///
4867void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00004868 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00004869 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad4ba2a172011-01-12 09:06:06 +00004870 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004871 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00004872 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004873 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004874 PointeeTy = IntTy;
4875 }
4876 }
4877}
4878
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004879void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad4ba2a172011-01-12 09:06:06 +00004880 const FieldDecl *Field) const {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004881 // We follow the behavior of gcc, expanding structures which are
4882 // directly pointed to, and expanding embedded structures. Note that
4883 // these rules are sufficient to prevent recursive encoding of the
4884 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00004885 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00004886 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004887}
4888
John McCall3624e9e2012-12-20 02:45:14 +00004889static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
4890 BuiltinType::Kind kind) {
4891 switch (kind) {
David Chisnall64fd7e82010-06-04 01:10:52 +00004892 case BuiltinType::Void: return 'v';
4893 case BuiltinType::Bool: return 'B';
4894 case BuiltinType::Char_U:
4895 case BuiltinType::UChar: return 'C';
John McCall3624e9e2012-12-20 02:45:14 +00004896 case BuiltinType::Char16:
David Chisnall64fd7e82010-06-04 01:10:52 +00004897 case BuiltinType::UShort: return 'S';
John McCall3624e9e2012-12-20 02:45:14 +00004898 case BuiltinType::Char32:
David Chisnall64fd7e82010-06-04 01:10:52 +00004899 case BuiltinType::UInt: return 'I';
4900 case BuiltinType::ULong:
John McCall3624e9e2012-12-20 02:45:14 +00004901 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004902 case BuiltinType::UInt128: return 'T';
4903 case BuiltinType::ULongLong: return 'Q';
4904 case BuiltinType::Char_S:
4905 case BuiltinType::SChar: return 'c';
4906 case BuiltinType::Short: return 's';
Chris Lattner3f59c972010-12-25 23:25:43 +00004907 case BuiltinType::WChar_S:
4908 case BuiltinType::WChar_U:
David Chisnall64fd7e82010-06-04 01:10:52 +00004909 case BuiltinType::Int: return 'i';
4910 case BuiltinType::Long:
John McCall3624e9e2012-12-20 02:45:14 +00004911 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004912 case BuiltinType::LongLong: return 'q';
4913 case BuiltinType::Int128: return 't';
4914 case BuiltinType::Float: return 'f';
4915 case BuiltinType::Double: return 'd';
Daniel Dunbar3a0be842010-10-11 21:13:48 +00004916 case BuiltinType::LongDouble: return 'D';
John McCall3624e9e2012-12-20 02:45:14 +00004917 case BuiltinType::NullPtr: return '*'; // like char*
4918
4919 case BuiltinType::Half:
4920 // FIXME: potentially need @encodes for these!
4921 return ' ';
4922
4923 case BuiltinType::ObjCId:
4924 case BuiltinType::ObjCClass:
4925 case BuiltinType::ObjCSel:
4926 llvm_unreachable("@encoding ObjC primitive type");
4927
4928 // OpenCL and placeholder types don't need @encodings.
4929 case BuiltinType::OCLImage1d:
4930 case BuiltinType::OCLImage1dArray:
4931 case BuiltinType::OCLImage1dBuffer:
4932 case BuiltinType::OCLImage2d:
4933 case BuiltinType::OCLImage2dArray:
4934 case BuiltinType::OCLImage3d:
Guy Benyeie6b9d802013-01-20 12:31:11 +00004935 case BuiltinType::OCLEvent:
Guy Benyei21f18c42013-02-07 10:55:47 +00004936 case BuiltinType::OCLSampler:
John McCall3624e9e2012-12-20 02:45:14 +00004937 case BuiltinType::Dependent:
4938#define BUILTIN_TYPE(KIND, ID)
4939#define PLACEHOLDER_TYPE(KIND, ID) \
4940 case BuiltinType::KIND:
4941#include "clang/AST/BuiltinTypes.def"
4942 llvm_unreachable("invalid builtin type for @encode");
David Chisnall64fd7e82010-06-04 01:10:52 +00004943 }
David Blaikie719e53f2013-01-09 17:48:41 +00004944 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnall64fd7e82010-06-04 01:10:52 +00004945}
4946
Douglas Gregor5471bc82011-09-08 17:18:35 +00004947static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4948 EnumDecl *Enum = ET->getDecl();
4949
4950 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4951 if (!Enum->isFixed())
4952 return 'i';
4953
4954 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall3624e9e2012-12-20 02:45:14 +00004955 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
4956 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor5471bc82011-09-08 17:18:35 +00004957}
4958
Jay Foad4ba2a172011-01-12 09:06:06 +00004959static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00004960 QualType T, const FieldDecl *FD) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004961 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004962 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00004963 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4964 // The GNU runtime requires more information; bitfields are encoded as b,
4965 // then the offset (in bits) of the first element, then the type of the
4966 // bitfield, then the size in bits. For example, in this structure:
4967 //
4968 // struct
4969 // {
4970 // int integer;
4971 // int flags:2;
4972 // };
4973 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4974 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4975 // information is not especially sensible, but we're stuck with it for
4976 // compatibility with GCC, although providing it breaks anything that
4977 // actually uses runtime introspection and wants to work on both runtimes...
John McCall260611a2012-06-20 06:18:46 +00004978 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnall64fd7e82010-06-04 01:10:52 +00004979 const RecordDecl *RD = FD->getParent();
4980 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedman82905742011-07-07 01:54:01 +00004981 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor5471bc82011-09-08 17:18:35 +00004982 if (const EnumType *ET = T->getAs<EnumType>())
4983 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall3624e9e2012-12-20 02:45:14 +00004984 else {
4985 const BuiltinType *BT = T->castAs<BuiltinType>();
4986 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
4987 }
David Chisnall64fd7e82010-06-04 01:10:52 +00004988 }
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004989 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004990}
4991
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00004992// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004993void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4994 bool ExpandPointedToStructures,
4995 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00004996 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004997 bool OutermostType,
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004998 bool EncodingProperty,
Bob Wilsondc8dab62011-11-30 01:57:58 +00004999 bool StructField,
5000 bool EncodeBlockParameters,
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005001 bool EncodeClassNames,
5002 bool EncodePointerToObjCTypedef) const {
John McCall3624e9e2012-12-20 02:45:14 +00005003 CanQualType CT = getCanonicalType(T);
5004 switch (CT->getTypeClass()) {
5005 case Type::Builtin:
5006 case Type::Enum:
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005007 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00005008 return EncodeBitField(this, S, T, FD);
John McCall3624e9e2012-12-20 02:45:14 +00005009 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5010 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5011 else
5012 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005013 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005014
John McCall3624e9e2012-12-20 02:45:14 +00005015 case Type::Complex: {
5016 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlssonc612f7b2009-04-09 21:55:45 +00005017 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00005018 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00005019 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005020 return;
5021 }
John McCall3624e9e2012-12-20 02:45:14 +00005022
5023 case Type::Atomic: {
5024 const AtomicType *AT = T->castAs<AtomicType>();
5025 S += 'A';
5026 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, 0,
5027 false, false);
5028 return;
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00005029 }
John McCall3624e9e2012-12-20 02:45:14 +00005030
5031 // encoding for pointer or reference types.
5032 case Type::Pointer:
5033 case Type::LValueReference:
5034 case Type::RValueReference: {
5035 QualType PointeeTy;
5036 if (isa<PointerType>(CT)) {
5037 const PointerType *PT = T->castAs<PointerType>();
5038 if (PT->isObjCSelType()) {
5039 S += ':';
5040 return;
5041 }
5042 PointeeTy = PT->getPointeeType();
5043 } else {
5044 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5045 }
5046
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005047 bool isReadOnly = false;
5048 // For historical/compatibility reasons, the read-only qualifier of the
5049 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5050 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00005051 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00005052 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005053 if (OutermostType && T.isConstQualified()) {
5054 isReadOnly = true;
5055 S += 'r';
5056 }
Mike Stump9fdbab32009-07-31 02:02:20 +00005057 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005058 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00005059 while (P->getAs<PointerType>())
5060 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005061 if (P.isConstQualified()) {
5062 isReadOnly = true;
5063 S += 'r';
5064 }
5065 }
5066 if (isReadOnly) {
5067 // Another legacy compatibility encoding. Some ObjC qualifier and type
5068 // combinations need to be rearranged.
5069 // Rewrite "in const" from "nr" to "rn"
Chris Lattner5f9e2722011-07-23 10:55:15 +00005070 if (StringRef(S).endswith("nr"))
Benjamin Kramer02379412010-04-27 17:12:11 +00005071 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005072 }
Mike Stump1eb44332009-09-09 15:08:12 +00005073
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005074 if (PointeeTy->isCharType()) {
5075 // char pointer types should be encoded as '*' unless it is a
5076 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00005077 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005078 S += '*';
5079 return;
5080 }
Ted Kremenek6217b802009-07-29 21:53:49 +00005081 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00005082 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5083 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5084 S += '#';
5085 return;
5086 }
5087 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5088 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5089 S += '@';
5090 return;
5091 }
5092 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005093 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005094 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005095 getLegacyIntegralTypeEncoding(PointeeTy);
5096
Mike Stump1eb44332009-09-09 15:08:12 +00005097 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005098 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005099 return;
5100 }
John McCall3624e9e2012-12-20 02:45:14 +00005101
5102 case Type::ConstantArray:
5103 case Type::IncompleteArray:
5104 case Type::VariableArray: {
5105 const ArrayType *AT = cast<ArrayType>(CT);
5106
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005107 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlsson559a8332009-02-22 01:38:57 +00005108 // Incomplete arrays are encoded as a pointer to the array element.
5109 S += '^';
5110
Mike Stump1eb44332009-09-09 15:08:12 +00005111 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00005112 false, ExpandStructures, FD);
5113 } else {
5114 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00005115
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005116 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
5117 if (getTypeSize(CAT->getElementType()) == 0)
5118 S += '0';
5119 else
5120 S += llvm::utostr(CAT->getSize().getZExtValue());
5121 } else {
Anders Carlsson559a8332009-02-22 01:38:57 +00005122 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005123 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5124 "Unknown array type!");
Anders Carlsson559a8332009-02-22 01:38:57 +00005125 S += '0';
5126 }
Mike Stump1eb44332009-09-09 15:08:12 +00005127
5128 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00005129 false, ExpandStructures, FD);
5130 S += ']';
5131 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005132 return;
5133 }
Mike Stump1eb44332009-09-09 15:08:12 +00005134
John McCall3624e9e2012-12-20 02:45:14 +00005135 case Type::FunctionNoProto:
5136 case Type::FunctionProto:
Anders Carlssonc0a87b72007-10-30 00:06:20 +00005137 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005138 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005139
John McCall3624e9e2012-12-20 02:45:14 +00005140 case Type::Record: {
5141 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005142 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00005143 // Anonymous structures print as '?'
5144 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5145 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00005146 if (ClassTemplateSpecializationDecl *Spec
5147 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5148 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer5eada842013-02-22 15:46:01 +00005149 llvm::raw_string_ostream OS(S);
5150 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor910f8002010-11-07 23:05:16 +00005151 TemplateArgs.data(),
5152 TemplateArgs.size(),
Douglas Gregor30c42402011-09-27 22:38:19 +00005153 (*this).getPrintingPolicy());
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00005154 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00005155 } else {
5156 S += '?';
5157 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00005158 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00005159 S += '=';
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005160 if (!RDecl->isUnion()) {
5161 getObjCEncodingForStructureImpl(RDecl, S, FD);
5162 } else {
5163 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5164 FieldEnd = RDecl->field_end();
5165 Field != FieldEnd; ++Field) {
5166 if (FD) {
5167 S += '"';
5168 S += Field->getNameAsString();
5169 S += '"';
5170 }
Mike Stump1eb44332009-09-09 15:08:12 +00005171
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005172 // Special case bit-fields.
5173 if (Field->isBitField()) {
5174 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie581deb32012-06-06 20:45:41 +00005175 *Field);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005176 } else {
5177 QualType qt = Field->getType();
5178 getLegacyIntegralTypeEncoding(qt);
5179 getObjCEncodingForTypeImpl(qt, S, false, true,
5180 FD, /*OutermostType*/false,
5181 /*EncodingProperty*/false,
5182 /*StructField*/true);
5183 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005184 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00005185 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00005186 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005187 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005188 return;
5189 }
Mike Stump1eb44332009-09-09 15:08:12 +00005190
John McCall3624e9e2012-12-20 02:45:14 +00005191 case Type::BlockPointer: {
5192 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff21a98b12009-02-02 18:24:29 +00005193 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilsondc8dab62011-11-30 01:57:58 +00005194 if (EncodeBlockParameters) {
John McCall3624e9e2012-12-20 02:45:14 +00005195 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilsondc8dab62011-11-30 01:57:58 +00005196
5197 S += '<';
5198 // Block return type
5199 getObjCEncodingForTypeImpl(FT->getResultType(), S,
5200 ExpandPointedToStructures, ExpandStructures,
5201 FD,
5202 false /* OutermostType */,
5203 EncodingProperty,
5204 false /* StructField */,
5205 EncodeBlockParameters,
5206 EncodeClassNames);
5207 // Block self
5208 S += "@?";
5209 // Block parameters
5210 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
5211 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
5212 E = FPT->arg_type_end(); I && (I != E); ++I) {
5213 getObjCEncodingForTypeImpl(*I, S,
5214 ExpandPointedToStructures,
5215 ExpandStructures,
5216 FD,
5217 false /* OutermostType */,
5218 EncodingProperty,
5219 false /* StructField */,
5220 EncodeBlockParameters,
5221 EncodeClassNames);
5222 }
5223 }
5224 S += '>';
5225 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005226 return;
5227 }
Mike Stump1eb44332009-09-09 15:08:12 +00005228
John McCall3624e9e2012-12-20 02:45:14 +00005229 case Type::ObjCObject:
5230 case Type::ObjCInterface: {
5231 // Ignore protocol qualifiers when mangling at this level.
5232 T = T->castAs<ObjCObjectType>()->getBaseType();
John McCallc12c5bb2010-05-15 11:32:37 +00005233
John McCall3624e9e2012-12-20 02:45:14 +00005234 // The assumption seems to be that this assert will succeed
5235 // because nested levels will have filtered out 'id' and 'Class'.
5236 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005237 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00005238 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005239 S += '{';
5240 const IdentifierInfo *II = OI->getIdentifier();
5241 S += II->getName();
5242 S += '=';
Jordy Rosedb8264e2011-07-22 02:08:32 +00005243 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00005244 DeepCollectObjCIvars(OI, true, Ivars);
5245 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00005246 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00005247 if (Field->isBitField())
5248 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005249 else
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005250 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5251 false, false, false, false, false,
5252 EncodePointerToObjCTypedef);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005253 }
5254 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005255 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005256 }
Mike Stump1eb44332009-09-09 15:08:12 +00005257
John McCall3624e9e2012-12-20 02:45:14 +00005258 case Type::ObjCObjectPointer: {
5259 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff14108da2009-07-10 23:34:53 +00005260 if (OPT->isObjCIdType()) {
5261 S += '@';
5262 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005263 }
Mike Stump1eb44332009-09-09 15:08:12 +00005264
Steve Naroff27d20a22009-10-28 22:03:49 +00005265 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5266 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5267 // Since this is a binary compatibility issue, need to consult with runtime
5268 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00005269 S += '#';
5270 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005271 }
Mike Stump1eb44332009-09-09 15:08:12 +00005272
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005273 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005274 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00005275 ExpandPointedToStructures,
5276 ExpandStructures, FD);
Bob Wilsondc8dab62011-11-30 01:57:58 +00005277 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff14108da2009-07-10 23:34:53 +00005278 // Note that we do extended encoding of protocol qualifer list
5279 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00005280 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005281 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5282 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00005283 S += '<';
5284 S += (*I)->getNameAsString();
5285 S += '>';
5286 }
5287 S += '"';
5288 }
5289 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005290 }
Mike Stump1eb44332009-09-09 15:08:12 +00005291
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005292 QualType PointeeTy = OPT->getPointeeType();
5293 if (!EncodingProperty &&
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005294 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5295 !EncodePointerToObjCTypedef) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005296 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00005297 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005298 // {...};
5299 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00005300 getObjCEncodingForTypeImpl(PointeeTy, S,
5301 false, ExpandPointedToStructures,
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005302 NULL,
5303 false, false, false, false, false,
5304 /*EncodePointerToObjCTypedef*/true);
Steve Naroff14108da2009-07-10 23:34:53 +00005305 return;
5306 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005307
5308 S += '@';
Bob Wilsondc8dab62011-11-30 01:57:58 +00005309 if (OPT->getInterfaceDecl() &&
5310 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005311 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00005312 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005313 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5314 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005315 S += '<';
5316 S += (*I)->getNameAsString();
5317 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00005318 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005319 S += '"';
5320 }
5321 return;
5322 }
Mike Stump1eb44332009-09-09 15:08:12 +00005323
John McCall532ec7b2010-05-17 23:56:34 +00005324 // gcc just blithely ignores member pointers.
John McCall3624e9e2012-12-20 02:45:14 +00005325 // FIXME: we shoul do better than that. 'M' is available.
5326 case Type::MemberPointer:
John McCall532ec7b2010-05-17 23:56:34 +00005327 return;
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005328
John McCall3624e9e2012-12-20 02:45:14 +00005329 case Type::Vector:
5330 case Type::ExtVector:
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005331 // This matches gcc's encoding, even though technically it is
5332 // insufficient.
5333 // FIXME. We should do a better job than gcc.
5334 return;
John McCall3624e9e2012-12-20 02:45:14 +00005335
5336#define ABSTRACT_TYPE(KIND, BASE)
5337#define TYPE(KIND, BASE)
5338#define DEPENDENT_TYPE(KIND, BASE) \
5339 case Type::KIND:
5340#define NON_CANONICAL_TYPE(KIND, BASE) \
5341 case Type::KIND:
5342#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5343 case Type::KIND:
5344#include "clang/AST/TypeNodes.def"
5345 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005346 }
John McCall3624e9e2012-12-20 02:45:14 +00005347 llvm_unreachable("bad type kind!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005348}
5349
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005350void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5351 std::string &S,
5352 const FieldDecl *FD,
5353 bool includeVBases) const {
5354 assert(RDecl && "Expected non-null RecordDecl");
5355 assert(!RDecl->isUnion() && "Should not be called for unions");
5356 if (!RDecl->getDefinition())
5357 return;
5358
5359 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5360 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5361 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5362
5363 if (CXXRec) {
5364 for (CXXRecordDecl::base_class_iterator
5365 BI = CXXRec->bases_begin(),
5366 BE = CXXRec->bases_end(); BI != BE; ++BI) {
5367 if (!BI->isVirtual()) {
5368 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005369 if (base->isEmpty())
5370 continue;
Benjamin Kramerd4f51982012-07-04 18:45:14 +00005371 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005372 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5373 std::make_pair(offs, base));
5374 }
5375 }
5376 }
5377
5378 unsigned i = 0;
5379 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5380 FieldEnd = RDecl->field_end();
5381 Field != FieldEnd; ++Field, ++i) {
5382 uint64_t offs = layout.getFieldOffset(i);
5383 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie581deb32012-06-06 20:45:41 +00005384 std::make_pair(offs, *Field));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005385 }
5386
5387 if (CXXRec && includeVBases) {
5388 for (CXXRecordDecl::base_class_iterator
5389 BI = CXXRec->vbases_begin(),
5390 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
5391 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005392 if (base->isEmpty())
5393 continue;
Benjamin Kramerd4f51982012-07-04 18:45:14 +00005394 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Argyrios Kyrtzidis19aa8602011-09-26 18:14:24 +00005395 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
5396 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5397 std::make_pair(offs, base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005398 }
5399 }
5400
5401 CharUnits size;
5402 if (CXXRec) {
5403 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5404 } else {
5405 size = layout.getSize();
5406 }
5407
5408 uint64_t CurOffs = 0;
5409 std::multimap<uint64_t, NamedDecl *>::iterator
5410 CurLayObj = FieldOrBaseOffsets.begin();
5411
Douglas Gregor58db7a52012-04-27 22:30:01 +00005412 if (CXXRec && CXXRec->isDynamicClass() &&
5413 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005414 if (FD) {
5415 S += "\"_vptr$";
5416 std::string recname = CXXRec->getNameAsString();
5417 if (recname.empty()) recname = "?";
5418 S += recname;
5419 S += '"';
5420 }
5421 S += "^^?";
5422 CurOffs += getTypeSize(VoidPtrTy);
5423 }
5424
5425 if (!RDecl->hasFlexibleArrayMember()) {
5426 // Mark the end of the structure.
5427 uint64_t offs = toBits(size);
5428 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5429 std::make_pair(offs, (NamedDecl*)0));
5430 }
5431
5432 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5433 assert(CurOffs <= CurLayObj->first);
5434
5435 if (CurOffs < CurLayObj->first) {
5436 uint64_t padding = CurLayObj->first - CurOffs;
5437 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5438 // packing/alignment of members is different that normal, in which case
5439 // the encoding will be out-of-sync with the real layout.
5440 // If the runtime switches to just consider the size of types without
5441 // taking into account alignment, we could make padding explicit in the
5442 // encoding (e.g. using arrays of chars). The encoding strings would be
5443 // longer then though.
5444 CurOffs += padding;
5445 }
5446
5447 NamedDecl *dcl = CurLayObj->second;
5448 if (dcl == 0)
5449 break; // reached end of structure.
5450
5451 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5452 // We expand the bases without their virtual bases since those are going
5453 // in the initial structure. Note that this differs from gcc which
5454 // expands virtual bases each time one is encountered in the hierarchy,
5455 // making the encoding type bigger than it really is.
5456 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005457 assert(!base->isEmpty());
5458 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005459 } else {
5460 FieldDecl *field = cast<FieldDecl>(dcl);
5461 if (FD) {
5462 S += '"';
5463 S += field->getNameAsString();
5464 S += '"';
5465 }
5466
5467 if (field->isBitField()) {
5468 EncodeBitField(this, S, field->getType(), field);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005469 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005470 } else {
5471 QualType qt = field->getType();
5472 getLegacyIntegralTypeEncoding(qt);
5473 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5474 /*OutermostType*/false,
5475 /*EncodingProperty*/false,
5476 /*StructField*/true);
5477 CurOffs += getTypeSize(field->getType());
5478 }
5479 }
5480 }
5481}
5482
Mike Stump1eb44332009-09-09 15:08:12 +00005483void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00005484 std::string& S) const {
5485 if (QT & Decl::OBJC_TQ_In)
5486 S += 'n';
5487 if (QT & Decl::OBJC_TQ_Inout)
5488 S += 'N';
5489 if (QT & Decl::OBJC_TQ_Out)
5490 S += 'o';
5491 if (QT & Decl::OBJC_TQ_Bycopy)
5492 S += 'O';
5493 if (QT & Decl::OBJC_TQ_Byref)
5494 S += 'R';
5495 if (QT & Decl::OBJC_TQ_Oneway)
5496 S += 'V';
5497}
5498
Douglas Gregor4dfd02a2011-08-12 05:46:01 +00005499TypedefDecl *ASTContext::getObjCIdDecl() const {
5500 if (!ObjCIdDecl) {
5501 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5502 T = getObjCObjectPointerType(T);
5503 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
5504 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5505 getTranslationUnitDecl(),
5506 SourceLocation(), SourceLocation(),
5507 &Idents.get("id"), IdInfo);
5508 }
5509
5510 return ObjCIdDecl;
Steve Naroff7e219e42007-10-15 14:41:52 +00005511}
5512
Douglas Gregor7a27ea52011-08-12 06:17:30 +00005513TypedefDecl *ASTContext::getObjCSelDecl() const {
5514 if (!ObjCSelDecl) {
5515 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5516 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5517 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5518 getTranslationUnitDecl(),
5519 SourceLocation(), SourceLocation(),
5520 &Idents.get("SEL"), SelInfo);
5521 }
5522 return ObjCSelDecl;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00005523}
5524
Douglas Gregor79d67262011-08-12 05:59:41 +00005525TypedefDecl *ASTContext::getObjCClassDecl() const {
5526 if (!ObjCClassDecl) {
5527 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5528 T = getObjCObjectPointerType(T);
5529 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5530 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5531 getTranslationUnitDecl(),
5532 SourceLocation(), SourceLocation(),
5533 &Idents.get("Class"), ClassInfo);
5534 }
5535
5536 return ObjCClassDecl;
Anders Carlsson8baaca52007-10-31 02:53:19 +00005537}
5538
Douglas Gregora6ea10e2012-01-17 18:09:05 +00005539ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5540 if (!ObjCProtocolClassDecl) {
5541 ObjCProtocolClassDecl
5542 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5543 SourceLocation(),
5544 &Idents.get("Protocol"),
5545 /*PrevDecl=*/0,
5546 SourceLocation(), true);
5547 }
5548
5549 return ObjCProtocolClassDecl;
5550}
5551
Meador Ingec5613b22012-06-16 03:34:49 +00005552//===----------------------------------------------------------------------===//
5553// __builtin_va_list Construction Functions
5554//===----------------------------------------------------------------------===//
5555
5556static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5557 // typedef char* __builtin_va_list;
5558 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5559 TypeSourceInfo *TInfo
5560 = Context->getTrivialTypeSourceInfo(CharPtrType);
5561
5562 TypedefDecl *VaListTypeDecl
5563 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5564 Context->getTranslationUnitDecl(),
5565 SourceLocation(), SourceLocation(),
5566 &Context->Idents.get("__builtin_va_list"),
5567 TInfo);
5568 return VaListTypeDecl;
5569}
5570
5571static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5572 // typedef void* __builtin_va_list;
5573 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5574 TypeSourceInfo *TInfo
5575 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5576
5577 TypedefDecl *VaListTypeDecl
5578 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5579 Context->getTranslationUnitDecl(),
5580 SourceLocation(), SourceLocation(),
5581 &Context->Idents.get("__builtin_va_list"),
5582 TInfo);
5583 return VaListTypeDecl;
5584}
5585
Tim Northoverc264e162013-01-31 12:13:10 +00005586static TypedefDecl *
5587CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
5588 RecordDecl *VaListTagDecl;
5589 if (Context->getLangOpts().CPlusPlus) {
5590 // namespace std { struct __va_list {
5591 NamespaceDecl *NS;
5592 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5593 Context->getTranslationUnitDecl(),
5594 /*Inline*/false, SourceLocation(),
5595 SourceLocation(), &Context->Idents.get("std"),
5596 /*PrevDecl*/0);
5597
5598 VaListTagDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5599 Context->getTranslationUnitDecl(),
5600 SourceLocation(), SourceLocation(),
5601 &Context->Idents.get("__va_list"));
5602 VaListTagDecl->setDeclContext(NS);
5603 } else {
5604 // struct __va_list
5605 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5606 Context->getTranslationUnitDecl(),
5607 &Context->Idents.get("__va_list"));
5608 }
5609
5610 VaListTagDecl->startDefinition();
5611
5612 const size_t NumFields = 5;
5613 QualType FieldTypes[NumFields];
5614 const char *FieldNames[NumFields];
5615
5616 // void *__stack;
5617 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
5618 FieldNames[0] = "__stack";
5619
5620 // void *__gr_top;
5621 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
5622 FieldNames[1] = "__gr_top";
5623
5624 // void *__vr_top;
5625 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5626 FieldNames[2] = "__vr_top";
5627
5628 // int __gr_offs;
5629 FieldTypes[3] = Context->IntTy;
5630 FieldNames[3] = "__gr_offs";
5631
5632 // int __vr_offs;
5633 FieldTypes[4] = Context->IntTy;
5634 FieldNames[4] = "__vr_offs";
5635
5636 // Create fields
5637 for (unsigned i = 0; i < NumFields; ++i) {
5638 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5639 VaListTagDecl,
5640 SourceLocation(),
5641 SourceLocation(),
5642 &Context->Idents.get(FieldNames[i]),
5643 FieldTypes[i], /*TInfo=*/0,
5644 /*BitWidth=*/0,
5645 /*Mutable=*/false,
5646 ICIS_NoInit);
5647 Field->setAccess(AS_public);
5648 VaListTagDecl->addDecl(Field);
5649 }
5650 VaListTagDecl->completeDefinition();
5651 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5652 Context->VaListTagTy = VaListTagType;
5653
5654 // } __builtin_va_list;
5655 TypedefDecl *VaListTypedefDecl
5656 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5657 Context->getTranslationUnitDecl(),
5658 SourceLocation(), SourceLocation(),
5659 &Context->Idents.get("__builtin_va_list"),
5660 Context->getTrivialTypeSourceInfo(VaListTagType));
5661
5662 return VaListTypedefDecl;
5663}
5664
Meador Ingec5613b22012-06-16 03:34:49 +00005665static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5666 // typedef struct __va_list_tag {
5667 RecordDecl *VaListTagDecl;
5668
5669 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5670 Context->getTranslationUnitDecl(),
5671 &Context->Idents.get("__va_list_tag"));
5672 VaListTagDecl->startDefinition();
5673
5674 const size_t NumFields = 5;
5675 QualType FieldTypes[NumFields];
5676 const char *FieldNames[NumFields];
5677
5678 // unsigned char gpr;
5679 FieldTypes[0] = Context->UnsignedCharTy;
5680 FieldNames[0] = "gpr";
5681
5682 // unsigned char fpr;
5683 FieldTypes[1] = Context->UnsignedCharTy;
5684 FieldNames[1] = "fpr";
5685
5686 // unsigned short reserved;
5687 FieldTypes[2] = Context->UnsignedShortTy;
5688 FieldNames[2] = "reserved";
5689
5690 // void* overflow_arg_area;
5691 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5692 FieldNames[3] = "overflow_arg_area";
5693
5694 // void* reg_save_area;
5695 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5696 FieldNames[4] = "reg_save_area";
5697
5698 // Create fields
5699 for (unsigned i = 0; i < NumFields; ++i) {
5700 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5701 SourceLocation(),
5702 SourceLocation(),
5703 &Context->Idents.get(FieldNames[i]),
5704 FieldTypes[i], /*TInfo=*/0,
5705 /*BitWidth=*/0,
5706 /*Mutable=*/false,
5707 ICIS_NoInit);
5708 Field->setAccess(AS_public);
5709 VaListTagDecl->addDecl(Field);
5710 }
5711 VaListTagDecl->completeDefinition();
5712 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingefb40e3f2012-07-01 15:57:25 +00005713 Context->VaListTagTy = VaListTagType;
Meador Ingec5613b22012-06-16 03:34:49 +00005714
5715 // } __va_list_tag;
5716 TypedefDecl *VaListTagTypedefDecl
5717 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5718 Context->getTranslationUnitDecl(),
5719 SourceLocation(), SourceLocation(),
5720 &Context->Idents.get("__va_list_tag"),
5721 Context->getTrivialTypeSourceInfo(VaListTagType));
5722 QualType VaListTagTypedefType =
5723 Context->getTypedefType(VaListTagTypedefDecl);
5724
5725 // typedef __va_list_tag __builtin_va_list[1];
5726 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5727 QualType VaListTagArrayType
5728 = Context->getConstantArrayType(VaListTagTypedefType,
5729 Size, ArrayType::Normal, 0);
5730 TypeSourceInfo *TInfo
5731 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5732 TypedefDecl *VaListTypedefDecl
5733 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5734 Context->getTranslationUnitDecl(),
5735 SourceLocation(), SourceLocation(),
5736 &Context->Idents.get("__builtin_va_list"),
5737 TInfo);
5738
5739 return VaListTypedefDecl;
5740}
5741
5742static TypedefDecl *
5743CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5744 // typedef struct __va_list_tag {
5745 RecordDecl *VaListTagDecl;
5746 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5747 Context->getTranslationUnitDecl(),
5748 &Context->Idents.get("__va_list_tag"));
5749 VaListTagDecl->startDefinition();
5750
5751 const size_t NumFields = 4;
5752 QualType FieldTypes[NumFields];
5753 const char *FieldNames[NumFields];
5754
5755 // unsigned gp_offset;
5756 FieldTypes[0] = Context->UnsignedIntTy;
5757 FieldNames[0] = "gp_offset";
5758
5759 // unsigned fp_offset;
5760 FieldTypes[1] = Context->UnsignedIntTy;
5761 FieldNames[1] = "fp_offset";
5762
5763 // void* overflow_arg_area;
5764 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5765 FieldNames[2] = "overflow_arg_area";
5766
5767 // void* reg_save_area;
5768 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5769 FieldNames[3] = "reg_save_area";
5770
5771 // Create fields
5772 for (unsigned i = 0; i < NumFields; ++i) {
5773 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5774 VaListTagDecl,
5775 SourceLocation(),
5776 SourceLocation(),
5777 &Context->Idents.get(FieldNames[i]),
5778 FieldTypes[i], /*TInfo=*/0,
5779 /*BitWidth=*/0,
5780 /*Mutable=*/false,
5781 ICIS_NoInit);
5782 Field->setAccess(AS_public);
5783 VaListTagDecl->addDecl(Field);
5784 }
5785 VaListTagDecl->completeDefinition();
5786 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingefb40e3f2012-07-01 15:57:25 +00005787 Context->VaListTagTy = VaListTagType;
Meador Ingec5613b22012-06-16 03:34:49 +00005788
5789 // } __va_list_tag;
5790 TypedefDecl *VaListTagTypedefDecl
5791 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5792 Context->getTranslationUnitDecl(),
5793 SourceLocation(), SourceLocation(),
5794 &Context->Idents.get("__va_list_tag"),
5795 Context->getTrivialTypeSourceInfo(VaListTagType));
5796 QualType VaListTagTypedefType =
5797 Context->getTypedefType(VaListTagTypedefDecl);
5798
5799 // typedef __va_list_tag __builtin_va_list[1];
5800 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5801 QualType VaListTagArrayType
5802 = Context->getConstantArrayType(VaListTagTypedefType,
5803 Size, ArrayType::Normal,0);
5804 TypeSourceInfo *TInfo
5805 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5806 TypedefDecl *VaListTypedefDecl
5807 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5808 Context->getTranslationUnitDecl(),
5809 SourceLocation(), SourceLocation(),
5810 &Context->Idents.get("__builtin_va_list"),
5811 TInfo);
5812
5813 return VaListTypedefDecl;
5814}
5815
5816static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5817 // typedef int __builtin_va_list[4];
5818 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5819 QualType IntArrayType
5820 = Context->getConstantArrayType(Context->IntTy,
5821 Size, ArrayType::Normal, 0);
5822 TypedefDecl *VaListTypedefDecl
5823 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5824 Context->getTranslationUnitDecl(),
5825 SourceLocation(), SourceLocation(),
5826 &Context->Idents.get("__builtin_va_list"),
5827 Context->getTrivialTypeSourceInfo(IntArrayType));
5828
5829 return VaListTypedefDecl;
5830}
5831
Logan Chieneae5a8202012-10-10 06:56:20 +00005832static TypedefDecl *
5833CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
5834 RecordDecl *VaListDecl;
5835 if (Context->getLangOpts().CPlusPlus) {
5836 // namespace std { struct __va_list {
5837 NamespaceDecl *NS;
5838 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5839 Context->getTranslationUnitDecl(),
5840 /*Inline*/false, SourceLocation(),
5841 SourceLocation(), &Context->Idents.get("std"),
5842 /*PrevDecl*/0);
5843
5844 VaListDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5845 Context->getTranslationUnitDecl(),
5846 SourceLocation(), SourceLocation(),
5847 &Context->Idents.get("__va_list"));
5848
5849 VaListDecl->setDeclContext(NS);
5850
5851 } else {
5852 // struct __va_list {
5853 VaListDecl = CreateRecordDecl(*Context, TTK_Struct,
5854 Context->getTranslationUnitDecl(),
5855 &Context->Idents.get("__va_list"));
5856 }
5857
5858 VaListDecl->startDefinition();
5859
5860 // void * __ap;
5861 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5862 VaListDecl,
5863 SourceLocation(),
5864 SourceLocation(),
5865 &Context->Idents.get("__ap"),
5866 Context->getPointerType(Context->VoidTy),
5867 /*TInfo=*/0,
5868 /*BitWidth=*/0,
5869 /*Mutable=*/false,
5870 ICIS_NoInit);
5871 Field->setAccess(AS_public);
5872 VaListDecl->addDecl(Field);
5873
5874 // };
5875 VaListDecl->completeDefinition();
5876
5877 // typedef struct __va_list __builtin_va_list;
5878 TypeSourceInfo *TInfo
5879 = Context->getTrivialTypeSourceInfo(Context->getRecordType(VaListDecl));
5880
5881 TypedefDecl *VaListTypeDecl
5882 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5883 Context->getTranslationUnitDecl(),
5884 SourceLocation(), SourceLocation(),
5885 &Context->Idents.get("__builtin_va_list"),
5886 TInfo);
5887
5888 return VaListTypeDecl;
5889}
5890
Meador Ingec5613b22012-06-16 03:34:49 +00005891static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
5892 TargetInfo::BuiltinVaListKind Kind) {
5893 switch (Kind) {
5894 case TargetInfo::CharPtrBuiltinVaList:
5895 return CreateCharPtrBuiltinVaListDecl(Context);
5896 case TargetInfo::VoidPtrBuiltinVaList:
5897 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northoverc264e162013-01-31 12:13:10 +00005898 case TargetInfo::AArch64ABIBuiltinVaList:
5899 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Ingec5613b22012-06-16 03:34:49 +00005900 case TargetInfo::PowerABIBuiltinVaList:
5901 return CreatePowerABIBuiltinVaListDecl(Context);
5902 case TargetInfo::X86_64ABIBuiltinVaList:
5903 return CreateX86_64ABIBuiltinVaListDecl(Context);
5904 case TargetInfo::PNaClABIBuiltinVaList:
5905 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chieneae5a8202012-10-10 06:56:20 +00005906 case TargetInfo::AAPCSABIBuiltinVaList:
5907 return CreateAAPCSABIBuiltinVaListDecl(Context);
Meador Ingec5613b22012-06-16 03:34:49 +00005908 }
5909
5910 llvm_unreachable("Unhandled __builtin_va_list type kind");
5911}
5912
5913TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
5914 if (!BuiltinVaListDecl)
5915 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
5916
5917 return BuiltinVaListDecl;
5918}
5919
Meador Ingefb40e3f2012-07-01 15:57:25 +00005920QualType ASTContext::getVaListTagType() const {
5921 // Force the creation of VaListTagTy by building the __builtin_va_list
5922 // declaration.
5923 if (VaListTagTy.isNull())
5924 (void) getBuiltinVaListDecl();
5925
5926 return VaListTagTy;
5927}
5928
Ted Kremeneka526c5c2008-01-07 19:49:32 +00005929void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00005930 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00005931 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00005932
Ted Kremeneka526c5c2008-01-07 19:49:32 +00005933 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00005934}
5935
John McCall0bd6feb2009-12-02 08:04:21 +00005936/// \brief Retrieve the template name that corresponds to a non-empty
5937/// lookup.
Jay Foad4ba2a172011-01-12 09:06:06 +00005938TemplateName
5939ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
5940 UnresolvedSetIterator End) const {
John McCall0bd6feb2009-12-02 08:04:21 +00005941 unsigned size = End - Begin;
5942 assert(size > 1 && "set is not overloaded!");
5943
5944 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
5945 size * sizeof(FunctionTemplateDecl*));
5946 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
5947
5948 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00005949 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00005950 NamedDecl *D = *I;
5951 assert(isa<FunctionTemplateDecl>(D) ||
5952 (isa<UsingShadowDecl>(D) &&
5953 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
5954 *Storage++ = D;
5955 }
5956
5957 return TemplateName(OT);
5958}
5959
Douglas Gregor7532dc62009-03-30 22:58:21 +00005960/// \brief Retrieve the template name that represents a qualified
5961/// template name such as \c std::vector.
Jay Foad4ba2a172011-01-12 09:06:06 +00005962TemplateName
5963ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
5964 bool TemplateKeyword,
5965 TemplateDecl *Template) const {
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00005966 assert(NNS && "Missing nested-name-specifier in qualified template name");
5967
Douglas Gregor789b1f62010-02-04 18:10:26 +00005968 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00005969 llvm::FoldingSetNodeID ID;
5970 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
5971
5972 void *InsertPos = 0;
5973 QualifiedTemplateName *QTN =
5974 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5975 if (!QTN) {
Richard Smith2f47cab2012-08-16 01:19:31 +00005976 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
5977 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregor7532dc62009-03-30 22:58:21 +00005978 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
5979 }
5980
5981 return TemplateName(QTN);
5982}
5983
5984/// \brief Retrieve the template name that represents a dependent
5985/// template name such as \c MetaFun::template apply.
Jay Foad4ba2a172011-01-12 09:06:06 +00005986TemplateName
5987ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
5988 const IdentifierInfo *Name) const {
Mike Stump1eb44332009-09-09 15:08:12 +00005989 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00005990 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00005991
5992 llvm::FoldingSetNodeID ID;
5993 DependentTemplateName::Profile(ID, NNS, Name);
5994
5995 void *InsertPos = 0;
5996 DependentTemplateName *QTN =
5997 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5998
5999 if (QTN)
6000 return TemplateName(QTN);
6001
6002 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6003 if (CanonNNS == NNS) {
Richard Smith2f47cab2012-08-16 01:19:31 +00006004 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6005 DependentTemplateName(NNS, Name);
Douglas Gregor7532dc62009-03-30 22:58:21 +00006006 } else {
6007 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smith2f47cab2012-08-16 01:19:31 +00006008 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6009 DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00006010 DependentTemplateName *CheckQTN =
6011 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6012 assert(!CheckQTN && "Dependent type name canonicalization broken");
6013 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00006014 }
6015
6016 DependentTemplateNames.InsertNode(QTN, InsertPos);
6017 return TemplateName(QTN);
6018}
6019
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006020/// \brief Retrieve the template name that represents a dependent
6021/// template name such as \c MetaFun::template operator+.
6022TemplateName
6023ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00006024 OverloadedOperatorKind Operator) const {
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006025 assert((!NNS || NNS->isDependent()) &&
6026 "Nested name specifier must be dependent");
6027
6028 llvm::FoldingSetNodeID ID;
6029 DependentTemplateName::Profile(ID, NNS, Operator);
6030
6031 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00006032 DependentTemplateName *QTN
6033 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006034
6035 if (QTN)
6036 return TemplateName(QTN);
6037
6038 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6039 if (CanonNNS == NNS) {
Richard Smith2f47cab2012-08-16 01:19:31 +00006040 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6041 DependentTemplateName(NNS, Operator);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006042 } else {
6043 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smith2f47cab2012-08-16 01:19:31 +00006044 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6045 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00006046
6047 DependentTemplateName *CheckQTN
6048 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6049 assert(!CheckQTN && "Dependent template name canonicalization broken");
6050 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006051 }
6052
6053 DependentTemplateNames.InsertNode(QTN, InsertPos);
6054 return TemplateName(QTN);
6055}
6056
Douglas Gregor1aee05d2011-01-15 06:45:20 +00006057TemplateName
John McCall14606042011-06-30 08:33:18 +00006058ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6059 TemplateName replacement) const {
6060 llvm::FoldingSetNodeID ID;
6061 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
6062
6063 void *insertPos = 0;
6064 SubstTemplateTemplateParmStorage *subst
6065 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6066
6067 if (!subst) {
6068 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6069 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6070 }
6071
6072 return TemplateName(subst);
6073}
6074
6075TemplateName
Douglas Gregor1aee05d2011-01-15 06:45:20 +00006076ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6077 const TemplateArgument &ArgPack) const {
6078 ASTContext &Self = const_cast<ASTContext &>(*this);
6079 llvm::FoldingSetNodeID ID;
6080 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
6081
6082 void *InsertPos = 0;
6083 SubstTemplateTemplateParmPackStorage *Subst
6084 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6085
6086 if (!Subst) {
John McCall14606042011-06-30 08:33:18 +00006087 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor1aee05d2011-01-15 06:45:20 +00006088 ArgPack.pack_size(),
6089 ArgPack.pack_begin());
6090 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6091 }
6092
6093 return TemplateName(Subst);
6094}
6095
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006096/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00006097/// TargetInfo, produce the corresponding type. The unsigned @p Type
6098/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00006099CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006100 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00006101 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006102 case TargetInfo::SignedShort: return ShortTy;
6103 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6104 case TargetInfo::SignedInt: return IntTy;
6105 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6106 case TargetInfo::SignedLong: return LongTy;
6107 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6108 case TargetInfo::SignedLongLong: return LongLongTy;
6109 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6110 }
6111
David Blaikieb219cfc2011-09-23 05:06:16 +00006112 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006113}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00006114
6115//===----------------------------------------------------------------------===//
6116// Type Predicates.
6117//===----------------------------------------------------------------------===//
6118
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00006119/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6120/// garbage collection attribute.
6121///
John McCallae278a32011-01-12 00:34:59 +00006122Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikie4e4d0842012-03-11 07:00:24 +00006123 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCallae278a32011-01-12 00:34:59 +00006124 return Qualifiers::GCNone;
6125
David Blaikie4e4d0842012-03-11 07:00:24 +00006126 assert(getLangOpts().ObjC1);
John McCallae278a32011-01-12 00:34:59 +00006127 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6128
6129 // Default behaviour under objective-C's gc is for ObjC pointers
6130 // (or pointers to them) be treated as though they were declared
6131 // as __strong.
6132 if (GCAttrs == Qualifiers::GCNone) {
6133 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6134 return Qualifiers::Strong;
6135 else if (Ty->isPointerType())
6136 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6137 } else {
6138 // It's not valid to set GC attributes on anything that isn't a
6139 // pointer.
6140#ifndef NDEBUG
6141 QualType CT = Ty->getCanonicalTypeInternal();
6142 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6143 CT = AT->getElementType();
6144 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6145#endif
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00006146 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00006147 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00006148}
6149
Chris Lattner6ac46a42008-04-07 06:51:04 +00006150//===----------------------------------------------------------------------===//
6151// Type Compatibility Testing
6152//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00006153
Mike Stump1eb44332009-09-09 15:08:12 +00006154/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00006155/// compatible.
6156static bool areCompatVectorTypes(const VectorType *LHS,
6157 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00006158 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00006159 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00006160 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00006161}
6162
Douglas Gregor255210e2010-08-06 10:14:59 +00006163bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6164 QualType SecondVec) {
6165 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6166 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6167
6168 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6169 return true;
6170
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00006171 // Treat Neon vector types and most AltiVec vector types as if they are the
6172 // equivalent GCC vector types.
Douglas Gregor255210e2010-08-06 10:14:59 +00006173 const VectorType *First = FirstVec->getAs<VectorType>();
6174 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00006175 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor255210e2010-08-06 10:14:59 +00006176 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00006177 First->getVectorKind() != VectorType::AltiVecPixel &&
6178 First->getVectorKind() != VectorType::AltiVecBool &&
6179 Second->getVectorKind() != VectorType::AltiVecPixel &&
6180 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor255210e2010-08-06 10:14:59 +00006181 return true;
6182
6183 return false;
6184}
6185
Steve Naroff4084c302009-07-23 01:01:38 +00006186//===----------------------------------------------------------------------===//
6187// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6188//===----------------------------------------------------------------------===//
6189
6190/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6191/// inheritance hierarchy of 'rProto'.
Jay Foad4ba2a172011-01-12 09:06:06 +00006192bool
6193ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6194 ObjCProtocolDecl *rProto) const {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00006195 if (declaresSameEntity(lProto, rProto))
Steve Naroff4084c302009-07-23 01:01:38 +00006196 return true;
6197 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
6198 E = rProto->protocol_end(); PI != E; ++PI)
6199 if (ProtocolCompatibleWithProtocol(lProto, *PI))
6200 return true;
6201 return false;
6202}
6203
Dmitri Gribenko4c3b8a32012-08-28 02:49:14 +00006204/// QualifiedIdConformsQualifiedId - compare id<pr,...> with id<pr1,...>
Steve Naroff4084c302009-07-23 01:01:38 +00006205/// return true if lhs's protocols conform to rhs's protocol; false
6206/// otherwise.
6207bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
6208 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
6209 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
6210 return false;
6211}
6212
Dmitri Gribenko4c3b8a32012-08-28 02:49:14 +00006213/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6214/// Class<pr1, ...>.
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00006215bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6216 QualType rhs) {
6217 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6218 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6219 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6220
6221 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6222 E = lhsQID->qual_end(); I != E; ++I) {
6223 bool match = false;
6224 ObjCProtocolDecl *lhsProto = *I;
6225 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6226 E = rhsOPT->qual_end(); J != E; ++J) {
6227 ObjCProtocolDecl *rhsProto = *J;
6228 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6229 match = true;
6230 break;
6231 }
6232 }
6233 if (!match)
6234 return false;
6235 }
6236 return true;
6237}
6238
Steve Naroff4084c302009-07-23 01:01:38 +00006239/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6240/// ObjCQualifiedIDType.
6241bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6242 bool compare) {
6243 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00006244 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00006245 lhs->isObjCIdType() || lhs->isObjCClassType())
6246 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00006247 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00006248 rhs->isObjCIdType() || rhs->isObjCClassType())
6249 return true;
6250
6251 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00006252 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00006253
Steve Naroff4084c302009-07-23 01:01:38 +00006254 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006255
Steve Naroff4084c302009-07-23 01:01:38 +00006256 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006257 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00006258 // make sure we check the class hierarchy.
6259 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6260 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6261 E = lhsQID->qual_end(); I != E; ++I) {
6262 // when comparing an id<P> on lhs with a static type on rhs,
6263 // see if static class implements all of id's protocols, directly or
6264 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00006265 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00006266 return false;
6267 }
6268 }
6269 // If there are no qualifiers and no interface, we have an 'id'.
6270 return true;
6271 }
Mike Stump1eb44332009-09-09 15:08:12 +00006272 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00006273 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6274 E = lhsQID->qual_end(); I != E; ++I) {
6275 ObjCProtocolDecl *lhsProto = *I;
6276 bool match = false;
6277
6278 // when comparing an id<P> on lhs with a static type on rhs,
6279 // see if static class implements all of id's protocols, directly or
6280 // through its super class and categories.
6281 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6282 E = rhsOPT->qual_end(); J != E; ++J) {
6283 ObjCProtocolDecl *rhsProto = *J;
6284 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6285 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6286 match = true;
6287 break;
6288 }
6289 }
Mike Stump1eb44332009-09-09 15:08:12 +00006290 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00006291 // make sure we check the class hierarchy.
6292 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6293 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6294 E = lhsQID->qual_end(); I != E; ++I) {
6295 // when comparing an id<P> on lhs with a static type on rhs,
6296 // see if static class implements all of id's protocols, directly or
6297 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00006298 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00006299 match = true;
6300 break;
6301 }
6302 }
6303 }
6304 if (!match)
6305 return false;
6306 }
Mike Stump1eb44332009-09-09 15:08:12 +00006307
Steve Naroff4084c302009-07-23 01:01:38 +00006308 return true;
6309 }
Mike Stump1eb44332009-09-09 15:08:12 +00006310
Steve Naroff4084c302009-07-23 01:01:38 +00006311 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6312 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6313
Mike Stump1eb44332009-09-09 15:08:12 +00006314 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00006315 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006316 // If both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00006317 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
6318 E = lhsOPT->qual_end(); I != E; ++I) {
6319 ObjCProtocolDecl *lhsProto = *I;
6320 bool match = false;
6321
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006322 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff4084c302009-07-23 01:01:38 +00006323 // see if static class implements all of id's protocols, directly or
6324 // through its super class and categories.
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006325 // First, lhs protocols in the qualifier list must be found, direct
6326 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff4084c302009-07-23 01:01:38 +00006327 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6328 E = rhsQID->qual_end(); J != E; ++J) {
6329 ObjCProtocolDecl *rhsProto = *J;
6330 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6331 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6332 match = true;
6333 break;
6334 }
6335 }
6336 if (!match)
6337 return false;
6338 }
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006339
6340 // Static class's protocols, or its super class or category protocols
6341 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6342 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6343 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6344 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6345 // This is rather dubious but matches gcc's behavior. If lhs has
6346 // no type qualifier and its class has no static protocol(s)
6347 // assume that it is mismatch.
6348 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6349 return false;
6350 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6351 LHSInheritedProtocols.begin(),
6352 E = LHSInheritedProtocols.end(); I != E; ++I) {
6353 bool match = false;
6354 ObjCProtocolDecl *lhsProto = (*I);
6355 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6356 E = rhsQID->qual_end(); J != E; ++J) {
6357 ObjCProtocolDecl *rhsProto = *J;
6358 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6359 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6360 match = true;
6361 break;
6362 }
6363 }
6364 if (!match)
6365 return false;
6366 }
6367 }
Steve Naroff4084c302009-07-23 01:01:38 +00006368 return true;
6369 }
6370 return false;
6371}
6372
Eli Friedman3d815e72008-08-22 00:56:42 +00006373/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00006374/// compatible for assignment from RHS to LHS. This handles validation of any
6375/// protocol qualifiers on the LHS or RHS.
6376///
Steve Naroff14108da2009-07-10 23:34:53 +00006377bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6378 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00006379 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6380 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6381
Steve Naroffde2e22d2009-07-15 18:40:39 +00006382 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00006383 if (LHS->isObjCUnqualifiedIdOrClass() ||
6384 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00006385 return true;
6386
John McCallc12c5bb2010-05-15 11:32:37 +00006387 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00006388 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6389 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00006390 false);
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00006391
6392 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6393 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6394 QualType(RHSOPT,0));
6395
John McCallc12c5bb2010-05-15 11:32:37 +00006396 // If we have 2 user-defined types, fall into that path.
6397 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00006398 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00006399
Steve Naroff4084c302009-07-23 01:01:38 +00006400 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00006401}
6402
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006403/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00006404/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006405/// arguments in block literals. When passed as arguments, passing 'A*' where
6406/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6407/// not OK. For the return type, the opposite is not OK.
6408bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6409 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006410 const ObjCObjectPointerType *RHSOPT,
6411 bool BlockReturnType) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00006412 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006413 return true;
6414
6415 if (LHSOPT->isObjCBuiltinType()) {
6416 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6417 }
6418
Fariborz Jahaniana9834482010-04-06 17:23:39 +00006419 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006420 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6421 QualType(RHSOPT,0),
6422 false);
6423
6424 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6425 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6426 if (LHS && RHS) { // We have 2 user-defined types.
6427 if (LHS != RHS) {
6428 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006429 return BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006430 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006431 return !BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006432 }
6433 else
6434 return true;
6435 }
6436 return false;
6437}
6438
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006439/// getIntersectionOfProtocols - This routine finds the intersection of set
6440/// of protocols inherited from two distinct objective-c pointer objects.
6441/// It is used to build composite qualifier list of the composite type of
6442/// the conditional expression involving two objective-c pointer objects.
6443static
6444void getIntersectionOfProtocols(ASTContext &Context,
6445 const ObjCObjectPointerType *LHSOPT,
6446 const ObjCObjectPointerType *RHSOPT,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006447 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006448
John McCallc12c5bb2010-05-15 11:32:37 +00006449 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6450 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6451 assert(LHS->getInterface() && "LHS must have an interface base");
6452 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006453
6454 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6455 unsigned LHSNumProtocols = LHS->getNumProtocols();
6456 if (LHSNumProtocols > 0)
6457 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6458 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006459 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006460 Context.CollectInheritedProtocols(LHS->getInterface(),
6461 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006462 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6463 LHSInheritedProtocols.end());
6464 }
6465
6466 unsigned RHSNumProtocols = RHS->getNumProtocols();
6467 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00006468 ObjCProtocolDecl **RHSProtocols =
6469 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006470 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6471 if (InheritedProtocolSet.count(RHSProtocols[i]))
6472 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier30601782011-08-17 23:08:45 +00006473 } else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006474 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006475 Context.CollectInheritedProtocols(RHS->getInterface(),
6476 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006477 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6478 RHSInheritedProtocols.begin(),
6479 E = RHSInheritedProtocols.end(); I != E; ++I)
6480 if (InheritedProtocolSet.count((*I)))
6481 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006482 }
6483}
6484
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006485/// areCommonBaseCompatible - Returns common base class of the two classes if
6486/// one found. Note that this is O'2 algorithm. But it will be called as the
6487/// last type comparison in a ?-exp of ObjC pointer types before a
6488/// warning is issued. So, its invokation is extremely rare.
6489QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00006490 const ObjCObjectPointerType *Lptr,
6491 const ObjCObjectPointerType *Rptr) {
6492 const ObjCObjectType *LHS = Lptr->getObjectType();
6493 const ObjCObjectType *RHS = Rptr->getObjectType();
6494 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6495 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor60ef3082011-12-15 00:29:59 +00006496 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006497 return QualType();
6498
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00006499 do {
John McCallc12c5bb2010-05-15 11:32:37 +00006500 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006501 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006502 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006503 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6504
6505 QualType Result = QualType(LHS, 0);
6506 if (!Protocols.empty())
6507 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6508 Result = getObjCObjectPointerType(Result);
6509 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006510 }
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00006511 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006512
6513 return QualType();
6514}
6515
John McCallc12c5bb2010-05-15 11:32:37 +00006516bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6517 const ObjCObjectType *RHS) {
6518 assert(LHS->getInterface() && "LHS is not an interface type");
6519 assert(RHS->getInterface() && "RHS is not an interface type");
6520
Chris Lattner6ac46a42008-04-07 06:51:04 +00006521 // Verify that the base decls are compatible: the RHS must be a subclass of
6522 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00006523 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00006524 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006525
Chris Lattner6ac46a42008-04-07 06:51:04 +00006526 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6527 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00006528 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00006529 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00006530
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006531 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6532 // more detailed analysis is required.
6533 if (RHS->getNumProtocols() == 0) {
6534 // OK, if LHS is a superclass of RHS *and*
6535 // this superclass is assignment compatible with LHS.
6536 // false otherwise.
Fariborz Jahanian627788c2011-04-12 16:34:14 +00006537 bool IsSuperClass =
6538 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6539 if (IsSuperClass) {
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006540 // OK if conversion of LHS to SuperClass results in narrowing of types
6541 // ; i.e., SuperClass may implement at least one of the protocols
6542 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6543 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6544 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian627788c2011-04-12 16:34:14 +00006545 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006546 // If super class has no protocols, it is not a match.
6547 if (SuperClassInheritedProtocols.empty())
6548 return false;
6549
6550 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6551 LHSPE = LHS->qual_end();
6552 LHSPI != LHSPE; LHSPI++) {
6553 bool SuperImplementsProtocol = false;
6554 ObjCProtocolDecl *LHSProto = (*LHSPI);
6555
6556 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6557 SuperClassInheritedProtocols.begin(),
6558 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6559 ObjCProtocolDecl *SuperClassProto = (*I);
6560 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6561 SuperImplementsProtocol = true;
6562 break;
6563 }
6564 }
6565 if (!SuperImplementsProtocol)
6566 return false;
6567 }
6568 return true;
6569 }
6570 return false;
6571 }
Mike Stump1eb44332009-09-09 15:08:12 +00006572
John McCallc12c5bb2010-05-15 11:32:37 +00006573 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6574 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006575 LHSPI != LHSPE; LHSPI++) {
6576 bool RHSImplementsProtocol = false;
6577
6578 // If the RHS doesn't implement the protocol on the left, the types
6579 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00006580 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6581 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00006582 RHSPI != RHSPE; RHSPI++) {
6583 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006584 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00006585 break;
6586 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006587 }
6588 // FIXME: For better diagnostics, consider passing back the protocol name.
6589 if (!RHSImplementsProtocol)
6590 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00006591 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006592 // The RHS implements all protocols listed on the LHS.
6593 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00006594}
6595
Steve Naroff389bf462009-02-12 17:52:19 +00006596bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6597 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00006598 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6599 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00006600
Steve Naroff14108da2009-07-10 23:34:53 +00006601 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00006602 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00006603
6604 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6605 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00006606}
6607
Douglas Gregor569c3162010-08-07 11:51:51 +00006608bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6609 return canAssignObjCInterfaces(
6610 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6611 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6612}
6613
Mike Stump1eb44332009-09-09 15:08:12 +00006614/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00006615/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00006616/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00006617/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor447234d2010-07-29 15:18:02 +00006618bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6619 bool CompareUnqualified) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006620 if (getLangOpts().CPlusPlus)
Douglas Gregor0e709ab2010-02-03 21:02:30 +00006621 return hasSameType(LHS, RHS);
6622
Douglas Gregor447234d2010-07-29 15:18:02 +00006623 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman3d815e72008-08-22 00:56:42 +00006624}
6625
Fariborz Jahanianc286f382011-07-12 22:05:16 +00006626bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanian82378392011-07-12 23:20:13 +00006627 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc286f382011-07-12 22:05:16 +00006628}
6629
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006630bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6631 return !mergeTypes(LHS, RHS, true).isNull();
6632}
6633
Peter Collingbourne48466752010-10-24 18:30:18 +00006634/// mergeTransparentUnionType - if T is a transparent union type and a member
6635/// of T is compatible with SubType, return the merged type, else return
6636/// QualType()
6637QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6638 bool OfBlockPointer,
6639 bool Unqualified) {
6640 if (const RecordType *UT = T->getAsUnionType()) {
6641 RecordDecl *UD = UT->getDecl();
6642 if (UD->hasAttr<TransparentUnionAttr>()) {
6643 for (RecordDecl::field_iterator it = UD->field_begin(),
6644 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbournef91d7572010-12-02 21:00:06 +00006645 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00006646 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6647 if (!MT.isNull())
6648 return MT;
6649 }
6650 }
6651 }
6652
6653 return QualType();
6654}
6655
6656/// mergeFunctionArgumentTypes - merge two types which appear as function
6657/// argument types
6658QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
6659 bool OfBlockPointer,
6660 bool Unqualified) {
6661 // GNU extension: two types are compatible if they appear as a function
6662 // argument, one of the types is a transparent union type and the other
6663 // type is compatible with a union member
6664 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6665 Unqualified);
6666 if (!lmerge.isNull())
6667 return lmerge;
6668
6669 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6670 Unqualified);
6671 if (!rmerge.isNull())
6672 return rmerge;
6673
6674 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6675}
6676
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006677QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor447234d2010-07-29 15:18:02 +00006678 bool OfBlockPointer,
6679 bool Unqualified) {
John McCall183700f2009-09-21 23:43:11 +00006680 const FunctionType *lbase = lhs->getAs<FunctionType>();
6681 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00006682 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6683 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00006684 bool allLTypes = true;
6685 bool allRTypes = true;
6686
6687 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006688 QualType retType;
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00006689 if (OfBlockPointer) {
6690 QualType RHS = rbase->getResultType();
6691 QualType LHS = lbase->getResultType();
6692 bool UnqualifiedResult = Unqualified;
6693 if (!UnqualifiedResult)
6694 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006695 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00006696 }
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006697 else
John McCall8cc246c2010-12-15 01:06:38 +00006698 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6699 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006700 if (retType.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006701
6702 if (Unqualified)
6703 retType = retType.getUnqualifiedType();
6704
6705 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6706 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6707 if (Unqualified) {
6708 LRetType = LRetType.getUnqualifiedType();
6709 RRetType = RRetType.getUnqualifiedType();
6710 }
6711
6712 if (getCanonicalType(retType) != LRetType)
Chris Lattner61710852008-10-05 17:34:18 +00006713 allLTypes = false;
Douglas Gregor447234d2010-07-29 15:18:02 +00006714 if (getCanonicalType(retType) != RRetType)
Chris Lattner61710852008-10-05 17:34:18 +00006715 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00006716
Daniel Dunbar6a15c852010-04-28 16:20:58 +00006717 // FIXME: double check this
6718 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6719 // rbase->getRegParmAttr() != 0 &&
6720 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00006721 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6722 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8cc246c2010-12-15 01:06:38 +00006723
Douglas Gregorab8bbf42010-01-18 17:14:39 +00006724 // Compatible functions must have compatible calling conventions
John McCall8cc246c2010-12-15 01:06:38 +00006725 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00006726 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00006727
John McCall8cc246c2010-12-15 01:06:38 +00006728 // Regparm is part of the calling convention.
Eli Friedmana49218e2011-04-09 08:18:08 +00006729 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6730 return QualType();
John McCall8cc246c2010-12-15 01:06:38 +00006731 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6732 return QualType();
6733
John McCallf85e1932011-06-15 23:02:42 +00006734 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6735 return QualType();
6736
John McCall8cc246c2010-12-15 01:06:38 +00006737 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6738 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8cc246c2010-12-15 01:06:38 +00006739
Rafael Espindola8b8a09e2012-11-29 16:09:03 +00006740 if (lbaseInfo.getNoReturn() != NoReturn)
6741 allLTypes = false;
6742 if (rbaseInfo.getNoReturn() != NoReturn)
6743 allRTypes = false;
6744
John McCallf85e1932011-06-15 23:02:42 +00006745 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00006746
Eli Friedman3d815e72008-08-22 00:56:42 +00006747 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00006748 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6749 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00006750 unsigned lproto_nargs = lproto->getNumArgs();
6751 unsigned rproto_nargs = rproto->getNumArgs();
6752
6753 // Compatible functions must have the same number of arguments
6754 if (lproto_nargs != rproto_nargs)
6755 return QualType();
6756
6757 // Variadic and non-variadic functions aren't compatible
6758 if (lproto->isVariadic() != rproto->isVariadic())
6759 return QualType();
6760
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00006761 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6762 return QualType();
6763
Fariborz Jahanian78213e42011-09-28 21:52:05 +00006764 if (LangOpts.ObjCAutoRefCount &&
6765 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6766 return QualType();
6767
Eli Friedman3d815e72008-08-22 00:56:42 +00006768 // Check argument compatibility
Chris Lattner5f9e2722011-07-23 10:55:15 +00006769 SmallVector<QualType, 10> types;
Eli Friedman3d815e72008-08-22 00:56:42 +00006770 for (unsigned i = 0; i < lproto_nargs; i++) {
6771 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
6772 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00006773 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
6774 OfBlockPointer,
6775 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006776 if (argtype.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006777
6778 if (Unqualified)
6779 argtype = argtype.getUnqualifiedType();
6780
Eli Friedman3d815e72008-08-22 00:56:42 +00006781 types.push_back(argtype);
Douglas Gregor447234d2010-07-29 15:18:02 +00006782 if (Unqualified) {
6783 largtype = largtype.getUnqualifiedType();
6784 rargtype = rargtype.getUnqualifiedType();
6785 }
6786
Chris Lattner61710852008-10-05 17:34:18 +00006787 if (getCanonicalType(argtype) != getCanonicalType(largtype))
6788 allLTypes = false;
6789 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
6790 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00006791 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00006792
Eli Friedman3d815e72008-08-22 00:56:42 +00006793 if (allLTypes) return lhs;
6794 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00006795
6796 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
6797 EPI.ExtInfo = einfo;
Jordan Rosebea522f2013-03-08 21:51:21 +00006798 return getFunctionType(retType, types, EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00006799 }
6800
6801 if (lproto) allRTypes = false;
6802 if (rproto) allLTypes = false;
6803
Douglas Gregor72564e72009-02-26 23:50:07 +00006804 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00006805 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00006806 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00006807 if (proto->isVariadic()) return QualType();
6808 // Check that the types are compatible with the types that
6809 // would result from default argument promotions (C99 6.7.5.3p15).
6810 // The only types actually affected are promotable integer
6811 // types and floats, which would be passed as a different
6812 // type depending on whether the prototype is visible.
6813 unsigned proto_nargs = proto->getNumArgs();
6814 for (unsigned i = 0; i < proto_nargs; ++i) {
6815 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00006816
Eli Friedmanc586d5d2012-08-30 00:44:15 +00006817 // Look at the converted type of enum types, since that is the type used
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00006818 // to pass enum values.
Eli Friedmanc586d5d2012-08-30 00:44:15 +00006819 if (const EnumType *Enum = argTy->getAs<EnumType>()) {
6820 argTy = Enum->getDecl()->getIntegerType();
6821 if (argTy.isNull())
6822 return QualType();
6823 }
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00006824
Eli Friedman3d815e72008-08-22 00:56:42 +00006825 if (argTy->isPromotableIntegerType() ||
6826 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
6827 return QualType();
6828 }
6829
6830 if (allLTypes) return lhs;
6831 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00006832
6833 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
6834 EPI.ExtInfo = einfo;
Jordan Rosebea522f2013-03-08 21:51:21 +00006835 return getFunctionType(retType,
6836 ArrayRef<QualType>(proto->arg_type_begin(),
6837 proto->getNumArgs()),
6838 EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00006839 }
6840
6841 if (allLTypes) return lhs;
6842 if (allRTypes) return rhs;
John McCall8cc246c2010-12-15 01:06:38 +00006843 return getFunctionNoProtoType(retType, einfo);
Eli Friedman3d815e72008-08-22 00:56:42 +00006844}
6845
John McCallb9da7132013-03-21 00:10:07 +00006846/// Given that we have an enum type and a non-enum type, try to merge them.
6847static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
6848 QualType other, bool isBlockReturnType) {
6849 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
6850 // a signed integer type, or an unsigned integer type.
6851 // Compatibility is based on the underlying type, not the promotion
6852 // type.
6853 QualType underlyingType = ET->getDecl()->getIntegerType();
6854 if (underlyingType.isNull()) return QualType();
6855 if (Context.hasSameType(underlyingType, other))
6856 return other;
6857
6858 // In block return types, we're more permissive and accept any
6859 // integral type of the same size.
6860 if (isBlockReturnType && other->isIntegerType() &&
6861 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
6862 return other;
6863
6864 return QualType();
6865}
6866
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006867QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor447234d2010-07-29 15:18:02 +00006868 bool OfBlockPointer,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006869 bool Unqualified, bool BlockReturnType) {
Bill Wendling43d69752007-12-03 07:33:35 +00006870 // C++ [expr]: If an expression initially has the type "reference to T", the
6871 // type is adjusted to "T" prior to any further analysis, the expression
6872 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00006873 // expression is an lvalue unless the reference is an rvalue reference and
6874 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00006875 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
6876 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor447234d2010-07-29 15:18:02 +00006877
6878 if (Unqualified) {
6879 LHS = LHS.getUnqualifiedType();
6880 RHS = RHS.getUnqualifiedType();
6881 }
Douglas Gregor0e709ab2010-02-03 21:02:30 +00006882
Eli Friedman3d815e72008-08-22 00:56:42 +00006883 QualType LHSCan = getCanonicalType(LHS),
6884 RHSCan = getCanonicalType(RHS);
6885
6886 // If two types are identical, they are compatible.
6887 if (LHSCan == RHSCan)
6888 return LHS;
6889
John McCall0953e762009-09-24 19:53:00 +00006890 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00006891 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6892 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00006893 if (LQuals != RQuals) {
6894 // If any of these qualifiers are different, we have a type
6895 // mismatch.
6896 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCallf85e1932011-06-15 23:02:42 +00006897 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
6898 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall0953e762009-09-24 19:53:00 +00006899 return QualType();
6900
6901 // Exactly one GC qualifier difference is allowed: __strong is
6902 // okay if the other type has no GC qualifier but is an Objective
6903 // C object pointer (i.e. implicitly strong by default). We fix
6904 // this by pretending that the unqualified type was actually
6905 // qualified __strong.
6906 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6907 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6908 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6909
6910 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6911 return QualType();
6912
6913 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
6914 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
6915 }
6916 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
6917 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
6918 }
Eli Friedman3d815e72008-08-22 00:56:42 +00006919 return QualType();
John McCall0953e762009-09-24 19:53:00 +00006920 }
6921
6922 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00006923
Eli Friedman852d63b2009-06-01 01:22:52 +00006924 Type::TypeClass LHSClass = LHSCan->getTypeClass();
6925 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00006926
Chris Lattner1adb8832008-01-14 05:45:46 +00006927 // We want to consider the two function types to be the same for these
6928 // comparisons, just force one to the other.
6929 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
6930 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00006931
6932 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00006933 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
6934 LHSClass = Type::ConstantArray;
6935 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
6936 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00006937
John McCallc12c5bb2010-05-15 11:32:37 +00006938 // ObjCInterfaces are just specialized ObjCObjects.
6939 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
6940 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
6941
Nate Begeman213541a2008-04-18 23:10:10 +00006942 // Canonicalize ExtVector -> Vector.
6943 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
6944 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00006945
Chris Lattnera36a61f2008-04-07 05:43:21 +00006946 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00006947 if (LHSClass != RHSClass) {
John McCallb9da7132013-03-21 00:10:07 +00006948 // Note that we only have special rules for turning block enum
6949 // returns into block int returns, not vice-versa.
John McCall183700f2009-09-21 23:43:11 +00006950 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCallb9da7132013-03-21 00:10:07 +00006951 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmanbab96962008-02-12 08:46:17 +00006952 }
John McCall183700f2009-09-21 23:43:11 +00006953 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCallb9da7132013-03-21 00:10:07 +00006954 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmanbab96962008-02-12 08:46:17 +00006955 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00006956 // allow block pointer type to match an 'id' type.
Fariborz Jahanian41963632012-01-26 17:08:50 +00006957 if (OfBlockPointer && !BlockReturnType) {
6958 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
6959 return LHS;
6960 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
6961 return RHS;
6962 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00006963
Eli Friedman3d815e72008-08-22 00:56:42 +00006964 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00006965 }
Eli Friedman3d815e72008-08-22 00:56:42 +00006966
Steve Naroff4a746782008-01-09 22:43:08 +00006967 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00006968 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00006969#define TYPE(Class, Base)
6970#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00006971#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00006972#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
6973#define DEPENDENT_TYPE(Class, Base) case Type::Class:
6974#include "clang/AST/TypeNodes.def"
David Blaikieb219cfc2011-09-23 05:06:16 +00006975 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregor72564e72009-02-26 23:50:07 +00006976
Sebastian Redl7c80bd62009-03-16 23:22:08 +00006977 case Type::LValueReference:
6978 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00006979 case Type::MemberPointer:
David Blaikieb219cfc2011-09-23 05:06:16 +00006980 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregor72564e72009-02-26 23:50:07 +00006981
John McCallc12c5bb2010-05-15 11:32:37 +00006982 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00006983 case Type::IncompleteArray:
6984 case Type::VariableArray:
6985 case Type::FunctionProto:
6986 case Type::ExtVector:
David Blaikieb219cfc2011-09-23 05:06:16 +00006987 llvm_unreachable("Types are eliminated above");
Douglas Gregor72564e72009-02-26 23:50:07 +00006988
Chris Lattner1adb8832008-01-14 05:45:46 +00006989 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00006990 {
6991 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00006992 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
6993 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006994 if (Unqualified) {
6995 LHSPointee = LHSPointee.getUnqualifiedType();
6996 RHSPointee = RHSPointee.getUnqualifiedType();
6997 }
6998 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
6999 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00007000 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00007001 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00007002 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00007003 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00007004 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00007005 return getPointerType(ResultType);
7006 }
Steve Naroffc0febd52008-12-10 17:49:55 +00007007 case Type::BlockPointer:
7008 {
7009 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00007010 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7011 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00007012 if (Unqualified) {
7013 LHSPointee = LHSPointee.getUnqualifiedType();
7014 RHSPointee = RHSPointee.getUnqualifiedType();
7015 }
7016 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7017 Unqualified);
Steve Naroffc0febd52008-12-10 17:49:55 +00007018 if (ResultType.isNull()) return QualType();
7019 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7020 return LHS;
7021 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7022 return RHS;
7023 return getBlockPointerType(ResultType);
7024 }
Eli Friedmanb001de72011-10-06 23:00:33 +00007025 case Type::Atomic:
7026 {
7027 // Merge two pointer types, while trying to preserve typedef info
7028 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7029 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7030 if (Unqualified) {
7031 LHSValue = LHSValue.getUnqualifiedType();
7032 RHSValue = RHSValue.getUnqualifiedType();
7033 }
7034 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7035 Unqualified);
7036 if (ResultType.isNull()) return QualType();
7037 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7038 return LHS;
7039 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7040 return RHS;
7041 return getAtomicType(ResultType);
7042 }
Chris Lattner1adb8832008-01-14 05:45:46 +00007043 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00007044 {
7045 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7046 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7047 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7048 return QualType();
7049
7050 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7051 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor447234d2010-07-29 15:18:02 +00007052 if (Unqualified) {
7053 LHSElem = LHSElem.getUnqualifiedType();
7054 RHSElem = RHSElem.getUnqualifiedType();
7055 }
7056
7057 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00007058 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00007059 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7060 return LHS;
7061 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7062 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00007063 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7064 ArrayType::ArraySizeModifier(), 0);
7065 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7066 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00007067 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7068 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00007069 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7070 return LHS;
7071 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7072 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00007073 if (LVAT) {
7074 // FIXME: This isn't correct! But tricky to implement because
7075 // the array's size has to be the size of LHS, but the type
7076 // has to be different.
7077 return LHS;
7078 }
7079 if (RVAT) {
7080 // FIXME: This isn't correct! But tricky to implement because
7081 // the array's size has to be the size of RHS, but the type
7082 // has to be different.
7083 return RHS;
7084 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00007085 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7086 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00007087 return getIncompleteArrayType(ResultType,
7088 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00007089 }
Chris Lattner1adb8832008-01-14 05:45:46 +00007090 case Type::FunctionNoProto:
Douglas Gregor447234d2010-07-29 15:18:02 +00007091 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregor72564e72009-02-26 23:50:07 +00007092 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00007093 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00007094 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00007095 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00007096 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00007097 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00007098 case Type::Complex:
7099 // Distinct complex types are incompatible.
7100 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00007101 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00007102 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00007103 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7104 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00007105 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00007106 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00007107 case Type::ObjCObject: {
7108 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00007109 // FIXME: This should be type compatibility, e.g. whether
7110 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00007111 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7112 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7113 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00007114 return LHS;
7115
Eli Friedman3d815e72008-08-22 00:56:42 +00007116 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00007117 }
Steve Naroff14108da2009-07-10 23:34:53 +00007118 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00007119 if (OfBlockPointer) {
7120 if (canAssignObjCInterfacesInBlockPointer(
7121 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00007122 RHS->getAs<ObjCObjectPointerType>(),
7123 BlockReturnType))
David Blaikie7530c032012-01-17 06:56:22 +00007124 return LHS;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00007125 return QualType();
7126 }
John McCall183700f2009-09-21 23:43:11 +00007127 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7128 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00007129 return LHS;
7130
Steve Naroffbc76dd02008-12-10 22:14:21 +00007131 return QualType();
David Blaikie7530c032012-01-17 06:56:22 +00007132 }
Steve Naroffec0550f2007-10-15 20:41:53 +00007133 }
Douglas Gregor72564e72009-02-26 23:50:07 +00007134
David Blaikie7530c032012-01-17 06:56:22 +00007135 llvm_unreachable("Invalid Type::Class!");
Steve Naroffec0550f2007-10-15 20:41:53 +00007136}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00007137
Fariborz Jahanian78213e42011-09-28 21:52:05 +00007138bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7139 const FunctionProtoType *FromFunctionType,
7140 const FunctionProtoType *ToFunctionType) {
7141 if (FromFunctionType->hasAnyConsumedArgs() !=
7142 ToFunctionType->hasAnyConsumedArgs())
7143 return false;
7144 FunctionProtoType::ExtProtoInfo FromEPI =
7145 FromFunctionType->getExtProtoInfo();
7146 FunctionProtoType::ExtProtoInfo ToEPI =
7147 ToFunctionType->getExtProtoInfo();
7148 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
7149 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
7150 ArgIdx != NumArgs; ++ArgIdx) {
7151 if (FromEPI.ConsumedArguments[ArgIdx] !=
7152 ToEPI.ConsumedArguments[ArgIdx])
7153 return false;
7154 }
7155 return true;
7156}
7157
Fariborz Jahanian2390a722010-05-19 21:37:30 +00007158/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7159/// 'RHS' attributes and returns the merged version; including for function
7160/// return types.
7161QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7162 QualType LHSCan = getCanonicalType(LHS),
7163 RHSCan = getCanonicalType(RHS);
7164 // If two types are identical, they are compatible.
7165 if (LHSCan == RHSCan)
7166 return LHS;
7167 if (RHSCan->isFunctionType()) {
7168 if (!LHSCan->isFunctionType())
7169 return QualType();
7170 QualType OldReturnType =
7171 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
7172 QualType NewReturnType =
7173 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
7174 QualType ResReturnType =
7175 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7176 if (ResReturnType.isNull())
7177 return QualType();
7178 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7179 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7180 // In either case, use OldReturnType to build the new function type.
7181 const FunctionType *F = LHS->getAs<FunctionType>();
7182 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalle23cf432010-12-14 08:05:40 +00007183 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7184 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00007185 QualType ResultType
Jordan Rosebea522f2013-03-08 21:51:21 +00007186 = getFunctionType(OldReturnType,
7187 ArrayRef<QualType>(FPT->arg_type_begin(),
7188 FPT->getNumArgs()),
7189 EPI);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00007190 return ResultType;
7191 }
7192 }
7193 return QualType();
7194 }
7195
7196 // If the qualifiers are different, the types can still be merged.
7197 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7198 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7199 if (LQuals != RQuals) {
7200 // If any of these qualifiers are different, we have a type mismatch.
7201 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7202 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7203 return QualType();
7204
7205 // Exactly one GC qualifier difference is allowed: __strong is
7206 // okay if the other type has no GC qualifier but is an Objective
7207 // C object pointer (i.e. implicitly strong by default). We fix
7208 // this by pretending that the unqualified type was actually
7209 // qualified __strong.
7210 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7211 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7212 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7213
7214 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7215 return QualType();
7216
7217 if (GC_L == Qualifiers::Strong)
7218 return LHS;
7219 if (GC_R == Qualifiers::Strong)
7220 return RHS;
7221 return QualType();
7222 }
7223
7224 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7225 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7226 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7227 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7228 if (ResQT == LHSBaseQT)
7229 return LHS;
7230 if (ResQT == RHSBaseQT)
7231 return RHS;
7232 }
7233 return QualType();
7234}
7235
Chris Lattner5426bf62008-04-07 07:01:58 +00007236//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00007237// Integer Predicates
7238//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00007239
Jay Foad4ba2a172011-01-12 09:06:06 +00007240unsigned ASTContext::getIntWidth(QualType T) const {
John McCallf4c73712011-01-19 06:33:43 +00007241 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00007242 T = ET->getDecl()->getIntegerType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00007243 if (T->isBooleanType())
7244 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00007245 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00007246 return (unsigned)getTypeSize(T);
7247}
7248
Abramo Bagnara762f1592012-09-09 10:21:24 +00007249QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregorf6094622010-07-23 15:58:24 +00007250 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00007251
7252 // Turn <4 x signed int> -> <4 x unsigned int>
7253 if (const VectorType *VTy = T->getAs<VectorType>())
7254 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsone86d78c2010-11-10 21:56:12 +00007255 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattner6a2b9262009-10-17 20:33:28 +00007256
7257 // For enums, we return the unsigned version of the base type.
7258 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00007259 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00007260
7261 const BuiltinType *BTy = T->getAs<BuiltinType>();
7262 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00007263 switch (BTy->getKind()) {
7264 case BuiltinType::Char_S:
7265 case BuiltinType::SChar:
7266 return UnsignedCharTy;
7267 case BuiltinType::Short:
7268 return UnsignedShortTy;
7269 case BuiltinType::Int:
7270 return UnsignedIntTy;
7271 case BuiltinType::Long:
7272 return UnsignedLongTy;
7273 case BuiltinType::LongLong:
7274 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00007275 case BuiltinType::Int128:
7276 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00007277 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00007278 llvm_unreachable("Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00007279 }
7280}
7281
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00007282ASTMutationListener::~ASTMutationListener() { }
7283
Chris Lattner86df27b2009-06-14 00:45:47 +00007284
7285//===----------------------------------------------------------------------===//
7286// Builtin Type Computation
7287//===----------------------------------------------------------------------===//
7288
7289/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattner33daae62010-10-01 22:42:38 +00007290/// pointer over the consumed characters. This returns the resultant type. If
7291/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7292/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7293/// a vector of "i*".
Chris Lattner14e0e742010-10-01 22:53:11 +00007294///
7295/// RequiresICE is filled in on return to indicate whether the value is required
7296/// to be an Integer Constant Expression.
Jay Foad4ba2a172011-01-12 09:06:06 +00007297static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00007298 ASTContext::GetBuiltinTypeError &Error,
Chris Lattner14e0e742010-10-01 22:53:11 +00007299 bool &RequiresICE,
Chris Lattner33daae62010-10-01 22:42:38 +00007300 bool AllowTypeModifiers) {
Chris Lattner86df27b2009-06-14 00:45:47 +00007301 // Modifiers.
7302 int HowLong = 0;
7303 bool Signed = false, Unsigned = false;
Chris Lattner14e0e742010-10-01 22:53:11 +00007304 RequiresICE = false;
Chris Lattner393bd8e2010-10-01 07:13:18 +00007305
Chris Lattner33daae62010-10-01 22:42:38 +00007306 // Read the prefixed modifiers first.
Chris Lattner86df27b2009-06-14 00:45:47 +00007307 bool Done = false;
7308 while (!Done) {
7309 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00007310 default: Done = true; --Str; break;
Chris Lattner393bd8e2010-10-01 07:13:18 +00007311 case 'I':
Chris Lattner14e0e742010-10-01 22:53:11 +00007312 RequiresICE = true;
Chris Lattner393bd8e2010-10-01 07:13:18 +00007313 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007314 case 'S':
7315 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7316 assert(!Signed && "Can't use 'S' modifier multiple times!");
7317 Signed = true;
7318 break;
7319 case 'U':
7320 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7321 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7322 Unsigned = true;
7323 break;
7324 case 'L':
7325 assert(HowLong <= 2 && "Can't have LLLL modifier");
7326 ++HowLong;
7327 break;
7328 }
7329 }
7330
7331 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00007332
Chris Lattner86df27b2009-06-14 00:45:47 +00007333 // Read the base type.
7334 switch (*Str++) {
David Blaikieb219cfc2011-09-23 05:06:16 +00007335 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattner86df27b2009-06-14 00:45:47 +00007336 case 'v':
7337 assert(HowLong == 0 && !Signed && !Unsigned &&
7338 "Bad modifiers used with 'v'!");
7339 Type = Context.VoidTy;
7340 break;
7341 case 'f':
7342 assert(HowLong == 0 && !Signed && !Unsigned &&
7343 "Bad modifiers used with 'f'!");
7344 Type = Context.FloatTy;
7345 break;
7346 case 'd':
7347 assert(HowLong < 2 && !Signed && !Unsigned &&
7348 "Bad modifiers used with 'd'!");
7349 if (HowLong)
7350 Type = Context.LongDoubleTy;
7351 else
7352 Type = Context.DoubleTy;
7353 break;
7354 case 's':
7355 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7356 if (Unsigned)
7357 Type = Context.UnsignedShortTy;
7358 else
7359 Type = Context.ShortTy;
7360 break;
7361 case 'i':
7362 if (HowLong == 3)
7363 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7364 else if (HowLong == 2)
7365 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7366 else if (HowLong == 1)
7367 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7368 else
7369 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7370 break;
7371 case 'c':
7372 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7373 if (Signed)
7374 Type = Context.SignedCharTy;
7375 else if (Unsigned)
7376 Type = Context.UnsignedCharTy;
7377 else
7378 Type = Context.CharTy;
7379 break;
7380 case 'b': // boolean
7381 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7382 Type = Context.BoolTy;
7383 break;
7384 case 'z': // size_t.
7385 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7386 Type = Context.getSizeType();
7387 break;
7388 case 'F':
7389 Type = Context.getCFConstantStringType();
7390 break;
Fariborz Jahanianba8bda02010-11-09 21:38:20 +00007391 case 'G':
7392 Type = Context.getObjCIdType();
7393 break;
7394 case 'H':
7395 Type = Context.getObjCSelType();
7396 break;
Fariborz Jahanianf7992132013-01-04 18:45:40 +00007397 case 'M':
7398 Type = Context.getObjCSuperType();
7399 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007400 case 'a':
7401 Type = Context.getBuiltinVaListType();
7402 assert(!Type.isNull() && "builtin va list type not initialized!");
7403 break;
7404 case 'A':
7405 // This is a "reference" to a va_list; however, what exactly
7406 // this means depends on how va_list is defined. There are two
7407 // different kinds of va_list: ones passed by value, and ones
7408 // passed by reference. An example of a by-value va_list is
7409 // x86, where va_list is a char*. An example of by-ref va_list
7410 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7411 // we want this argument to be a char*&; for x86-64, we want
7412 // it to be a __va_list_tag*.
7413 Type = Context.getBuiltinVaListType();
7414 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattner14e0e742010-10-01 22:53:11 +00007415 if (Type->isArrayType())
Chris Lattner86df27b2009-06-14 00:45:47 +00007416 Type = Context.getArrayDecayedType(Type);
Chris Lattner14e0e742010-10-01 22:53:11 +00007417 else
Chris Lattner86df27b2009-06-14 00:45:47 +00007418 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00007419 break;
7420 case 'V': {
7421 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00007422 unsigned NumElements = strtoul(Str, &End, 10);
7423 assert(End != Str && "Missing vector size");
Chris Lattner86df27b2009-06-14 00:45:47 +00007424 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00007425
Chris Lattner14e0e742010-10-01 22:53:11 +00007426 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7427 RequiresICE, false);
7428 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattner33daae62010-10-01 22:42:38 +00007429
7430 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner788b0fd2010-06-23 06:00:24 +00007431 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00007432 VectorType::GenericVector);
Chris Lattner86df27b2009-06-14 00:45:47 +00007433 break;
7434 }
Douglas Gregorb4bc99b2012-06-07 18:08:25 +00007435 case 'E': {
7436 char *End;
7437
7438 unsigned NumElements = strtoul(Str, &End, 10);
7439 assert(End != Str && "Missing vector size");
7440
7441 Str = End;
7442
7443 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7444 false);
7445 Type = Context.getExtVectorType(ElementType, NumElements);
7446 break;
7447 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00007448 case 'X': {
Chris Lattner14e0e742010-10-01 22:53:11 +00007449 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7450 false);
7451 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregord3a23b22009-09-28 21:45:01 +00007452 Type = Context.getComplexType(ElementType);
7453 break;
Fariborz Jahaniancc075e42011-08-23 23:33:09 +00007454 }
7455 case 'Y' : {
7456 Type = Context.getPointerDiffType();
7457 break;
7458 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00007459 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00007460 Type = Context.getFILEType();
7461 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00007462 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00007463 return QualType();
7464 }
Mike Stumpfd612db2009-07-28 23:47:15 +00007465 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00007466 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00007467 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00007468 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00007469 else
7470 Type = Context.getjmp_bufType();
7471
Mike Stumpfd612db2009-07-28 23:47:15 +00007472 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00007473 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00007474 return QualType();
7475 }
7476 break;
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +00007477 case 'K':
7478 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7479 Type = Context.getucontext_tType();
7480
7481 if (Type.isNull()) {
7482 Error = ASTContext::GE_Missing_ucontext;
7483 return QualType();
7484 }
7485 break;
Eli Friedman6902e412012-11-27 02:58:24 +00007486 case 'p':
7487 Type = Context.getProcessIDType();
7488 break;
Mike Stump782fa302009-07-28 02:25:19 +00007489 }
Mike Stump1eb44332009-09-09 15:08:12 +00007490
Chris Lattner33daae62010-10-01 22:42:38 +00007491 // If there are modifiers and if we're allowed to parse them, go for it.
7492 Done = !AllowTypeModifiers;
Chris Lattner86df27b2009-06-14 00:45:47 +00007493 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00007494 switch (char c = *Str++) {
Chris Lattner33daae62010-10-01 22:42:38 +00007495 default: Done = true; --Str; break;
7496 case '*':
7497 case '&': {
7498 // Both pointers and references can have their pointee types
7499 // qualified with an address space.
7500 char *End;
7501 unsigned AddrSpace = strtoul(Str, &End, 10);
7502 if (End != Str && AddrSpace != 0) {
7503 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7504 Str = End;
7505 }
7506 if (c == '*')
7507 Type = Context.getPointerType(Type);
7508 else
7509 Type = Context.getLValueReferenceType(Type);
7510 break;
7511 }
7512 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7513 case 'C':
7514 Type = Type.withConst();
7515 break;
7516 case 'D':
7517 Type = Context.getVolatileType(Type);
7518 break;
Ted Kremenek18932a02012-01-20 21:40:12 +00007519 case 'R':
7520 Type = Type.withRestrict();
7521 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007522 }
7523 }
Chris Lattner393bd8e2010-10-01 07:13:18 +00007524
Chris Lattner14e0e742010-10-01 22:53:11 +00007525 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner393bd8e2010-10-01 07:13:18 +00007526 "Integer constant 'I' type must be an integer");
Mike Stump1eb44332009-09-09 15:08:12 +00007527
Chris Lattner86df27b2009-06-14 00:45:47 +00007528 return Type;
7529}
7530
7531/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattner33daae62010-10-01 22:42:38 +00007532QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattner14e0e742010-10-01 22:53:11 +00007533 GetBuiltinTypeError &Error,
Jay Foad4ba2a172011-01-12 09:06:06 +00007534 unsigned *IntegerConstantArgs) const {
Chris Lattner33daae62010-10-01 22:42:38 +00007535 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump1eb44332009-09-09 15:08:12 +00007536
Chris Lattner5f9e2722011-07-23 10:55:15 +00007537 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00007538
Chris Lattner14e0e742010-10-01 22:53:11 +00007539 bool RequiresICE = false;
Chris Lattner86df27b2009-06-14 00:45:47 +00007540 Error = GE_None;
Chris Lattner14e0e742010-10-01 22:53:11 +00007541 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7542 RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00007543 if (Error != GE_None)
7544 return QualType();
Chris Lattner14e0e742010-10-01 22:53:11 +00007545
7546 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7547
Chris Lattner86df27b2009-06-14 00:45:47 +00007548 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattner14e0e742010-10-01 22:53:11 +00007549 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00007550 if (Error != GE_None)
7551 return QualType();
7552
Chris Lattner14e0e742010-10-01 22:53:11 +00007553 // If this argument is required to be an IntegerConstantExpression and the
7554 // caller cares, fill in the bitmask we return.
7555 if (RequiresICE && IntegerConstantArgs)
7556 *IntegerConstantArgs |= 1 << ArgTypes.size();
7557
Chris Lattner86df27b2009-06-14 00:45:47 +00007558 // Do array -> pointer decay. The builtin should use the decayed type.
7559 if (Ty->isArrayType())
7560 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00007561
Chris Lattner86df27b2009-06-14 00:45:47 +00007562 ArgTypes.push_back(Ty);
7563 }
7564
7565 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7566 "'.' should only occur at end of builtin type list!");
7567
John McCall00ccbef2010-12-21 00:44:39 +00007568 FunctionType::ExtInfo EI;
7569 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7570
7571 bool Variadic = (TypeStr[0] == '.');
7572
7573 // We really shouldn't be making a no-proto type here, especially in C++.
7574 if (ArgTypes.empty() && Variadic)
7575 return getFunctionNoProtoType(ResType, EI);
Douglas Gregorce056bc2010-02-21 22:15:06 +00007576
John McCalle23cf432010-12-14 08:05:40 +00007577 FunctionProtoType::ExtProtoInfo EPI;
John McCall00ccbef2010-12-21 00:44:39 +00007578 EPI.ExtInfo = EI;
7579 EPI.Variadic = Variadic;
John McCalle23cf432010-12-14 08:05:40 +00007580
Jordan Rosebea522f2013-03-08 21:51:21 +00007581 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattner86df27b2009-06-14 00:45:47 +00007582}
Eli Friedmana95d7572009-08-19 07:44:53 +00007583
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007584GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
7585 GVALinkage External = GVA_StrongExternal;
7586
7587 Linkage L = FD->getLinkage();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007588 switch (L) {
7589 case NoLinkage:
7590 case InternalLinkage:
7591 case UniqueExternalLinkage:
7592 return GVA_Internal;
7593
7594 case ExternalLinkage:
7595 switch (FD->getTemplateSpecializationKind()) {
7596 case TSK_Undeclared:
7597 case TSK_ExplicitSpecialization:
7598 External = GVA_StrongExternal;
7599 break;
7600
7601 case TSK_ExplicitInstantiationDefinition:
7602 return GVA_ExplicitTemplateInstantiation;
7603
7604 case TSK_ExplicitInstantiationDeclaration:
7605 case TSK_ImplicitInstantiation:
7606 External = GVA_TemplateInstantiation;
7607 break;
7608 }
7609 }
7610
7611 if (!FD->isInlined())
7612 return External;
7613
David Blaikie4e4d0842012-03-11 07:00:24 +00007614 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007615 // GNU or C99 inline semantics. Determine whether this symbol should be
7616 // externally visible.
7617 if (FD->isInlineDefinitionExternallyVisible())
7618 return External;
7619
7620 // C99 inline semantics, where the symbol is not externally visible.
7621 return GVA_C99Inline;
7622 }
7623
7624 // C++0x [temp.explicit]p9:
7625 // [ Note: The intent is that an inline function that is the subject of
7626 // an explicit instantiation declaration will still be implicitly
7627 // instantiated when used so that the body can be considered for
7628 // inlining, but that no out-of-line copy of the inline function would be
7629 // generated in the translation unit. -- end note ]
7630 if (FD->getTemplateSpecializationKind()
7631 == TSK_ExplicitInstantiationDeclaration)
7632 return GVA_C99Inline;
7633
7634 return GVA_CXXInline;
7635}
7636
7637GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
7638 // If this is a static data member, compute the kind of template
7639 // specialization. Otherwise, this variable is not part of a
7640 // template.
7641 TemplateSpecializationKind TSK = TSK_Undeclared;
7642 if (VD->isStaticDataMember())
7643 TSK = VD->getTemplateSpecializationKind();
7644
7645 Linkage L = VD->getLinkage();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007646
7647 switch (L) {
7648 case NoLinkage:
7649 case InternalLinkage:
7650 case UniqueExternalLinkage:
7651 return GVA_Internal;
7652
7653 case ExternalLinkage:
7654 switch (TSK) {
7655 case TSK_Undeclared:
7656 case TSK_ExplicitSpecialization:
7657 return GVA_StrongExternal;
7658
7659 case TSK_ExplicitInstantiationDeclaration:
7660 llvm_unreachable("Variable should not be instantiated");
7661 // Fall through to treat this like any other instantiation.
7662
7663 case TSK_ExplicitInstantiationDefinition:
7664 return GVA_ExplicitTemplateInstantiation;
7665
7666 case TSK_ImplicitInstantiation:
7667 return GVA_TemplateInstantiation;
7668 }
7669 }
7670
David Blaikie7530c032012-01-17 06:56:22 +00007671 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007672}
7673
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +00007674bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007675 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7676 if (!VD->isFileVarDecl())
7677 return false;
Richard Smithf396ad92013-04-01 20:22:16 +00007678 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7679 // We never need to emit an uninstantiated function template.
7680 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
7681 return false;
7682 } else
7683 return false;
7684
7685 // If this is a member of a class template, we do not need to emit it.
7686 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007687 return false;
7688
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00007689 // Weak references don't produce any output by themselves.
7690 if (D->hasAttr<WeakRefAttr>())
7691 return false;
7692
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007693 // Aliases and used decls are required.
7694 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7695 return true;
7696
7697 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7698 // Forward declarations aren't required.
Sean Hunt10620eb2011-05-06 20:44:56 +00007699 if (!FD->doesThisDeclarationHaveABody())
Nick Lewyckydce67a72011-07-18 05:26:13 +00007700 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007701
7702 // Constructors and destructors are required.
7703 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7704 return true;
7705
John McCalld5617ee2013-01-25 22:31:03 +00007706 // The key function for a class is required. This rule only comes
7707 // into play when inline functions can be key functions, though.
7708 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7709 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7710 const CXXRecordDecl *RD = MD->getParent();
7711 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7712 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
7713 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7714 return true;
7715 }
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007716 }
7717 }
7718
7719 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7720
7721 // static, static inline, always_inline, and extern inline functions can
7722 // always be deferred. Normal inline functions can be deferred in C99/C++.
7723 // Implicit template instantiations can also be deferred in C++.
7724 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev3a5aca82012-02-02 06:06:34 +00007725 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007726 return false;
7727 return true;
7728 }
Douglas Gregor94da1582011-09-10 00:22:34 +00007729
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007730 const VarDecl *VD = cast<VarDecl>(D);
7731 assert(VD->isFileVarDecl() && "Expected file scoped var");
7732
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00007733 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7734 return false;
7735
Richard Smith5f9a7e32012-11-12 21:38:00 +00007736 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007737 GVALinkage L = GetGVALinkageForVariable(VD);
Richard Smith5f9a7e32012-11-12 21:38:00 +00007738 if (L != GVA_Internal && L != GVA_TemplateInstantiation)
7739 return true;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007740
Richard Smith5f9a7e32012-11-12 21:38:00 +00007741 // Variables that have destruction with side-effects are required.
7742 if (VD->getType().isDestructedType())
7743 return true;
7744
7745 // Variables that have initialization with side-effects are required.
7746 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
7747 return true;
7748
7749 return false;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007750}
Charles Davis071cc7d2010-08-16 03:33:14 +00007751
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007752CallingConv ASTContext::getDefaultCXXMethodCallConv(bool isVariadic) {
Charles Davisee743f92010-11-09 18:04:24 +00007753 // Pass through to the C++ ABI object
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007754 return ABI->getDefaultMethodCallConv(isVariadic);
7755}
7756
7757CallingConv ASTContext::getCanonicalCallConv(CallingConv CC) const {
John McCallb8b2c9d2013-01-25 22:30:49 +00007758 if (CC == CC_C && !LangOpts.MRTD &&
7759 getTargetInfo().getCXXABI().isMemberFunctionCCDefault())
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007760 return CC_Default;
7761 return CC;
Charles Davisee743f92010-11-09 18:04:24 +00007762}
7763
Jay Foad4ba2a172011-01-12 09:06:06 +00007764bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlssondae0cb52010-11-25 01:51:53 +00007765 // Pass through to the C++ ABI object
7766 return ABI->isNearlyEmpty(RD);
7767}
7768
Peter Collingbourne14110472011-01-13 18:57:25 +00007769MangleContext *ASTContext::createMangleContext() {
John McCallb8b2c9d2013-01-25 22:30:49 +00007770 switch (Target->getCXXABI().getKind()) {
Tim Northoverc264e162013-01-31 12:13:10 +00007771 case TargetCXXABI::GenericAArch64:
John McCallb8b2c9d2013-01-25 22:30:49 +00007772 case TargetCXXABI::GenericItanium:
7773 case TargetCXXABI::GenericARM:
7774 case TargetCXXABI::iOS:
Peter Collingbourne14110472011-01-13 18:57:25 +00007775 return createItaniumMangleContext(*this, getDiagnostics());
John McCallb8b2c9d2013-01-25 22:30:49 +00007776 case TargetCXXABI::Microsoft:
Peter Collingbourne14110472011-01-13 18:57:25 +00007777 return createMicrosoftMangleContext(*this, getDiagnostics());
7778 }
David Blaikieb219cfc2011-09-23 05:06:16 +00007779 llvm_unreachable("Unsupported ABI");
Peter Collingbourne14110472011-01-13 18:57:25 +00007780}
7781
Charles Davis071cc7d2010-08-16 03:33:14 +00007782CXXABI::~CXXABI() {}
Ted Kremenekba29bd22011-04-28 04:53:38 +00007783
7784size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek0c8cd1a2011-07-27 18:41:12 +00007785 return ASTRecordLayouts.getMemorySize()
7786 + llvm::capacity_in_bytes(ObjCLayouts)
7787 + llvm::capacity_in_bytes(KeyFunctions)
7788 + llvm::capacity_in_bytes(ObjCImpls)
7789 + llvm::capacity_in_bytes(BlockVarCopyInits)
7790 + llvm::capacity_in_bytes(DeclAttrs)
7791 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
7792 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
7793 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
7794 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
7795 + llvm::capacity_in_bytes(OverriddenMethods)
7796 + llvm::capacity_in_bytes(Types)
Francois Pichetaf0f4d02011-08-14 03:52:19 +00007797 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet0d95f0d2011-08-14 14:28:49 +00007798 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekba29bd22011-04-28 04:53:38 +00007799}
Ted Kremenekd211cb72011-10-06 05:00:56 +00007800
David Blaikie66cff722012-11-14 01:52:05 +00007801void ASTContext::addUnnamedTag(const TagDecl *Tag) {
7802 // FIXME: This mangling should be applied to function local classes too
7803 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl() ||
7804 !isa<CXXRecordDecl>(Tag->getParent()) || Tag->getLinkage() != ExternalLinkage)
7805 return;
7806
7807 std::pair<llvm::DenseMap<const DeclContext *, unsigned>::iterator, bool> P =
7808 UnnamedMangleContexts.insert(std::make_pair(Tag->getParent(), 0));
7809 UnnamedMangleNumbers.insert(std::make_pair(Tag, P.first->second++));
7810}
7811
7812int ASTContext::getUnnamedTagManglingNumber(const TagDecl *Tag) const {
7813 llvm::DenseMap<const TagDecl *, unsigned>::const_iterator I =
7814 UnnamedMangleNumbers.find(Tag);
7815 return I != UnnamedMangleNumbers.end() ? I->second : -1;
7816}
7817
Douglas Gregor9e8c92a2012-02-20 19:44:39 +00007818unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
7819 CXXRecordDecl *Lambda = CallOperator->getParent();
7820 return LambdaMangleContexts[Lambda->getDeclContext()]
7821 .getManglingNumber(CallOperator);
7822}
7823
7824
Ted Kremenekd211cb72011-10-06 05:00:56 +00007825void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
7826 ParamIndices[D] = index;
7827}
7828
7829unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
7830 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
7831 assert(I != ParamIndices.end() &&
7832 "ParmIndices lacks entry set by ParmVarDecl");
7833 return I->second;
7834}