blob: 70c933e75215e9b96233e7c97c11a1c702a941b6 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000015#include "CXXABI.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000016#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/Attr.h"
Ken Dyckbdc601b2009-12-22 14:23:30 +000018#include "clang/AST/CharUnits.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000019#include "clang/AST/Comment.h"
Dmitri Gribenkoaa580812012-08-09 00:03:17 +000020#include "clang/AST/CommentCommandTraits.h"
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +000021#include "clang/AST/DeclCXX.h"
Steve Naroff980e5082007-10-01 19:00:59 +000022#include "clang/AST/DeclObjC.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000023#include "clang/AST/DeclTemplate.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000024#include "clang/AST/Expr.h"
John McCallea1471e2010-05-20 01:18:31 +000025#include "clang/AST/ExprCXX.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000026#include "clang/AST/ExternalASTSource.h"
Peter Collingbourne14110472011-01-13 18:57:25 +000027#include "clang/AST/Mangle.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000028#include "clang/AST/RecordLayout.h"
Reid Klecknercff15122013-06-17 12:56:08 +000029#include "clang/AST/RecursiveASTVisitor.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000030#include "clang/AST/TypeLoc.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000031#include "clang/Basic/Builtins.h"
Chris Lattnera9376d42009-03-28 03:45:20 +000032#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000033#include "clang/Basic/TargetInfo.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000034#include "llvm/ADT/SmallString.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000035#include "llvm/ADT/StringExtras.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000036#include "llvm/Support/Capacity.h"
Nate Begeman6fe7c8a2009-01-18 06:42:49 +000037#include "llvm/Support/MathExtras.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000038#include "llvm/Support/raw_ostream.h"
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +000039#include <map>
Anders Carlsson29445a02009-07-18 21:19:52 +000040
Reid Spencer5f016e22007-07-11 17:01:13 +000041using namespace clang;
42
Douglas Gregor18274032010-07-03 00:47:00 +000043unsigned ASTContext::NumImplicitDefaultConstructors;
44unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregor22584312010-07-02 23:41:54 +000045unsigned ASTContext::NumImplicitCopyConstructors;
46unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Sean Huntffe37fd2011-05-25 20:50:04 +000047unsigned ASTContext::NumImplicitMoveConstructors;
48unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregora376d102010-07-02 21:50:04 +000049unsigned ASTContext::NumImplicitCopyAssignmentOperators;
50unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Huntffe37fd2011-05-25 20:50:04 +000051unsigned ASTContext::NumImplicitMoveAssignmentOperators;
52unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor4923aa22010-07-02 20:37:36 +000053unsigned ASTContext::NumImplicitDestructors;
54unsigned ASTContext::NumImplicitDestructorsDeclared;
55
Reid Spencer5f016e22007-07-11 17:01:13 +000056enum FloatingRank {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +000057 HalfRank, FloatRank, DoubleRank, LongDoubleRank
Reid Spencer5f016e22007-07-11 17:01:13 +000058};
59
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +000060RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +000061 if (!CommentsLoaded && ExternalSource) {
62 ExternalSource->ReadComments();
63 CommentsLoaded = true;
64 }
65
66 assert(D);
67
Dmitri Gribenkoc3fee352012-06-28 16:19:39 +000068 // User can not attach documentation to implicit declarations.
69 if (D->isImplicit())
70 return NULL;
71
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +000072 // User can not attach documentation to implicit instantiations.
73 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
74 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
75 return NULL;
76 }
77
Dmitri Gribenkodce750b2012-08-20 22:36:31 +000078 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
79 if (VD->isStaticDataMember() &&
80 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
81 return NULL;
82 }
83
84 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
85 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
86 return NULL;
87 }
88
Dmitri Gribenkod1e5c0d2013-01-27 21:18:39 +000089 if (const ClassTemplateSpecializationDecl *CTSD =
90 dyn_cast<ClassTemplateSpecializationDecl>(D)) {
91 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
92 if (TSK == TSK_ImplicitInstantiation ||
93 TSK == TSK_Undeclared)
94 return NULL;
95 }
96
Dmitri Gribenkodce750b2012-08-20 22:36:31 +000097 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
98 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
99 return NULL;
100 }
Fariborz Jahanian099ecfb2013-04-17 21:05:20 +0000101 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
102 // When tag declaration (but not definition!) is part of the
103 // decl-specifier-seq of some other declaration, it doesn't get comment
104 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
105 return NULL;
106 }
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000107 // TODO: handle comments for function parameters properly.
108 if (isa<ParmVarDecl>(D))
109 return NULL;
110
Dmitri Gribenko96b09862012-07-31 22:37:06 +0000111 // TODO: we could look up template parameter documentation in the template
112 // documentation.
113 if (isa<TemplateTypeParmDecl>(D) ||
114 isa<NonTypeTemplateParmDecl>(D) ||
115 isa<TemplateTemplateParmDecl>(D))
116 return NULL;
117
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000118 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000119
120 // If there are no comments anywhere, we won't find anything.
121 if (RawComments.empty())
122 return NULL;
123
Dmitri Gribenkoabd56c82012-07-13 01:06:46 +0000124 // Find declaration location.
125 // For Objective-C declarations we generally don't expect to have multiple
126 // declarators, thus use declaration starting location as the "declaration
127 // location".
128 // For all other declarations multiple declarators are used quite frequently,
129 // so we use the location of the identifier as the "declaration location".
130 SourceLocation DeclLoc;
131 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko96b09862012-07-31 22:37:06 +0000132 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +0000133 isa<RedeclarableTemplateDecl>(D) ||
134 isa<ClassTemplateSpecializationDecl>(D))
Dmitri Gribenkoabd56c82012-07-13 01:06:46 +0000135 DeclLoc = D->getLocStart();
136 else
137 DeclLoc = D->getLocation();
138
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000139 // If the declaration doesn't map directly to a location in a file, we
140 // can't find the comment.
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000141 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
142 return NULL;
143
144 // Find the comment that occurs just after this declaration.
Dmitri Gribenkoa444f182012-07-17 22:01:09 +0000145 ArrayRef<RawComment *>::iterator Comment;
146 {
147 // When searching for comments during parsing, the comment we are looking
148 // for is usually among the last two comments we parsed -- check them
149 // first.
Dmitri Gribenko6fd7d302013-04-10 15:35:17 +0000150 RawComment CommentAtDeclLoc(
151 SourceMgr, SourceRange(DeclLoc), false,
152 LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenkoa444f182012-07-17 22:01:09 +0000153 BeforeThanCompare<RawComment> Compare(SourceMgr);
154 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
155 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
156 if (!Found && RawComments.size() >= 2) {
157 MaybeBeforeDecl--;
158 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
159 }
160
161 if (Found) {
162 Comment = MaybeBeforeDecl + 1;
163 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
164 &CommentAtDeclLoc, Compare));
165 } else {
166 // Slow path.
167 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
168 &CommentAtDeclLoc, Compare);
169 }
170 }
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000171
172 // Decompose the location for the declaration and find the beginning of the
173 // file buffer.
174 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
175
176 // First check whether we have a trailing comment.
177 if (Comment != RawComments.end() &&
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000178 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
Dmitri Gribenko9c006762012-07-06 23:27:33 +0000179 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D))) {
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000180 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000181 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000182 // Check that Doxygen trailing comment comes after the declaration, starts
183 // on the same line and in the same file as the declaration.
184 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
185 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
186 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
187 CommentBeginDecomp.second)) {
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000188 return *Comment;
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000189 }
190 }
191
192 // The comment just after the declaration was not a trailing comment.
193 // Let's look at the previous comment.
194 if (Comment == RawComments.begin())
195 return NULL;
196 --Comment;
197
198 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000199 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000200 return NULL;
201
202 // Decompose the end of the comment.
203 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000204 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000205
206 // If the comment and the declaration aren't in the same file, then they
207 // aren't related.
208 if (DeclLocDecomp.first != CommentEndDecomp.first)
209 return NULL;
210
211 // Get the corresponding buffer.
212 bool Invalid = false;
213 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
214 &Invalid).data();
215 if (Invalid)
216 return NULL;
217
218 // Extract text between the comment and declaration.
219 StringRef Text(Buffer + CommentEndDecomp.second,
220 DeclLocDecomp.second - CommentEndDecomp.second);
221
Dmitri Gribenko8bdb58a2012-06-27 23:43:37 +0000222 // There should be no other declarations or preprocessor directives between
223 // comment and declaration.
Dmitri Gribenkoabd56c82012-07-13 01:06:46 +0000224 if (Text.find_first_of(",;{}#@") != StringRef::npos)
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000225 return NULL;
226
Dmitri Gribenko811c8202012-07-06 18:19:34 +0000227 return *Comment;
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000228}
229
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000230namespace {
231/// If we have a 'templated' declaration for a template, adjust 'D' to
232/// refer to the actual template.
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000233/// If we have an implicit instantiation, adjust 'D' to refer to template.
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000234const Decl *adjustDeclToTemplate(const Decl *D) {
Douglas Gregorcd81df22012-08-13 16:37:30 +0000235 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000236 // Is this function declaration part of a function template?
Douglas Gregorcd81df22012-08-13 16:37:30 +0000237 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000238 return FTD;
239
240 // Nothing to do if function is not an implicit instantiation.
241 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
242 return D;
243
244 // Function is an implicit instantiation of a function template?
245 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
246 return FTD;
247
248 // Function is instantiated from a member definition of a class template?
249 if (const FunctionDecl *MemberDecl =
250 FD->getInstantiatedFromMemberFunction())
251 return MemberDecl;
252
253 return D;
Douglas Gregorcd81df22012-08-13 16:37:30 +0000254 }
Dmitri Gribenko2125c902012-08-22 17:44:32 +0000255 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
256 // Static data member is instantiated from a member definition of a class
257 // template?
258 if (VD->isStaticDataMember())
259 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
260 return MemberDecl;
261
262 return D;
263 }
264 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
265 // Is this class declaration part of a class template?
266 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
267 return CTD;
268
269 // Class is an implicit instantiation of a class template or partial
270 // specialization?
271 if (const ClassTemplateSpecializationDecl *CTSD =
272 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
273 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
274 return D;
275 llvm::PointerUnion<ClassTemplateDecl *,
276 ClassTemplatePartialSpecializationDecl *>
277 PU = CTSD->getSpecializedTemplateOrPartial();
278 return PU.is<ClassTemplateDecl*>() ?
279 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
280 static_cast<const Decl*>(
281 PU.get<ClassTemplatePartialSpecializationDecl *>());
282 }
283
284 // Class is instantiated from a member definition of a class template?
285 if (const MemberSpecializationInfo *Info =
286 CRD->getMemberSpecializationInfo())
287 return Info->getInstantiatedFrom();
288
289 return D;
290 }
291 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
292 // Enum is instantiated from a member definition of a class template?
293 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
294 return MemberDecl;
295
296 return D;
297 }
298 // FIXME: Adjust alias templates?
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000299 return D;
300}
301} // unnamed namespace
302
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000303const RawComment *ASTContext::getRawCommentForAnyRedecl(
304 const Decl *D,
305 const Decl **OriginalDecl) const {
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000306 D = adjustDeclToTemplate(D);
Douglas Gregorcd81df22012-08-13 16:37:30 +0000307
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000308 // Check whether we have cached a comment for this declaration already.
309 {
310 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
311 RedeclComments.find(D);
312 if (Pos != RedeclComments.end()) {
313 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000314 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
315 if (OriginalDecl)
316 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000317 return Raw.getRaw();
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000318 }
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000319 }
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000320 }
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000321
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000322 // Search for comments attached to declarations in the redeclaration chain.
323 const RawComment *RC = NULL;
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000324 const Decl *OriginalDeclForRC = NULL;
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000325 for (Decl::redecl_iterator I = D->redecls_begin(),
326 E = D->redecls_end();
327 I != E; ++I) {
328 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
329 RedeclComments.find(*I);
330 if (Pos != RedeclComments.end()) {
331 const RawCommentAndCacheFlags &Raw = Pos->second;
332 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
333 RC = Raw.getRaw();
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000334 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000335 break;
336 }
337 } else {
338 RC = getRawCommentForDeclNoCache(*I);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000339 OriginalDeclForRC = *I;
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000340 RawCommentAndCacheFlags Raw;
341 if (RC) {
342 Raw.setRaw(RC);
343 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
344 } else
345 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000346 Raw.setOriginalDecl(*I);
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000347 RedeclComments[*I] = Raw;
348 if (RC)
349 break;
350 }
351 }
352
Dmitri Gribenko8376f592012-06-28 16:25:36 +0000353 // If we found a comment, it should be a documentation comment.
354 assert(!RC || RC->isDocumentation());
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000355
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000356 if (OriginalDecl)
357 *OriginalDecl = OriginalDeclForRC;
358
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000359 // Update cache for every declaration in the redeclaration chain.
360 RawCommentAndCacheFlags Raw;
361 Raw.setRaw(RC);
362 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000363 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkof50555e2012-08-11 00:51:43 +0000364
365 for (Decl::redecl_iterator I = D->redecls_begin(),
366 E = D->redecls_end();
367 I != E; ++I) {
368 RawCommentAndCacheFlags &R = RedeclComments[*I];
369 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
370 R = Raw;
371 }
372
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000373 return RC;
374}
375
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000376static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
377 SmallVectorImpl<const NamedDecl *> &Redeclared) {
378 const DeclContext *DC = ObjCMethod->getDeclContext();
379 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
380 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
381 if (!ID)
382 return;
383 // Add redeclared method here.
Douglas Gregord3297242013-01-16 23:00:23 +0000384 for (ObjCInterfaceDecl::known_extensions_iterator
385 Ext = ID->known_extensions_begin(),
386 ExtEnd = ID->known_extensions_end();
387 Ext != ExtEnd; ++Ext) {
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000388 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregord3297242013-01-16 23:00:23 +0000389 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000390 ObjCMethod->isInstanceMethod()))
391 Redeclared.push_back(RedeclaredMethod);
392 }
393 }
394}
395
Fariborz Jahanian749ace62012-10-11 23:52:50 +0000396comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
397 const Decl *D) const {
398 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
399 ThisDeclInfo->CommentDecl = D;
400 ThisDeclInfo->IsFilled = false;
401 ThisDeclInfo->fill();
402 ThisDeclInfo->CommentDecl = FC->getDecl();
403 comments::FullComment *CFC =
404 new (*this) comments::FullComment(FC->getBlocks(),
405 ThisDeclInfo);
406 return CFC;
407
408}
409
Richard Smith0a74a4c2013-05-21 05:24:00 +0000410comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
411 const RawComment *RC = getRawCommentForDeclNoCache(D);
412 return RC ? RC->parse(*this, 0, D) : 0;
413}
414
Dmitri Gribenko19523542012-09-29 11:40:46 +0000415comments::FullComment *ASTContext::getCommentForDecl(
416 const Decl *D,
417 const Preprocessor *PP) const {
Fariborz Jahanianfbff0c42013-05-13 17:27:00 +0000418 if (D->isInvalidDecl())
419 return NULL;
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000420 D = adjustDeclToTemplate(D);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000421
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000422 const Decl *Canonical = D->getCanonicalDecl();
423 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
424 ParsedComments.find(Canonical);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000425
426 if (Pos != ParsedComments.end()) {
Fariborz Jahanian749ace62012-10-11 23:52:50 +0000427 if (Canonical != D) {
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000428 comments::FullComment *FC = Pos->second;
Fariborz Jahanian749ace62012-10-11 23:52:50 +0000429 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000430 return CFC;
431 }
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000432 return Pos->second;
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000433 }
434
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000435 const Decl *OriginalDecl;
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000436
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000437 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000438 if (!RC) {
439 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko1e905da2012-11-03 14:24:57 +0000440 SmallVector<const NamedDecl*, 8> Overridden;
Fariborz Jahanianc328d9c2013-01-12 00:28:34 +0000441 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian23799e32013-01-25 23:08:39 +0000442 if (OMD && OMD->isPropertyAccessor())
443 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
444 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
445 return cloneFullComment(FC, D);
Fariborz Jahanianc328d9c2013-01-12 00:28:34 +0000446 if (OMD)
Dmitri Gribenko1e905da2012-11-03 14:24:57 +0000447 addRedeclaredMethods(OMD, Overridden);
448 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian23799e32013-01-25 23:08:39 +0000449 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
450 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
451 return cloneFullComment(FC, D);
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000452 }
Fariborz Jahanian4857fdc2013-05-02 15:44:16 +0000453 else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenkod1e5c0d2013-01-27 21:18:39 +0000454 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian23799e32013-01-25 23:08:39 +0000455 // does not have one of its own.
Fariborz Jahanian41170b52013-01-25 22:48:32 +0000456 QualType QT = TD->getUnderlyingType();
Dmitri Gribenkod1e5c0d2013-01-27 21:18:39 +0000457 if (const TagType *TT = QT->getAs<TagType>())
458 if (const Decl *TD = TT->getDecl())
459 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian23799e32013-01-25 23:08:39 +0000460 return cloneFullComment(FC, D);
Fariborz Jahanian41170b52013-01-25 22:48:32 +0000461 }
Fariborz Jahanian622bb4a2013-04-26 20:55:38 +0000462 else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
463 while (IC->getSuperClass()) {
464 IC = IC->getSuperClass();
465 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
466 return cloneFullComment(FC, D);
467 }
468 }
469 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
470 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
471 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
472 return cloneFullComment(FC, D);
473 }
474 else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
475 if (!(RD = RD->getDefinition()))
476 return NULL;
477 // Check non-virtual bases.
478 for (CXXRecordDecl::base_class_const_iterator I =
479 RD->bases_begin(), E = RD->bases_end(); I != E; ++I) {
Fariborz Jahanian91efca02013-04-26 23:34:36 +0000480 if (I->isVirtual() || (I->getAccessSpecifier() != AS_public))
Fariborz Jahanian622bb4a2013-04-26 20:55:38 +0000481 continue;
482 QualType Ty = I->getType();
483 if (Ty.isNull())
484 continue;
485 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
486 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
487 continue;
488
489 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
490 return cloneFullComment(FC, D);
491 }
492 }
493 // Check virtual bases.
494 for (CXXRecordDecl::base_class_const_iterator I =
495 RD->vbases_begin(), E = RD->vbases_end(); I != E; ++I) {
Fariborz Jahanian91efca02013-04-26 23:34:36 +0000496 if (I->getAccessSpecifier() != AS_public)
497 continue;
Fariborz Jahanian622bb4a2013-04-26 20:55:38 +0000498 QualType Ty = I->getType();
499 if (Ty.isNull())
500 continue;
501 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
502 if (!(VirtualBase= VirtualBase->getDefinition()))
503 continue;
504 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
505 return cloneFullComment(FC, D);
506 }
507 }
508 }
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000509 return NULL;
Fariborz Jahanianbf967be2012-10-10 18:34:52 +0000510 }
511
Dmitri Gribenko4b41c652012-08-22 18:12:19 +0000512 // If the RawComment was attached to other redeclaration of this Decl, we
513 // should parse the comment in context of that other Decl. This is important
514 // because comments can contain references to parameter names which can be
515 // different across redeclarations.
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000516 if (D != OriginalDecl)
Dmitri Gribenko19523542012-09-29 11:40:46 +0000517 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko1599eac2012-08-16 18:19:43 +0000518
Dmitri Gribenko19523542012-09-29 11:40:46 +0000519 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkoc41ace92012-08-14 17:17:18 +0000520 ParsedComments[Canonical] = FC;
521 return FC;
Dmitri Gribenko8d3ba232012-07-06 00:28:32 +0000522}
523
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000524void
525ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
526 TemplateTemplateParmDecl *Parm) {
527 ID.AddInteger(Parm->getDepth());
528 ID.AddInteger(Parm->getPosition());
Douglas Gregor61c4d282011-01-05 15:48:55 +0000529 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000530
531 TemplateParameterList *Params = Parm->getTemplateParameters();
532 ID.AddInteger(Params->size());
533 for (TemplateParameterList::const_iterator P = Params->begin(),
534 PEnd = Params->end();
535 P != PEnd; ++P) {
536 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
537 ID.AddInteger(0);
538 ID.AddBoolean(TTP->isParameterPack());
539 continue;
540 }
541
542 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
543 ID.AddInteger(1);
Douglas Gregor61c4d282011-01-05 15:48:55 +0000544 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman9e9c4542012-03-07 01:09:33 +0000545 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000546 if (NTTP->isExpandedParameterPack()) {
547 ID.AddBoolean(true);
548 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman9e9c4542012-03-07 01:09:33 +0000549 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
550 QualType T = NTTP->getExpansionType(I);
551 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
552 }
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000553 } else
554 ID.AddBoolean(false);
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000555 continue;
556 }
557
558 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
559 ID.AddInteger(2);
560 Profile(ID, TTP);
561 }
562}
563
564TemplateTemplateParmDecl *
565ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad4ba2a172011-01-12 09:06:06 +0000566 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000567 // Check if we already have a canonical template template parameter.
568 llvm::FoldingSetNodeID ID;
569 CanonicalTemplateTemplateParm::Profile(ID, TTP);
570 void *InsertPos = 0;
571 CanonicalTemplateTemplateParm *Canonical
572 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
573 if (Canonical)
574 return Canonical->getParam();
575
576 // Build a canonical template parameter list.
577 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000578 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000579 CanonParams.reserve(Params->size());
580 for (TemplateParameterList::const_iterator P = Params->begin(),
581 PEnd = Params->end();
582 P != PEnd; ++P) {
583 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
584 CanonParams.push_back(
585 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnara344577e2011-03-06 15:48:19 +0000586 SourceLocation(),
587 SourceLocation(),
588 TTP->getDepth(),
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000589 TTP->getIndex(), 0, false,
590 TTP->isParameterPack()));
591 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000592 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
593 QualType T = getCanonicalType(NTTP->getType());
594 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
595 NonTypeTemplateParmDecl *Param;
596 if (NTTP->isExpandedParameterPack()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000597 SmallVector<QualType, 2> ExpandedTypes;
598 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000599 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
600 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
601 ExpandedTInfos.push_back(
602 getTrivialTypeSourceInfo(ExpandedTypes.back()));
603 }
604
605 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000606 SourceLocation(),
607 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000608 NTTP->getDepth(),
609 NTTP->getPosition(), 0,
610 T,
611 TInfo,
612 ExpandedTypes.data(),
613 ExpandedTypes.size(),
614 ExpandedTInfos.data());
615 } else {
616 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000617 SourceLocation(),
618 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000619 NTTP->getDepth(),
620 NTTP->getPosition(), 0,
621 T,
622 NTTP->isParameterPack(),
623 TInfo);
624 }
625 CanonParams.push_back(Param);
626
627 } else
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000628 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
629 cast<TemplateTemplateParmDecl>(*P)));
630 }
631
632 TemplateTemplateParmDecl *CanonTTP
633 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
634 SourceLocation(), TTP->getDepth(),
Douglas Gregor61c4d282011-01-05 15:48:55 +0000635 TTP->getPosition(),
636 TTP->isParameterPack(),
637 0,
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000638 TemplateParameterList::Create(*this, SourceLocation(),
639 SourceLocation(),
640 CanonParams.data(),
641 CanonParams.size(),
642 SourceLocation()));
643
644 // Get the new insert position for the node we care about.
645 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
646 assert(Canonical == 0 && "Shouldn't be in the map!");
647 (void)Canonical;
648
649 // Create the canonical template template parameter entry.
650 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
651 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
652 return CanonTTP;
653}
654
Charles Davis071cc7d2010-08-16 03:33:14 +0000655CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCallee79a4c2010-08-21 22:46:04 +0000656 if (!LangOpts.CPlusPlus) return 0;
657
John McCallb8b2c9d2013-01-25 22:30:49 +0000658 switch (T.getCXXABI().getKind()) {
659 case TargetCXXABI::GenericARM:
660 case TargetCXXABI::iOS:
John McCallee79a4c2010-08-21 22:46:04 +0000661 return CreateARMCXXABI(*this);
Tim Northoverc264e162013-01-31 12:13:10 +0000662 case TargetCXXABI::GenericAArch64: // Same as Itanium at this level
John McCallb8b2c9d2013-01-25 22:30:49 +0000663 case TargetCXXABI::GenericItanium:
Charles Davis071cc7d2010-08-16 03:33:14 +0000664 return CreateItaniumCXXABI(*this);
John McCallb8b2c9d2013-01-25 22:30:49 +0000665 case TargetCXXABI::Microsoft:
Charles Davis20cf7172010-08-19 02:18:14 +0000666 return CreateMicrosoftCXXABI(*this);
667 }
David Blaikie7530c032012-01-17 06:56:22 +0000668 llvm_unreachable("Invalid CXXABI type!");
Charles Davis071cc7d2010-08-16 03:33:14 +0000669}
670
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000671static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000672 const LangOptions &LOpts) {
673 if (LOpts.FakeAddressSpaceMap) {
674 // The fake address space map must have a distinct entry for each
675 // language-specific address space.
676 static const unsigned FakeAddrSpaceMap[] = {
677 1, // opencl_global
678 2, // opencl_local
Peter Collingbourne4dc34eb2012-05-20 21:08:35 +0000679 3, // opencl_constant
680 4, // cuda_device
681 5, // cuda_constant
682 6 // cuda_shared
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000683 };
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000684 return &FakeAddrSpaceMap;
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000685 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000686 return &T.getAddressSpaceMap();
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000687 }
688}
689
Douglas Gregor3e3cd932011-09-01 20:23:19 +0000690ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000691 const TargetInfo *t,
Daniel Dunbare91593e2008-08-11 04:54:23 +0000692 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000693 Builtin::Context &builtins,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000694 unsigned size_reserve,
695 bool DelayInitialization)
696 : FunctionProtoTypes(this_()),
697 TemplateSpecializationTypes(this_()),
698 DependentTemplateSpecializationTypes(this_()),
699 SubstTemplateTemplateParmPacks(this_()),
700 GlobalNestedNameSpecifier(0),
Nico Webercac18ad2013-06-20 21:44:55 +0000701 Int128Decl(0), UInt128Decl(0), Float128StubDecl(0),
Meador Ingec5613b22012-06-16 03:34:49 +0000702 BuiltinVaListDecl(0),
Douglas Gregora6ea10e2012-01-17 18:09:05 +0000703 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Fariborz Jahanian96171302012-08-30 18:49:41 +0000704 BOOLDecl(0),
Douglas Gregore97179c2011-09-08 01:46:34 +0000705 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000706 FILEDecl(0),
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +0000707 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
708 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
709 cudaConfigureCallDecl(0),
Douglas Gregore6649772011-12-03 00:30:27 +0000710 NullTypeSourceInfo(QualType()),
711 FirstLocalImport(), LastLocalImport(),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000712 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregor30c42402011-09-27 22:38:19 +0000713 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000714 Idents(idents), Selectors(sels),
715 BuiltinInfo(builtins),
716 DeclarationNames(*this),
Douglas Gregor30c42402011-09-27 22:38:19 +0000717 ExternalSource(0), Listener(0),
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000718 Comments(SM), CommentsLoaded(false),
Dmitri Gribenko6ebf0912013-02-22 14:21:27 +0000719 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
Rafael Espindola42b78612013-05-29 19:51:12 +0000720 LastSDM(0, 0)
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000721{
Mike Stump1eb44332009-09-09 15:08:12 +0000722 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +0000723 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000724
725 if (!DelayInitialization) {
726 assert(t && "No target supplied for ASTContext initialization");
727 InitBuiltinTypes(*t);
728 }
Daniel Dunbare91593e2008-08-11 04:54:23 +0000729}
730
Reid Spencer5f016e22007-07-11 17:01:13 +0000731ASTContext::~ASTContext() {
Ted Kremenek3478eb62010-02-11 07:12:28 +0000732 // Release the DenseMaps associated with DeclContext objects.
733 // FIXME: Is this the ideal solution?
734 ReleaseDeclContextMaps();
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000735
Manuel Klimekf0f353b2013-06-03 13:51:33 +0000736 // Call all of the deallocation functions on all of their targets.
737 for (DeallocationMap::const_iterator I = Deallocations.begin(),
738 E = Deallocations.end(); I != E; ++I)
739 for (unsigned J = 0, N = I->second.size(); J != N; ++J)
740 (I->first)((I->second)[J]);
741
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000742 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000743 // because they can contain DenseMaps.
744 for (llvm::DenseMap<const ObjCContainerDecl*,
745 const ASTRecordLayout*>::iterator
746 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
747 // Increment in loop to prevent using deallocated memory.
748 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
749 R->Destroy(*this);
750
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000751 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
752 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
753 // Increment in loop to prevent using deallocated memory.
754 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
755 R->Destroy(*this);
756 }
Douglas Gregor63200642010-08-30 16:49:28 +0000757
758 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
759 AEnd = DeclAttrs.end();
760 A != AEnd; ++A)
761 A->second->~AttrVec();
762}
Douglas Gregorab452ba2009-03-26 23:50:42 +0000763
Douglas Gregor00545312010-05-23 18:26:36 +0000764void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Manuel Klimekf0f353b2013-06-03 13:51:33 +0000765 Deallocations[Callback].push_back(Data);
Douglas Gregor00545312010-05-23 18:26:36 +0000766}
767
Mike Stump1eb44332009-09-09 15:08:12 +0000768void
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000769ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregor2cf26342009-04-09 22:27:44 +0000770 ExternalSource.reset(Source.take());
771}
772
Reid Spencer5f016e22007-07-11 17:01:13 +0000773void ASTContext::PrintStats() const {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000774 llvm::errs() << "\n*** AST Context Stats:\n";
775 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000776
Douglas Gregordbe833d2009-05-26 14:40:08 +0000777 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000778#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000779#define ABSTRACT_TYPE(Name, Parent)
780#include "clang/AST/TypeNodes.def"
781 0 // Extra
782 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000783
Reid Spencer5f016e22007-07-11 17:01:13 +0000784 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
785 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000786 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000787 }
788
Douglas Gregordbe833d2009-05-26 14:40:08 +0000789 unsigned Idx = 0;
790 unsigned TotalBytes = 0;
791#define TYPE(Name, Parent) \
792 if (counts[Idx]) \
Chandler Carruthcd92a652011-07-04 05:32:14 +0000793 llvm::errs() << " " << counts[Idx] << " " << #Name \
794 << " types\n"; \
Douglas Gregordbe833d2009-05-26 14:40:08 +0000795 TotalBytes += counts[Idx] * sizeof(Name##Type); \
796 ++Idx;
797#define ABSTRACT_TYPE(Name, Parent)
798#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000799
Chandler Carruthcd92a652011-07-04 05:32:14 +0000800 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
801
Douglas Gregor4923aa22010-07-02 20:37:36 +0000802 // Implicit special member functions.
Chandler Carruthcd92a652011-07-04 05:32:14 +0000803 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
804 << NumImplicitDefaultConstructors
805 << " implicit default constructors created\n";
806 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
807 << NumImplicitCopyConstructors
808 << " implicit copy constructors created\n";
David Blaikie4e4d0842012-03-11 07:00:24 +0000809 if (getLangOpts().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000810 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
811 << NumImplicitMoveConstructors
812 << " implicit move constructors created\n";
813 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
814 << NumImplicitCopyAssignmentOperators
815 << " implicit copy assignment operators created\n";
David Blaikie4e4d0842012-03-11 07:00:24 +0000816 if (getLangOpts().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000817 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
818 << NumImplicitMoveAssignmentOperators
819 << " implicit move assignment operators created\n";
820 llvm::errs() << NumImplicitDestructorsDeclared << "/"
821 << NumImplicitDestructors
822 << " implicit destructors created\n";
823
Douglas Gregor2cf26342009-04-09 22:27:44 +0000824 if (ExternalSource.get()) {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000825 llvm::errs() << "\n";
Douglas Gregor2cf26342009-04-09 22:27:44 +0000826 ExternalSource->PrintStats();
827 }
Chandler Carruthcd92a652011-07-04 05:32:14 +0000828
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000829 BumpAlloc.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000830}
831
Douglas Gregor772eeae2011-08-12 06:49:56 +0000832TypedefDecl *ASTContext::getInt128Decl() const {
833 if (!Int128Decl) {
834 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
835 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
836 getTranslationUnitDecl(),
837 SourceLocation(),
838 SourceLocation(),
839 &Idents.get("__int128_t"),
840 TInfo);
841 }
842
843 return Int128Decl;
844}
845
846TypedefDecl *ASTContext::getUInt128Decl() const {
847 if (!UInt128Decl) {
848 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
849 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
850 getTranslationUnitDecl(),
851 SourceLocation(),
852 SourceLocation(),
853 &Idents.get("__uint128_t"),
854 TInfo);
855 }
856
857 return UInt128Decl;
858}
Reid Spencer5f016e22007-07-11 17:01:13 +0000859
Nico Webercac18ad2013-06-20 21:44:55 +0000860TypeDecl *ASTContext::getFloat128StubType() const {
Nico Weber3f7c1b12013-06-21 01:29:36 +0000861 assert(LangOpts.CPlusPlus && "should only be called for c++");
Nico Webercac18ad2013-06-20 21:44:55 +0000862 if (!Float128StubDecl) {
Nico Weber9b9bdba2013-06-20 23:30:30 +0000863 Float128StubDecl = CXXRecordDecl::Create(const_cast<ASTContext &>(*this),
864 TTK_Struct,
865 getTranslationUnitDecl(),
866 SourceLocation(),
867 SourceLocation(),
868 &Idents.get("__float128"));
Nico Webercac18ad2013-06-20 21:44:55 +0000869 }
870
871 return Float128StubDecl;
872}
873
John McCalle27ec8a2009-10-23 23:03:21 +0000874void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000875 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000876 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000877 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000878}
879
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000880void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
881 assert((!this->Target || this->Target == &Target) &&
882 "Incorrect target reinitialization");
Reid Spencer5f016e22007-07-11 17:01:13 +0000883 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000884
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000885 this->Target = &Target;
886
887 ABI.reset(createCXXABI(Target));
888 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
889
Reid Spencer5f016e22007-07-11 17:01:13 +0000890 // C99 6.2.5p19.
891 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000892
Reid Spencer5f016e22007-07-11 17:01:13 +0000893 // C99 6.2.5p2.
894 InitBuiltinType(BoolTy, BuiltinType::Bool);
895 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000896 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000897 InitBuiltinType(CharTy, BuiltinType::Char_S);
898 else
899 InitBuiltinType(CharTy, BuiltinType::Char_U);
900 // C99 6.2.5p4.
901 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
902 InitBuiltinType(ShortTy, BuiltinType::Short);
903 InitBuiltinType(IntTy, BuiltinType::Int);
904 InitBuiltinType(LongTy, BuiltinType::Long);
905 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000906
Reid Spencer5f016e22007-07-11 17:01:13 +0000907 // C99 6.2.5p6.
908 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
909 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
910 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
911 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
912 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000913
Reid Spencer5f016e22007-07-11 17:01:13 +0000914 // C99 6.2.5p10.
915 InitBuiltinType(FloatTy, BuiltinType::Float);
916 InitBuiltinType(DoubleTy, BuiltinType::Double);
917 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000918
Chris Lattner2df9ced2009-04-30 02:43:43 +0000919 // GNU extension, 128-bit integers.
920 InitBuiltinType(Int128Ty, BuiltinType::Int128);
921 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
922
Hans Wennborg15f92ba2013-05-10 10:08:40 +0000923 // C++ 3.9.1p5
924 if (TargetInfo::isTypeSigned(Target.getWCharType()))
925 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
926 else // -fshort-wchar makes wchar_t be unsigned.
927 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
928 if (LangOpts.CPlusPlus && LangOpts.WChar)
929 WideCharTy = WCharTy;
930 else {
931 // C99 (or C++ using -fno-wchar).
932 WideCharTy = getFromTargetType(Target.getWCharType());
933 }
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000934
James Molloy392da482012-05-04 10:55:22 +0000935 WIntTy = getFromTargetType(Target.getWIntType());
936
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000937 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
938 InitBuiltinType(Char16Ty, BuiltinType::Char16);
939 else // C99
940 Char16Ty = getFromTargetType(Target.getChar16Type());
941
942 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
943 InitBuiltinType(Char32Ty, BuiltinType::Char32);
944 else // C99
945 Char32Ty = getFromTargetType(Target.getChar32Type());
946
Douglas Gregor898574e2008-12-05 23:32:09 +0000947 // Placeholder type for type-dependent expressions whose type is
948 // completely unknown. No code should ever check a type against
949 // DependentTy and users should never see it; however, it is here to
950 // help diagnose failures to properly check for type-dependent
951 // expressions.
952 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000953
John McCall2a984ca2010-10-12 00:20:44 +0000954 // Placeholder type for functions.
955 InitBuiltinType(OverloadTy, BuiltinType::Overload);
956
John McCall864c0412011-04-26 20:42:42 +0000957 // Placeholder type for bound members.
958 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
959
John McCall3c3b7f92011-10-25 17:37:35 +0000960 // Placeholder type for pseudo-objects.
961 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
962
John McCall1de4d4e2011-04-07 08:22:57 +0000963 // "any" type; useful for debugger-like clients.
964 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
965
John McCall0ddaeb92011-10-17 18:09:15 +0000966 // Placeholder type for unbridged ARC casts.
967 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
968
Eli Friedmana6c66ce2012-08-31 00:14:07 +0000969 // Placeholder type for builtin functions.
970 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
971
Reid Spencer5f016e22007-07-11 17:01:13 +0000972 // C99 6.2.5p11.
973 FloatComplexTy = getComplexType(FloatTy);
974 DoubleComplexTy = getComplexType(DoubleTy);
975 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000976
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000977 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000978 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
979 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000980 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeib13621d2012-12-18 14:38:23 +0000981
982 if (LangOpts.OpenCL) {
983 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
984 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
985 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
986 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
987 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
988 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
Guy Benyeie6b9d802013-01-20 12:31:11 +0000989
Guy Benyei21f18c42013-02-07 10:55:47 +0000990 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyeie6b9d802013-01-20 12:31:11 +0000991 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Guy Benyeib13621d2012-12-18 14:38:23 +0000992 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000993
994 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian93a49942012-04-16 21:03:30 +0000995 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
996 SignedCharTy : BoolTy);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000997
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000998 ObjCConstantStringType = QualType();
Fariborz Jahanianf7992132013-01-04 18:45:40 +0000999
1000 ObjCSuperType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00001001
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001002 // void * type
1003 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001004
1005 // nullptr type (C++0x 2.14.7)
1006 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001007
1008 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1009 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingefb40e3f2012-07-01 15:57:25 +00001010
1011 // Builtin type used to help define __builtin_va_list.
1012 VaListTagTy = QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001013}
1014
David Blaikied6471f72011-09-25 23:23:43 +00001015DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00001016 return SourceMgr.getDiagnostics();
1017}
1018
Douglas Gregor63200642010-08-30 16:49:28 +00001019AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1020 AttrVec *&Result = DeclAttrs[D];
1021 if (!Result) {
1022 void *Mem = Allocate(sizeof(AttrVec));
1023 Result = new (Mem) AttrVec;
1024 }
1025
1026 return *Result;
1027}
1028
1029/// \brief Erase the attributes corresponding to the given declaration.
1030void ASTContext::eraseDeclAttrs(const Decl *D) {
1031 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1032 if (Pos != DeclAttrs.end()) {
1033 Pos->second->~AttrVec();
1034 DeclAttrs.erase(Pos);
1035 }
1036}
1037
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001038MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +00001039ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001040 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +00001041 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +00001042 = InstantiatedFromStaticDataMember.find(Var);
1043 if (Pos == InstantiatedFromStaticDataMember.end())
1044 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001045
Douglas Gregor7caa6822009-07-24 20:34:43 +00001046 return Pos->second;
1047}
1048
Mike Stump1eb44332009-09-09 15:08:12 +00001049void
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001050ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +00001051 TemplateSpecializationKind TSK,
1052 SourceLocation PointOfInstantiation) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00001053 assert(Inst->isStaticDataMember() && "Not a static data member");
1054 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1055 assert(!InstantiatedFromStaticDataMember[Inst] &&
1056 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001057 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +00001058 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregor7caa6822009-07-24 20:34:43 +00001059}
1060
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001061FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1062 const FunctionDecl *FD){
1063 assert(FD && "Specialization is 0");
1064 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet0d95f0d2011-08-14 14:28:49 +00001065 = ClassScopeSpecializationPattern.find(FD);
1066 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001067 return 0;
1068
1069 return Pos->second;
1070}
1071
1072void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1073 FunctionDecl *Pattern) {
1074 assert(FD && "Specialization is 0");
1075 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet0d95f0d2011-08-14 14:28:49 +00001076 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001077}
1078
John McCall7ba107a2009-11-18 02:36:19 +00001079NamedDecl *
John McCalled976492009-12-04 22:46:56 +00001080ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +00001081 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +00001082 = InstantiatedFromUsingDecl.find(UUD);
1083 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +00001084 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001085
Anders Carlsson0d8df782009-08-29 19:37:28 +00001086 return Pos->second;
1087}
1088
1089void
John McCalled976492009-12-04 22:46:56 +00001090ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1091 assert((isa<UsingDecl>(Pattern) ||
1092 isa<UnresolvedUsingValueDecl>(Pattern) ||
1093 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1094 "pattern decl is not a using decl");
1095 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1096 InstantiatedFromUsingDecl[Inst] = Pattern;
1097}
1098
1099UsingShadowDecl *
1100ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1101 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1102 = InstantiatedFromUsingShadowDecl.find(Inst);
1103 if (Pos == InstantiatedFromUsingShadowDecl.end())
1104 return 0;
1105
1106 return Pos->second;
1107}
1108
1109void
1110ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1111 UsingShadowDecl *Pattern) {
1112 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1113 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00001114}
1115
Anders Carlssond8b285f2009-09-01 04:26:58 +00001116FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1117 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1118 = InstantiatedFromUnnamedFieldDecl.find(Field);
1119 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1120 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001121
Anders Carlssond8b285f2009-09-01 04:26:58 +00001122 return Pos->second;
1123}
1124
1125void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1126 FieldDecl *Tmpl) {
1127 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1128 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1129 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1130 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +00001131
Anders Carlssond8b285f2009-09-01 04:26:58 +00001132 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1133}
1134
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +00001135bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
1136 const FieldDecl *LastFD) const {
1137 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001138 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +00001139}
1140
Fariborz Jahanian340fa242011-05-02 17:20:56 +00001141bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
1142 const FieldDecl *LastFD) const {
1143 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001144 FD->getBitWidthValue(*this) == 0 &&
1145 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanian340fa242011-05-02 17:20:56 +00001146}
1147
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +00001148bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
1149 const FieldDecl *LastFD) const {
1150 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001151 FD->getBitWidthValue(*this) &&
1152 LastFD->getBitWidthValue(*this));
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +00001153}
1154
Chad Rosierdd7fddb2011-08-04 23:34:15 +00001155bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +00001156 const FieldDecl *LastFD) const {
1157 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001158 LastFD->getBitWidthValue(*this));
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +00001159}
1160
Chad Rosierdd7fddb2011-08-04 23:34:15 +00001161bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +00001162 const FieldDecl *LastFD) const {
1163 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001164 FD->getBitWidthValue(*this));
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +00001165}
1166
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001167ASTContext::overridden_cxx_method_iterator
1168ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1169 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001170 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001171 if (Pos == OverriddenMethods.end())
1172 return 0;
1173
1174 return Pos->second.begin();
1175}
1176
1177ASTContext::overridden_cxx_method_iterator
1178ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1179 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001180 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001181 if (Pos == OverriddenMethods.end())
1182 return 0;
1183
1184 return Pos->second.end();
1185}
1186
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +00001187unsigned
1188ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1189 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001190 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +00001191 if (Pos == OverriddenMethods.end())
1192 return 0;
1193
1194 return Pos->second.size();
1195}
1196
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001197void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1198 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidis38eb1e12012-10-09 01:23:45 +00001199 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor7d10b7e2010-03-02 23:58:15 +00001200 OverriddenMethods[Method].push_back(Overridden);
1201}
1202
Dmitri Gribenko1e905da2012-11-03 14:24:57 +00001203void ASTContext::getOverriddenMethods(
1204 const NamedDecl *D,
1205 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001206 assert(D);
1207
1208 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis685d1042013-04-17 00:09:03 +00001209 Overridden.append(overridden_methods_begin(CXXMethod),
1210 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001211 return;
1212 }
1213
1214 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1215 if (!Method)
1216 return;
1217
Argyrios Kyrtzidis740ae672012-10-09 18:19:01 +00001218 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1219 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisbc0a2bb2012-10-09 20:08:43 +00001220 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidis21c36072012-10-09 01:23:50 +00001221}
1222
Douglas Gregore6649772011-12-03 00:30:27 +00001223void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1224 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1225 assert(!Import->isFromASTFile() && "Non-local import declaration");
1226 if (!FirstLocalImport) {
1227 FirstLocalImport = Import;
1228 LastLocalImport = Import;
1229 return;
1230 }
1231
1232 LastLocalImport->NextLocalImport = Import;
1233 LastLocalImport = Import;
1234}
1235
Chris Lattner464175b2007-07-18 17:52:12 +00001236//===----------------------------------------------------------------------===//
1237// Type Sizing and Analysis
1238//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +00001239
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001240/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1241/// scalar floating point type.
1242const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +00001243 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001244 assert(BT && "Not a floating point type!");
1245 switch (BT->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001246 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001247 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001248 case BuiltinType::Float: return Target->getFloatFormat();
1249 case BuiltinType::Double: return Target->getDoubleFormat();
1250 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001251 }
1252}
1253
Ken Dyck8b752f12010-01-27 17:10:57 +00001254/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +00001255/// specified decl. Note that bitfields do not have a valid alignment, so
1256/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +00001257/// If @p RefAsPointee, references are treated like their underlying type
1258/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad4ba2a172011-01-12 09:06:06 +00001259CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001260 unsigned Align = Target->getCharWidth();
Eli Friedmandcdafb62009-02-22 02:56:25 +00001261
John McCall4081a5c2010-10-08 18:24:19 +00001262 bool UseAlignAttrOnly = false;
1263 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1264 Align = AlignFromAttr;
Eli Friedmandcdafb62009-02-22 02:56:25 +00001265
John McCall4081a5c2010-10-08 18:24:19 +00001266 // __attribute__((aligned)) can increase or decrease alignment
1267 // *except* on a struct or struct member, where it only increases
1268 // alignment unless 'packed' is also specified.
1269 //
Peter Collingbourne82d0b0a2011-09-29 18:04:28 +00001270 // It is an error for alignas to decrease alignment, so we can
John McCall4081a5c2010-10-08 18:24:19 +00001271 // ignore that possibility; Sema should diagnose it.
1272 if (isa<FieldDecl>(D)) {
1273 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1274 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1275 } else {
1276 UseAlignAttrOnly = true;
1277 }
1278 }
Fariborz Jahanian78a7d7d2011-05-05 21:19:14 +00001279 else if (isa<FieldDecl>(D))
1280 UseAlignAttrOnly =
1281 D->hasAttr<PackedAttr>() ||
1282 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall4081a5c2010-10-08 18:24:19 +00001283
John McCallba4f5d52011-01-20 07:57:12 +00001284 // If we're using the align attribute only, just ignore everything
1285 // else about the declaration and its type.
John McCall4081a5c2010-10-08 18:24:19 +00001286 if (UseAlignAttrOnly) {
John McCallba4f5d52011-01-20 07:57:12 +00001287 // do nothing
1288
John McCall4081a5c2010-10-08 18:24:19 +00001289 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00001290 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001291 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00001292 if (RefAsPointee)
1293 T = RT->getPointeeType();
1294 else
1295 T = getPointerType(RT->getPointeeType());
1296 }
1297 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall3b657512011-01-19 10:06:00 +00001298 // Adjust alignments of declarations with array type by the
1299 // large-array alignment on the target.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001300 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall3b657512011-01-19 10:06:00 +00001301 const ArrayType *arrayType;
1302 if (MinWidth && (arrayType = getAsArrayType(T))) {
1303 if (isa<VariableArrayType>(arrayType))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001304 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall3b657512011-01-19 10:06:00 +00001305 else if (isa<ConstantArrayType>(arrayType) &&
1306 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001307 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedmandcdafb62009-02-22 02:56:25 +00001308
John McCall3b657512011-01-19 10:06:00 +00001309 // Walk through any array types while we're at it.
1310 T = getBaseElementType(arrayType);
1311 }
Chad Rosier9f1210c2011-07-26 07:03:04 +00001312 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Ulrich Weigand6b203512013-05-06 16:23:57 +00001313 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1314 if (VD->hasGlobalStorage())
1315 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1316 }
Eli Friedmandcdafb62009-02-22 02:56:25 +00001317 }
John McCallba4f5d52011-01-20 07:57:12 +00001318
1319 // Fields can be subject to extra alignment constraints, like if
1320 // the field is packed, the struct is packed, or the struct has a
1321 // a max-field-alignment constraint (#pragma pack). So calculate
1322 // the actual alignment of the field within the struct, and then
1323 // (as we're expected to) constrain that by the alignment of the type.
1324 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
1325 // So calculate the alignment of the field.
1326 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
1327
1328 // Start with the record's overall alignment.
Ken Dyckdac54c12011-02-15 02:32:40 +00001329 unsigned fieldAlign = toBits(layout.getAlignment());
John McCallba4f5d52011-01-20 07:57:12 +00001330
1331 // Use the GCD of that and the offset within the record.
1332 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
1333 if (offset > 0) {
1334 // Alignment is always a power of 2, so the GCD will be a power of 2,
1335 // which means we get to do this crazy thing instead of Euclid's.
1336 uint64_t lowBitOfOffset = offset & (~offset + 1);
1337 if (lowBitOfOffset < fieldAlign)
1338 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
1339 }
1340
1341 Align = std::min(Align, fieldAlign);
Charles Davis05f62472010-02-23 04:52:00 +00001342 }
Chris Lattneraf707ab2009-01-24 21:53:27 +00001343 }
Eli Friedmandcdafb62009-02-22 02:56:25 +00001344
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001345 return toCharUnitsFromBits(Align);
Chris Lattneraf707ab2009-01-24 21:53:27 +00001346}
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001347
John McCall929bbfb2012-08-21 04:10:00 +00001348// getTypeInfoDataSizeInChars - Return the size of a type, in
1349// chars. If the type is a record, its data size is returned. This is
1350// the size of the memcpy that's performed when assigning this type
1351// using a trivial copy/move assignment operator.
1352std::pair<CharUnits, CharUnits>
1353ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1354 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1355
1356 // In C++, objects can sometimes be allocated into the tail padding
1357 // of a base-class subobject. We decide whether that's possible
1358 // during class layout, so here we can just trust the layout results.
1359 if (getLangOpts().CPlusPlus) {
1360 if (const RecordType *RT = T->getAs<RecordType>()) {
1361 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1362 sizeAndAlign.first = layout.getDataSize();
1363 }
1364 }
1365
1366 return sizeAndAlign;
1367}
1368
Richard Trieu910f17e2013-05-14 21:59:17 +00001369/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1370/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1371std::pair<CharUnits, CharUnits>
1372static getConstantArrayInfoInChars(const ASTContext &Context,
1373 const ConstantArrayType *CAT) {
1374 std::pair<CharUnits, CharUnits> EltInfo =
1375 Context.getTypeInfoInChars(CAT->getElementType());
1376 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieu1069b732013-05-14 23:41:50 +00001377 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1378 (uint64_t)(-1)/Size) &&
Richard Trieu910f17e2013-05-14 21:59:17 +00001379 "Overflow in array type char size evaluation");
1380 uint64_t Width = EltInfo.first.getQuantity() * Size;
1381 unsigned Align = EltInfo.second.getQuantity();
1382 Width = llvm::RoundUpToAlignment(Width, Align);
1383 return std::make_pair(CharUnits::fromQuantity(Width),
1384 CharUnits::fromQuantity(Align));
1385}
1386
John McCallea1471e2010-05-20 01:18:31 +00001387std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +00001388ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu910f17e2013-05-14 21:59:17 +00001389 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1390 return getConstantArrayInfoInChars(*this, CAT);
John McCallea1471e2010-05-20 01:18:31 +00001391 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001392 return std::make_pair(toCharUnitsFromBits(Info.first),
1393 toCharUnitsFromBits(Info.second));
John McCallea1471e2010-05-20 01:18:31 +00001394}
1395
1396std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +00001397ASTContext::getTypeInfoInChars(QualType T) const {
John McCallea1471e2010-05-20 01:18:31 +00001398 return getTypeInfoInChars(T.getTypePtr());
1399}
1400
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001401std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1402 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1403 if (it != MemoizedTypeInfo.end())
1404 return it->second;
1405
1406 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1407 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1408 return Info;
1409}
1410
1411/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1412/// method does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +00001413///
1414/// FIXME: Pointers into different addr spaces could have different sizes and
1415/// alignment requirements: getPointerInfo should take an AddrSpace, this
1416/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +00001417std::pair<uint64_t, unsigned>
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001418ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5e301002009-02-27 18:32:39 +00001419 uint64_t Width=0;
1420 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +00001421 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +00001422#define TYPE(Class, Base)
1423#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +00001424#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +00001425#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1426#include "clang/AST/TypeNodes.def"
John McCalld3d49bb2011-06-28 16:49:23 +00001427 llvm_unreachable("Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +00001428
Chris Lattner692233e2007-07-13 22:27:08 +00001429 case Type::FunctionNoProto:
1430 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +00001431 // GCC extension: alignof(function) = 32 bits
1432 Width = 0;
1433 Align = 32;
1434 break;
1435
Douglas Gregor72564e72009-02-26 23:50:07 +00001436 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +00001437 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +00001438 Width = 0;
1439 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1440 break;
1441
Steve Narofffb22d962007-08-30 01:06:46 +00001442 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001443 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001444
Chris Lattner98be4942008-03-05 18:54:05 +00001445 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarafea966a2011-12-13 11:23:52 +00001446 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarbc5419a2012-03-09 04:12:54 +00001447 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1448 "Overflow in array type bit size evaluation");
Abramo Bagnarafea966a2011-12-13 11:23:52 +00001449 Width = EltInfo.first*Size;
Chris Lattner030d8842007-07-19 22:06:24 +00001450 Align = EltInfo.second;
Argyrios Kyrtzidiscd88b412011-04-26 21:05:39 +00001451 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattner030d8842007-07-19 22:06:24 +00001452 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +00001453 }
Nate Begeman213541a2008-04-18 23:10:10 +00001454 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +00001455 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +00001456 const VectorType *VT = cast<VectorType>(T);
1457 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1458 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +00001459 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +00001460 // If the alignment is not a power of 2, round up to the next power of 2.
1461 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +00001462 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +00001463 Align = llvm::NextPowerOf2(Align);
1464 Width = llvm::RoundUpToAlignment(Width, Align);
1465 }
Chad Rosierf9e9af72012-07-13 23:57:43 +00001466 // Adjust the alignment based on the target max.
1467 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1468 if (TargetVectorAlign && TargetVectorAlign < Align)
1469 Align = TargetVectorAlign;
Chris Lattner030d8842007-07-19 22:06:24 +00001470 break;
1471 }
Chris Lattner5d2a6302007-07-18 18:26:58 +00001472
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001473 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +00001474 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001475 default: llvm_unreachable("Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +00001476 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +00001477 // GCC extension: alignof(void) = 8 bits.
1478 Width = 0;
1479 Align = 8;
1480 break;
1481
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001482 case BuiltinType::Bool:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001483 Width = Target->getBoolWidth();
1484 Align = Target->getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001485 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001486 case BuiltinType::Char_S:
1487 case BuiltinType::Char_U:
1488 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001489 case BuiltinType::SChar:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001490 Width = Target->getCharWidth();
1491 Align = Target->getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001492 break;
Chris Lattner3f59c972010-12-25 23:25:43 +00001493 case BuiltinType::WChar_S:
1494 case BuiltinType::WChar_U:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001495 Width = Target->getWCharWidth();
1496 Align = Target->getWCharAlign();
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00001497 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001498 case BuiltinType::Char16:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001499 Width = Target->getChar16Width();
1500 Align = Target->getChar16Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001501 break;
1502 case BuiltinType::Char32:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001503 Width = Target->getChar32Width();
1504 Align = Target->getChar32Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001505 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001506 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001507 case BuiltinType::Short:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001508 Width = Target->getShortWidth();
1509 Align = Target->getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001510 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001511 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001512 case BuiltinType::Int:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001513 Width = Target->getIntWidth();
1514 Align = Target->getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001515 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001516 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001517 case BuiltinType::Long:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001518 Width = Target->getLongWidth();
1519 Align = Target->getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001520 break;
Chris Lattner692233e2007-07-13 22:27:08 +00001521 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001522 case BuiltinType::LongLong:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001523 Width = Target->getLongLongWidth();
1524 Align = Target->getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001525 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +00001526 case BuiltinType::Int128:
1527 case BuiltinType::UInt128:
1528 Width = 128;
1529 Align = 128; // int128_t is 128-bit aligned on all targets.
1530 break;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001531 case BuiltinType::Half:
1532 Width = Target->getHalfWidth();
1533 Align = Target->getHalfAlign();
1534 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001535 case BuiltinType::Float:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001536 Width = Target->getFloatWidth();
1537 Align = Target->getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001538 break;
1539 case BuiltinType::Double:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001540 Width = Target->getDoubleWidth();
1541 Align = Target->getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001542 break;
1543 case BuiltinType::LongDouble:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001544 Width = Target->getLongDoubleWidth();
1545 Align = Target->getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001546 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001547 case BuiltinType::NullPtr:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001548 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1549 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +00001550 break;
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +00001551 case BuiltinType::ObjCId:
1552 case BuiltinType::ObjCClass:
1553 case BuiltinType::ObjCSel:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001554 Width = Target->getPointerWidth(0);
1555 Align = Target->getPointerAlign(0);
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +00001556 break;
Guy Benyei21f18c42013-02-07 10:55:47 +00001557 case BuiltinType::OCLSampler:
1558 // Samplers are modeled as integers.
1559 Width = Target->getIntWidth();
1560 Align = Target->getIntAlign();
1561 break;
Guy Benyeie6b9d802013-01-20 12:31:11 +00001562 case BuiltinType::OCLEvent:
Guy Benyeib13621d2012-12-18 14:38:23 +00001563 case BuiltinType::OCLImage1d:
1564 case BuiltinType::OCLImage1dArray:
1565 case BuiltinType::OCLImage1dBuffer:
1566 case BuiltinType::OCLImage2d:
1567 case BuiltinType::OCLImage2dArray:
1568 case BuiltinType::OCLImage3d:
1569 // Currently these types are pointers to opaque types.
1570 Width = Target->getPointerWidth(0);
1571 Align = Target->getPointerAlign(0);
1572 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001573 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +00001574 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001575 case Type::ObjCObjectPointer:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001576 Width = Target->getPointerWidth(0);
1577 Align = Target->getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +00001578 break;
Steve Naroff485eeff2008-09-24 15:05:44 +00001579 case Type::BlockPointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001580 unsigned AS = getTargetAddressSpace(
1581 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001582 Width = Target->getPointerWidth(AS);
1583 Align = Target->getPointerAlign(AS);
Steve Naroff485eeff2008-09-24 15:05:44 +00001584 break;
1585 }
Sebastian Redl5d484e82009-11-23 17:18:46 +00001586 case Type::LValueReference:
1587 case Type::RValueReference: {
1588 // alignof and sizeof should never enter this code path here, so we go
1589 // the pointer route.
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001590 unsigned AS = getTargetAddressSpace(
1591 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001592 Width = Target->getPointerWidth(AS);
1593 Align = Target->getPointerAlign(AS);
Sebastian Redl5d484e82009-11-23 17:18:46 +00001594 break;
1595 }
Chris Lattnerf72a4432008-03-08 08:34:58 +00001596 case Type::Pointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001597 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001598 Width = Target->getPointerWidth(AS);
1599 Align = Target->getPointerAlign(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +00001600 break;
1601 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00001602 case Type::MemberPointer: {
Charles Davis071cc7d2010-08-16 03:33:14 +00001603 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Reid Kleckner84e9ab42013-03-28 20:02:56 +00001604 llvm::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson1cca74e2009-05-17 02:06:04 +00001605 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +00001606 }
Chris Lattner5d2a6302007-07-18 18:26:58 +00001607 case Type::Complex: {
1608 // Complex types have the same alignment as their elements, but twice the
1609 // size.
Mike Stump1eb44332009-09-09 15:08:12 +00001610 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +00001611 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001612 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +00001613 Align = EltInfo.second;
1614 break;
1615 }
John McCallc12c5bb2010-05-15 11:32:37 +00001616 case Type::ObjCObject:
1617 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +00001618 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001619 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +00001620 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001621 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001622 Align = toBits(Layout.getAlignment());
Devang Patel44a3dde2008-06-04 21:54:36 +00001623 break;
1624 }
Douglas Gregor72564e72009-02-26 23:50:07 +00001625 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00001626 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001627 const TagType *TT = cast<TagType>(T);
1628
1629 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor22ce41d2011-04-20 17:29:44 +00001630 Width = 8;
1631 Align = 8;
Chris Lattner8389eab2008-08-09 21:35:13 +00001632 break;
1633 }
Mike Stump1eb44332009-09-09 15:08:12 +00001634
Daniel Dunbar1d751182008-11-08 05:48:37 +00001635 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +00001636 return getTypeInfo(ET->getDecl()->getIntegerType());
1637
Daniel Dunbar1d751182008-11-08 05:48:37 +00001638 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +00001639 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001640 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001641 Align = toBits(Layout.getAlignment());
Chris Lattnerdc0d73e2007-07-23 22:46:22 +00001642 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001643 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001644
Chris Lattner9fcfe922009-10-22 05:17:15 +00001645 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +00001646 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1647 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +00001648
Richard Smith34b41d92011-02-20 03:19:35 +00001649 case Type::Auto: {
1650 const AutoType *A = cast<AutoType>(T);
Richard Smithdc7a4f52013-04-30 13:56:41 +00001651 assert(!A->getDeducedType().isNull() &&
1652 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gaydc856af2011-02-22 20:00:16 +00001653 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith34b41d92011-02-20 03:19:35 +00001654 }
1655
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001656 case Type::Paren:
1657 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1658
Douglas Gregor18857642009-04-30 17:32:17 +00001659 case Type::Typedef: {
Richard Smith162e1c12011-04-15 14:24:37 +00001660 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregordf1367a2010-08-27 00:11:28 +00001661 std::pair<uint64_t, unsigned> Info
1662 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattnerc1de52d2011-02-19 22:55:41 +00001663 // If the typedef has an aligned attribute on it, it overrides any computed
1664 // alignment we have. This violates the GCC documentation (which says that
1665 // attribute(aligned) can only round up) but matches its implementation.
1666 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1667 Align = AttrAlign;
1668 else
1669 Align = Info.second;
Douglas Gregordf1367a2010-08-27 00:11:28 +00001670 Width = Info.first;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001671 break;
Chris Lattner71763312008-04-06 22:05:18 +00001672 }
Douglas Gregor18857642009-04-30 17:32:17 +00001673
1674 case Type::TypeOfExpr:
1675 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1676 .getTypePtr());
1677
1678 case Type::TypeOf:
1679 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1680
Anders Carlsson395b4752009-06-24 19:06:50 +00001681 case Type::Decltype:
1682 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1683 .getTypePtr());
1684
Sean Huntca63c202011-05-24 22:41:36 +00001685 case Type::UnaryTransform:
1686 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1687
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001688 case Type::Elaborated:
1689 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +00001690
John McCall9d156a72011-01-06 01:58:22 +00001691 case Type::Attributed:
1692 return getTypeInfo(
1693 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1694
Richard Smith3e4c6c42011-05-05 21:57:07 +00001695 case Type::TemplateSpecialization: {
Mike Stump1eb44332009-09-09 15:08:12 +00001696 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +00001697 "Cannot request the size of a dependent type");
Richard Smith3e4c6c42011-05-05 21:57:07 +00001698 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1699 // A type alias template specialization may refer to a typedef with the
1700 // aligned attribute on it.
1701 if (TST->isTypeAlias())
1702 return getTypeInfo(TST->getAliasedType().getTypePtr());
1703 else
1704 return getTypeInfo(getCanonicalType(T));
1705 }
1706
Eli Friedmanb001de72011-10-06 23:00:33 +00001707 case Type::Atomic: {
John McCall9eda3ab2013-03-07 21:37:17 +00001708 // Start with the base type information.
Eli Friedman2be46072011-10-14 20:59:01 +00001709 std::pair<uint64_t, unsigned> Info
1710 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1711 Width = Info.first;
1712 Align = Info.second;
John McCall9eda3ab2013-03-07 21:37:17 +00001713
1714 // If the size of the type doesn't exceed the platform's max
1715 // atomic promotion width, make the size and alignment more
1716 // favorable to atomic operations:
1717 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1718 // Round the size up to a power of 2.
1719 if (!llvm::isPowerOf2_64(Width))
1720 Width = llvm::NextPowerOf2(Width);
1721
1722 // Set the alignment equal to the size.
Eli Friedman2be46072011-10-14 20:59:01 +00001723 Align = static_cast<unsigned>(Width);
1724 }
Eli Friedmanb001de72011-10-06 23:00:33 +00001725 }
1726
Douglas Gregor18857642009-04-30 17:32:17 +00001727 }
Mike Stump1eb44332009-09-09 15:08:12 +00001728
Eli Friedman2be46072011-10-14 20:59:01 +00001729 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001730 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +00001731}
1732
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001733/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1734CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1735 return CharUnits::fromQuantity(BitSize / getCharWidth());
1736}
1737
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001738/// toBits - Convert a size in characters to a size in characters.
1739int64_t ASTContext::toBits(CharUnits CharSize) const {
1740 return CharSize.getQuantity() * getCharWidth();
1741}
1742
Ken Dyckbdc601b2009-12-22 14:23:30 +00001743/// getTypeSizeInChars - Return the size of the specified type, in characters.
1744/// This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001745CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu910f17e2013-05-14 21:59:17 +00001746 return getTypeInfoInChars(T).first;
Ken Dyckbdc601b2009-12-22 14:23:30 +00001747}
Jay Foad4ba2a172011-01-12 09:06:06 +00001748CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu910f17e2013-05-14 21:59:17 +00001749 return getTypeInfoInChars(T).first;
Ken Dyckbdc601b2009-12-22 14:23:30 +00001750}
1751
Ken Dyck16e20cc2010-01-26 17:25:18 +00001752/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +00001753/// characters. This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001754CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001755 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001756}
Jay Foad4ba2a172011-01-12 09:06:06 +00001757CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001758 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001759}
1760
Chris Lattner34ebde42009-01-27 18:08:34 +00001761/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1762/// type for the current target in bits. This can be different than the ABI
1763/// alignment in cases where it is beneficial for performance to overalign
1764/// a data type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001765unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattner34ebde42009-01-27 18:08:34 +00001766 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +00001767
1768 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +00001769 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +00001770 T = CT->getElementType().getTypePtr();
1771 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosiercde7a1d2012-03-21 20:20:47 +00001772 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1773 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman1eed6022009-05-25 21:27:19 +00001774 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1775
Chris Lattner34ebde42009-01-27 18:08:34 +00001776 return ABIAlign;
1777}
1778
Ulrich Weigand6b203512013-05-06 16:23:57 +00001779/// getAlignOfGlobalVar - Return the alignment in bits that should be given
1780/// to a global variable of the specified type.
1781unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1782 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1783}
1784
1785/// getAlignOfGlobalVarInChars - Return the alignment in characters that
1786/// should be given to a global variable of the specified type.
1787CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1788 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1789}
1790
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001791/// DeepCollectObjCIvars -
1792/// This routine first collects all declared, but not synthesized, ivars in
1793/// super class and then collects all ivars, including those synthesized for
1794/// current class. This routine is used for implementation of current class
1795/// when all ivars, declared and synthesized are known.
Fariborz Jahanian98200742009-05-12 18:14:29 +00001796///
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001797void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1798 bool leafClass,
Jordy Rosedb8264e2011-07-22 02:08:32 +00001799 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001800 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1801 DeepCollectObjCIvars(SuperClass, false, Ivars);
1802 if (!leafClass) {
1803 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1804 E = OI->ivar_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001805 Ivars.push_back(*I);
Chad Rosier30601782011-08-17 23:08:45 +00001806 } else {
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001807 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosedb8264e2011-07-22 02:08:32 +00001808 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001809 Iv= Iv->getNextIvar())
1810 Ivars.push_back(Iv);
1811 }
Fariborz Jahanian98200742009-05-12 18:14:29 +00001812}
1813
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001814/// CollectInheritedProtocols - Collect all protocols in current class and
1815/// those inherited by it.
1816void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001817 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001818 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001819 // We can use protocol_iterator here instead of
1820 // all_referenced_protocol_iterator since we are walking all categories.
1821 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1822 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001823 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001824 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001825 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001826 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001827 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001828 CollectInheritedProtocols(*P, Protocols);
1829 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001830 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001831
1832 // Categories of this Interface.
Douglas Gregord3297242013-01-16 23:00:23 +00001833 for (ObjCInterfaceDecl::visible_categories_iterator
1834 Cat = OI->visible_categories_begin(),
1835 CatEnd = OI->visible_categories_end();
1836 Cat != CatEnd; ++Cat) {
1837 CollectInheritedProtocols(*Cat, Protocols);
1838 }
1839
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001840 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1841 while (SD) {
1842 CollectInheritedProtocols(SD, Protocols);
1843 SD = SD->getSuperClass();
1844 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001845 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001846 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001847 PE = OC->protocol_end(); P != PE; ++P) {
1848 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001849 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001850 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1851 PE = Proto->protocol_end(); P != PE; ++P)
1852 CollectInheritedProtocols(*P, Protocols);
1853 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001854 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001855 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1856 PE = OP->protocol_end(); P != PE; ++P) {
1857 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00001858 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001859 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1860 PE = Proto->protocol_end(); P != PE; ++P)
1861 CollectInheritedProtocols(*P, Protocols);
1862 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001863 }
1864}
1865
Jay Foad4ba2a172011-01-12 09:06:06 +00001866unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001867 unsigned count = 0;
1868 // Count ivars declared in class extension.
Douglas Gregord3297242013-01-16 23:00:23 +00001869 for (ObjCInterfaceDecl::known_extensions_iterator
1870 Ext = OI->known_extensions_begin(),
1871 ExtEnd = OI->known_extensions_end();
1872 Ext != ExtEnd; ++Ext) {
1873 count += Ext->ivar_size();
1874 }
1875
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001876 // Count ivar defined in this class's implementation. This
1877 // includes synthesized ivars.
1878 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001879 count += ImplDecl->ivar_size();
1880
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001881 return count;
1882}
1883
Argyrios Kyrtzidis8deabc12012-02-03 05:58:16 +00001884bool ASTContext::isSentinelNullExpr(const Expr *E) {
1885 if (!E)
1886 return false;
1887
1888 // nullptr_t is always treated as null.
1889 if (E->getType()->isNullPtrType()) return true;
1890
1891 if (E->getType()->isAnyPointerType() &&
1892 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1893 Expr::NPC_ValueDependentIsNull))
1894 return true;
1895
1896 // Unfortunately, __null has type 'int'.
1897 if (isa<GNUNullExpr>(E)) return true;
1898
1899 return false;
1900}
1901
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +00001902/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1903ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1904 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1905 I = ObjCImpls.find(D);
1906 if (I != ObjCImpls.end())
1907 return cast<ObjCImplementationDecl>(I->second);
1908 return 0;
1909}
1910/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1911ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1912 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1913 I = ObjCImpls.find(D);
1914 if (I != ObjCImpls.end())
1915 return cast<ObjCCategoryImplDecl>(I->second);
1916 return 0;
1917}
1918
1919/// \brief Set the implementation of ObjCInterfaceDecl.
1920void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1921 ObjCImplementationDecl *ImplD) {
1922 assert(IFaceD && ImplD && "Passed null params");
1923 ObjCImpls[IFaceD] = ImplD;
1924}
1925/// \brief Set the implementation of ObjCCategoryDecl.
1926void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1927 ObjCCategoryImplDecl *ImplD) {
1928 assert(CatD && ImplD && "Passed null params");
1929 ObjCImpls[CatD] = ImplD;
1930}
1931
Dmitri Gribenkob35cc2d2013-02-03 13:23:21 +00001932const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
1933 const NamedDecl *ND) const {
1934 if (const ObjCInterfaceDecl *ID =
1935 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001936 return ID;
Dmitri Gribenkob35cc2d2013-02-03 13:23:21 +00001937 if (const ObjCCategoryDecl *CD =
1938 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001939 return CD->getClassInterface();
Dmitri Gribenkob35cc2d2013-02-03 13:23:21 +00001940 if (const ObjCImplDecl *IMD =
1941 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001942 return IMD->getClassInterface();
1943
1944 return 0;
1945}
1946
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001947/// \brief Get the copy initialization expression of VarDecl,or NULL if
1948/// none exists.
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001949Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001950 assert(VD && "Passed null params");
1951 assert(VD->hasAttr<BlocksAttr>() &&
1952 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001953 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001954 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001955 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1956}
1957
1958/// \brief Set the copy inialization expression of a block var decl.
1959void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1960 assert(VD && Init && "Passed null params");
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001961 assert(VD->hasAttr<BlocksAttr>() &&
1962 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001963 BlockVarCopyInits[VD] = Init;
1964}
1965
John McCalla93c9342009-12-07 02:54:59 +00001966TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001967 unsigned DataSize) const {
John McCall109de5e2009-10-21 00:23:54 +00001968 if (!DataSize)
1969 DataSize = TypeLoc::getFullDataSizeForType(T);
1970 else
1971 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001972 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001973
John McCalla93c9342009-12-07 02:54:59 +00001974 TypeSourceInfo *TInfo =
1975 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1976 new (TInfo) TypeSourceInfo(T);
1977 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001978}
1979
John McCalla93c9342009-12-07 02:54:59 +00001980TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001981 SourceLocation L) const {
John McCalla93c9342009-12-07 02:54:59 +00001982 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregorc21c7e92011-01-25 19:13:18 +00001983 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCalla4eb74d2009-10-23 21:14:09 +00001984 return DI;
1985}
1986
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001987const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001988ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001989 return getObjCLayout(D, 0);
1990}
1991
1992const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001993ASTContext::getASTObjCImplementationLayout(
1994 const ObjCImplementationDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001995 return getObjCLayout(D->getClassInterface(), D);
1996}
1997
Chris Lattnera7674d82007-07-13 22:13:22 +00001998//===----------------------------------------------------------------------===//
1999// Type creation/memoization methods
2000//===----------------------------------------------------------------------===//
2001
Jay Foad4ba2a172011-01-12 09:06:06 +00002002QualType
John McCall3b657512011-01-19 10:06:00 +00002003ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2004 unsigned fastQuals = quals.getFastQualifiers();
2005 quals.removeFastQualifiers();
John McCall0953e762009-09-24 19:53:00 +00002006
2007 // Check if we've already instantiated this type.
2008 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00002009 ExtQuals::Profile(ID, baseType, quals);
2010 void *insertPos = 0;
2011 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2012 assert(eq->getQualifiers() == quals);
2013 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00002014 }
2015
John McCall3b657512011-01-19 10:06:00 +00002016 // If the base type is not canonical, make the appropriate canonical type.
2017 QualType canon;
2018 if (!baseType->isCanonicalUnqualified()) {
2019 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall200fa532012-02-08 00:46:36 +00002020 canonSplit.Quals.addConsistentQualifiers(quals);
2021 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00002022
2023 // Re-find the insert position.
2024 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2025 }
2026
2027 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2028 ExtQualNodes.InsertNode(eq, insertPos);
2029 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00002030}
2031
Jay Foad4ba2a172011-01-12 09:06:06 +00002032QualType
2033ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002034 QualType CanT = getCanonicalType(T);
2035 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00002036 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00002037
John McCall0953e762009-09-24 19:53:00 +00002038 // If we are composing extended qualifiers together, merge together
2039 // into one ExtQuals node.
2040 QualifierCollector Quals;
2041 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002042
John McCall0953e762009-09-24 19:53:00 +00002043 // If this type already has an address space specified, it cannot get
2044 // another one.
2045 assert(!Quals.hasAddressSpace() &&
2046 "Type cannot be in multiple addr spaces!");
2047 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00002048
John McCall0953e762009-09-24 19:53:00 +00002049 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00002050}
2051
Chris Lattnerb7d25532009-02-18 22:53:11 +00002052QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00002053 Qualifiers::GC GCAttr) const {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00002054 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00002055 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00002056 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00002057
John McCall7f040a92010-12-24 02:08:15 +00002058 if (const PointerType *ptr = T->getAs<PointerType>()) {
2059 QualType Pointee = ptr->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00002060 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00002061 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2062 return getPointerType(ResultType);
2063 }
2064 }
Mike Stump1eb44332009-09-09 15:08:12 +00002065
John McCall0953e762009-09-24 19:53:00 +00002066 // If we are composing extended qualifiers together, merge together
2067 // into one ExtQuals node.
2068 QualifierCollector Quals;
2069 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002070
John McCall0953e762009-09-24 19:53:00 +00002071 // If this type already has an ObjCGC specified, it cannot get
2072 // another one.
2073 assert(!Quals.hasObjCGCAttr() &&
2074 "Type cannot have multiple ObjCGCs!");
2075 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00002076
John McCall0953e762009-09-24 19:53:00 +00002077 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00002078}
Chris Lattnera7674d82007-07-13 22:13:22 +00002079
John McCalle6a365d2010-12-19 02:44:49 +00002080const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2081 FunctionType::ExtInfo Info) {
2082 if (T->getExtInfo() == Info)
2083 return T;
2084
2085 QualType Result;
2086 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
2087 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
2088 } else {
2089 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2090 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2091 EPI.ExtInfo = Info;
Reid Kleckner0567a792013-06-10 20:51:09 +00002092 Result = getFunctionType(FPT->getResultType(), FPT->getArgTypes(), EPI);
John McCalle6a365d2010-12-19 02:44:49 +00002093 }
2094
2095 return cast<FunctionType>(Result.getTypePtr());
2096}
2097
Richard Smith60e141e2013-05-04 07:00:32 +00002098void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2099 QualType ResultType) {
Richard Smith9dadfab2013-05-11 05:45:24 +00002100 FD = FD->getMostRecentDecl();
2101 while (true) {
Richard Smith60e141e2013-05-04 07:00:32 +00002102 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2103 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2104 FD->setType(getFunctionType(ResultType, FPT->getArgTypes(), EPI));
Richard Smith9dadfab2013-05-11 05:45:24 +00002105 if (FunctionDecl *Next = FD->getPreviousDecl())
2106 FD = Next;
2107 else
2108 break;
Richard Smith60e141e2013-05-04 07:00:32 +00002109 }
Richard Smith9dadfab2013-05-11 05:45:24 +00002110 if (ASTMutationListener *L = getASTMutationListener())
2111 L->DeducedReturnType(FD, ResultType);
Richard Smith60e141e2013-05-04 07:00:32 +00002112}
2113
Reid Spencer5f016e22007-07-11 17:01:13 +00002114/// getComplexType - Return the uniqued reference to the type for a complex
2115/// number with the specified element type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002116QualType ASTContext::getComplexType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002117 // Unique pointers, to guarantee there is only one pointer of a particular
2118 // structure.
2119 llvm::FoldingSetNodeID ID;
2120 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00002121
Reid Spencer5f016e22007-07-11 17:01:13 +00002122 void *InsertPos = 0;
2123 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2124 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002125
Reid Spencer5f016e22007-07-11 17:01:13 +00002126 // If the pointee type isn't canonical, this won't be a canonical type either,
2127 // so fill in the canonical type field.
2128 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002129 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002130 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00002131
Reid Spencer5f016e22007-07-11 17:01:13 +00002132 // Get the new insert position for the node we care about.
2133 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002134 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002135 }
John McCall6b304a02009-09-24 23:30:46 +00002136 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00002137 Types.push_back(New);
2138 ComplexTypes.InsertNode(New, InsertPos);
2139 return QualType(New, 0);
2140}
2141
Reid Spencer5f016e22007-07-11 17:01:13 +00002142/// getPointerType - Return the uniqued reference to the type for a pointer to
2143/// the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002144QualType ASTContext::getPointerType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002145 // Unique pointers, to guarantee there is only one pointer of a particular
2146 // structure.
2147 llvm::FoldingSetNodeID ID;
2148 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00002149
Reid Spencer5f016e22007-07-11 17:01:13 +00002150 void *InsertPos = 0;
2151 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2152 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002153
Reid Spencer5f016e22007-07-11 17:01:13 +00002154 // If the pointee type isn't canonical, this won't be a canonical type either,
2155 // so fill in the canonical type field.
2156 QualType Canonical;
Bob Wilsonc90cc932013-03-15 17:12:43 +00002157 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002158 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00002159
Bob Wilsonc90cc932013-03-15 17:12:43 +00002160 // Get the new insert position for the node we care about.
2161 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2162 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2163 }
John McCall6b304a02009-09-24 23:30:46 +00002164 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00002165 Types.push_back(New);
2166 PointerTypes.InsertNode(New, InsertPos);
2167 return QualType(New, 0);
2168}
2169
Mike Stump1eb44332009-09-09 15:08:12 +00002170/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00002171/// a pointer to the specified block.
Jay Foad4ba2a172011-01-12 09:06:06 +00002172QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff296e8d52008-08-28 19:20:44 +00002173 assert(T->isFunctionType() && "block of function types only");
2174 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00002175 // structure.
2176 llvm::FoldingSetNodeID ID;
2177 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00002178
Steve Naroff5618bd42008-08-27 16:04:49 +00002179 void *InsertPos = 0;
2180 if (BlockPointerType *PT =
2181 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2182 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002183
2184 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00002185 // type either so fill in the canonical type field.
2186 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002187 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00002188 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00002189
Steve Naroff5618bd42008-08-27 16:04:49 +00002190 // Get the new insert position for the node we care about.
2191 BlockPointerType *NewIP =
2192 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002193 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00002194 }
John McCall6b304a02009-09-24 23:30:46 +00002195 BlockPointerType *New
2196 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00002197 Types.push_back(New);
2198 BlockPointerTypes.InsertNode(New, InsertPos);
2199 return QualType(New, 0);
2200}
2201
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002202/// getLValueReferenceType - Return the uniqued reference to the type for an
2203/// lvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002204QualType
2205ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor9625e442011-05-21 22:16:50 +00002206 assert(getCanonicalType(T) != OverloadTy &&
2207 "Unresolved overloaded function type");
2208
Reid Spencer5f016e22007-07-11 17:01:13 +00002209 // Unique pointers, to guarantee there is only one pointer of a particular
2210 // structure.
2211 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00002212 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00002213
2214 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002215 if (LValueReferenceType *RT =
2216 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002217 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002218
John McCall54e14c42009-10-22 22:37:11 +00002219 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2220
Reid Spencer5f016e22007-07-11 17:01:13 +00002221 // If the referencee type isn't canonical, this won't be a canonical type
2222 // either, so fill in the canonical type field.
2223 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00002224 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2225 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2226 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002227
Reid Spencer5f016e22007-07-11 17:01:13 +00002228 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002229 LValueReferenceType *NewIP =
2230 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002231 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002232 }
2233
John McCall6b304a02009-09-24 23:30:46 +00002234 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00002235 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2236 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00002237 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002238 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00002239
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002240 return QualType(New, 0);
2241}
2242
2243/// getRValueReferenceType - Return the uniqued reference to the type for an
2244/// rvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002245QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002246 // Unique pointers, to guarantee there is only one pointer of a particular
2247 // structure.
2248 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00002249 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002250
2251 void *InsertPos = 0;
2252 if (RValueReferenceType *RT =
2253 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2254 return QualType(RT, 0);
2255
John McCall54e14c42009-10-22 22:37:11 +00002256 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2257
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002258 // If the referencee type isn't canonical, this won't be a canonical type
2259 // either, so fill in the canonical type field.
2260 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00002261 if (InnerRef || !T.isCanonical()) {
2262 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2263 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002264
2265 // Get the new insert position for the node we care about.
2266 RValueReferenceType *NewIP =
2267 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002268 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002269 }
2270
John McCall6b304a02009-09-24 23:30:46 +00002271 RValueReferenceType *New
2272 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002273 Types.push_back(New);
2274 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002275 return QualType(New, 0);
2276}
2277
Sebastian Redlf30208a2009-01-24 21:16:55 +00002278/// getMemberPointerType - Return the uniqued reference to the type for a
2279/// member pointer to the specified type, in the specified class.
Jay Foad4ba2a172011-01-12 09:06:06 +00002280QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redlf30208a2009-01-24 21:16:55 +00002281 // Unique pointers, to guarantee there is only one pointer of a particular
2282 // structure.
2283 llvm::FoldingSetNodeID ID;
2284 MemberPointerType::Profile(ID, T, Cls);
2285
2286 void *InsertPos = 0;
2287 if (MemberPointerType *PT =
2288 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2289 return QualType(PT, 0);
2290
2291 // If the pointee or class type isn't canonical, this won't be a canonical
2292 // type either, so fill in the canonical type field.
2293 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00002294 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00002295 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2296
2297 // Get the new insert position for the node we care about.
2298 MemberPointerType *NewIP =
2299 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002300 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redlf30208a2009-01-24 21:16:55 +00002301 }
John McCall6b304a02009-09-24 23:30:46 +00002302 MemberPointerType *New
2303 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00002304 Types.push_back(New);
2305 MemberPointerTypes.InsertNode(New, InsertPos);
2306 return QualType(New, 0);
2307}
2308
Mike Stump1eb44332009-09-09 15:08:12 +00002309/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00002310/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002311QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00002312 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00002313 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002314 unsigned IndexTypeQuals) const {
Sebastian Redl923d56d2009-11-05 15:52:31 +00002315 assert((EltTy->isDependentType() ||
2316 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00002317 "Constant array of VLAs is illegal!");
2318
Chris Lattner38aeec72009-05-13 04:12:56 +00002319 // Convert the array size into a canonical width matching the pointer size for
2320 // the target.
2321 llvm::APInt ArySize(ArySizeIn);
Jay Foad9f71a8f2010-12-07 08:25:34 +00002322 ArySize =
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002323 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump1eb44332009-09-09 15:08:12 +00002324
Reid Spencer5f016e22007-07-11 17:01:13 +00002325 llvm::FoldingSetNodeID ID;
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002326 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00002327
Reid Spencer5f016e22007-07-11 17:01:13 +00002328 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002329 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002330 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002331 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002332
John McCall3b657512011-01-19 10:06:00 +00002333 // If the element type isn't canonical or has qualifiers, this won't
2334 // be a canonical type either, so fill in the canonical type field.
2335 QualType Canon;
2336 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2337 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00002338 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002339 ASM, IndexTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00002340 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall3b657512011-01-19 10:06:00 +00002341
Reid Spencer5f016e22007-07-11 17:01:13 +00002342 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00002343 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002344 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002345 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002346 }
Mike Stump1eb44332009-09-09 15:08:12 +00002347
John McCall6b304a02009-09-24 23:30:46 +00002348 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002349 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00002350 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002351 Types.push_back(New);
2352 return QualType(New, 0);
2353}
2354
John McCallce889032011-01-18 08:40:38 +00002355/// getVariableArrayDecayedType - Turns the given type, which may be
2356/// variably-modified, into the corresponding type with all the known
2357/// sizes replaced with [*].
2358QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2359 // Vastly most common case.
2360 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002361
John McCallce889032011-01-18 08:40:38 +00002362 QualType result;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002363
John McCallce889032011-01-18 08:40:38 +00002364 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00002365 const Type *ty = split.Ty;
John McCallce889032011-01-18 08:40:38 +00002366 switch (ty->getTypeClass()) {
2367#define TYPE(Class, Base)
2368#define ABSTRACT_TYPE(Class, Base)
2369#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2370#include "clang/AST/TypeNodes.def"
2371 llvm_unreachable("didn't desugar past all non-canonical types?");
2372
2373 // These types should never be variably-modified.
2374 case Type::Builtin:
2375 case Type::Complex:
2376 case Type::Vector:
2377 case Type::ExtVector:
2378 case Type::DependentSizedExtVector:
2379 case Type::ObjCObject:
2380 case Type::ObjCInterface:
2381 case Type::ObjCObjectPointer:
2382 case Type::Record:
2383 case Type::Enum:
2384 case Type::UnresolvedUsing:
2385 case Type::TypeOfExpr:
2386 case Type::TypeOf:
2387 case Type::Decltype:
Sean Huntca63c202011-05-24 22:41:36 +00002388 case Type::UnaryTransform:
John McCallce889032011-01-18 08:40:38 +00002389 case Type::DependentName:
2390 case Type::InjectedClassName:
2391 case Type::TemplateSpecialization:
2392 case Type::DependentTemplateSpecialization:
2393 case Type::TemplateTypeParm:
2394 case Type::SubstTemplateTypeParmPack:
Richard Smith34b41d92011-02-20 03:19:35 +00002395 case Type::Auto:
John McCallce889032011-01-18 08:40:38 +00002396 case Type::PackExpansion:
2397 llvm_unreachable("type should never be variably-modified");
2398
2399 // These types can be variably-modified but should never need to
2400 // further decay.
2401 case Type::FunctionNoProto:
2402 case Type::FunctionProto:
2403 case Type::BlockPointer:
2404 case Type::MemberPointer:
2405 return type;
2406
2407 // These types can be variably-modified. All these modifications
2408 // preserve structure except as noted by comments.
2409 // TODO: if we ever care about optimizing VLAs, there are no-op
2410 // optimizations available here.
2411 case Type::Pointer:
2412 result = getPointerType(getVariableArrayDecayedType(
2413 cast<PointerType>(ty)->getPointeeType()));
2414 break;
2415
2416 case Type::LValueReference: {
2417 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2418 result = getLValueReferenceType(
2419 getVariableArrayDecayedType(lv->getPointeeType()),
2420 lv->isSpelledAsLValue());
2421 break;
2422 }
2423
2424 case Type::RValueReference: {
2425 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2426 result = getRValueReferenceType(
2427 getVariableArrayDecayedType(lv->getPointeeType()));
2428 break;
2429 }
2430
Eli Friedmanb001de72011-10-06 23:00:33 +00002431 case Type::Atomic: {
2432 const AtomicType *at = cast<AtomicType>(ty);
2433 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2434 break;
2435 }
2436
John McCallce889032011-01-18 08:40:38 +00002437 case Type::ConstantArray: {
2438 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2439 result = getConstantArrayType(
2440 getVariableArrayDecayedType(cat->getElementType()),
2441 cat->getSize(),
2442 cat->getSizeModifier(),
2443 cat->getIndexTypeCVRQualifiers());
2444 break;
2445 }
2446
2447 case Type::DependentSizedArray: {
2448 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2449 result = getDependentSizedArrayType(
2450 getVariableArrayDecayedType(dat->getElementType()),
2451 dat->getSizeExpr(),
2452 dat->getSizeModifier(),
2453 dat->getIndexTypeCVRQualifiers(),
2454 dat->getBracketsRange());
2455 break;
2456 }
2457
2458 // Turn incomplete types into [*] types.
2459 case Type::IncompleteArray: {
2460 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2461 result = getVariableArrayType(
2462 getVariableArrayDecayedType(iat->getElementType()),
2463 /*size*/ 0,
2464 ArrayType::Normal,
2465 iat->getIndexTypeCVRQualifiers(),
2466 SourceRange());
2467 break;
2468 }
2469
2470 // Turn VLA types into [*] types.
2471 case Type::VariableArray: {
2472 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2473 result = getVariableArrayType(
2474 getVariableArrayDecayedType(vat->getElementType()),
2475 /*size*/ 0,
2476 ArrayType::Star,
2477 vat->getIndexTypeCVRQualifiers(),
2478 vat->getBracketsRange());
2479 break;
2480 }
2481 }
2482
2483 // Apply the top-level qualifiers from the original.
John McCall200fa532012-02-08 00:46:36 +00002484 return getQualifiedType(result, split.Quals);
John McCallce889032011-01-18 08:40:38 +00002485}
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002486
Steve Naroffbdbf7b02007-08-30 18:14:25 +00002487/// getVariableArrayType - Returns a non-unique reference to the type for a
2488/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002489QualType ASTContext::getVariableArrayType(QualType EltTy,
2490 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00002491 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002492 unsigned IndexTypeQuals,
Jay Foad4ba2a172011-01-12 09:06:06 +00002493 SourceRange Brackets) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00002494 // Since we don't unique expressions, it isn't possible to unique VLA's
2495 // that have an expression provided for their size.
John McCall3b657512011-01-19 10:06:00 +00002496 QualType Canon;
Douglas Gregor715e9c82010-05-23 16:10:32 +00002497
John McCall3b657512011-01-19 10:06:00 +00002498 // Be sure to pull qualifiers off the element type.
2499 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2500 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall200fa532012-02-08 00:46:36 +00002501 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002502 IndexTypeQuals, Brackets);
John McCall200fa532012-02-08 00:46:36 +00002503 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor715e9c82010-05-23 16:10:32 +00002504 }
2505
John McCall6b304a02009-09-24 23:30:46 +00002506 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00002507 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002508
2509 VariableArrayTypes.push_back(New);
2510 Types.push_back(New);
2511 return QualType(New, 0);
2512}
2513
Douglas Gregor898574e2008-12-05 23:32:09 +00002514/// getDependentSizedArrayType - Returns a non-unique reference to
2515/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00002516/// type.
John McCall3b657512011-01-19 10:06:00 +00002517QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2518 Expr *numElements,
Douglas Gregor898574e2008-12-05 23:32:09 +00002519 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00002520 unsigned elementTypeQuals,
2521 SourceRange brackets) const {
2522 assert((!numElements || numElements->isTypeDependent() ||
2523 numElements->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00002524 "Size must be type- or value-dependent!");
2525
John McCall3b657512011-01-19 10:06:00 +00002526 // Dependently-sized array types that do not have a specified number
2527 // of elements will have their sizes deduced from a dependent
2528 // initializer. We do no canonicalization here at all, which is okay
2529 // because they can't be used in most locations.
2530 if (!numElements) {
2531 DependentSizedArrayType *newType
2532 = new (*this, TypeAlignment)
2533 DependentSizedArrayType(*this, elementType, QualType(),
2534 numElements, ASM, elementTypeQuals,
2535 brackets);
2536 Types.push_back(newType);
2537 return QualType(newType, 0);
2538 }
2539
2540 // Otherwise, we actually build a new type every time, but we
2541 // also build a canonical type.
2542
2543 SplitQualType canonElementType = getCanonicalType(elementType).split();
2544
2545 void *insertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00002546 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00002547 DependentSizedArrayType::Profile(ID, *this,
John McCall200fa532012-02-08 00:46:36 +00002548 QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002549 ASM, elementTypeQuals, numElements);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002550
John McCall3b657512011-01-19 10:06:00 +00002551 // Look for an existing type with these properties.
2552 DependentSizedArrayType *canonTy =
2553 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002554
John McCall3b657512011-01-19 10:06:00 +00002555 // If we don't have one, build one.
2556 if (!canonTy) {
2557 canonTy = new (*this, TypeAlignment)
John McCall200fa532012-02-08 00:46:36 +00002558 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002559 QualType(), numElements, ASM, elementTypeQuals,
2560 brackets);
2561 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2562 Types.push_back(canonTy);
Douglas Gregorcb78d882009-11-19 18:03:26 +00002563 }
2564
John McCall3b657512011-01-19 10:06:00 +00002565 // Apply qualifiers from the element type to the array.
2566 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall200fa532012-02-08 00:46:36 +00002567 canonElementType.Quals);
Mike Stump1eb44332009-09-09 15:08:12 +00002568
John McCall3b657512011-01-19 10:06:00 +00002569 // If we didn't need extra canonicalization for the element type,
2570 // then just use that as our result.
John McCall200fa532012-02-08 00:46:36 +00002571 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall3b657512011-01-19 10:06:00 +00002572 return canon;
2573
2574 // Otherwise, we need to build a type which follows the spelling
2575 // of the element type.
2576 DependentSizedArrayType *sugaredType
2577 = new (*this, TypeAlignment)
2578 DependentSizedArrayType(*this, elementType, canon, numElements,
2579 ASM, elementTypeQuals, brackets);
2580 Types.push_back(sugaredType);
2581 return QualType(sugaredType, 0);
Douglas Gregor898574e2008-12-05 23:32:09 +00002582}
2583
John McCall3b657512011-01-19 10:06:00 +00002584QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanc5773c42008-02-15 18:16:39 +00002585 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00002586 unsigned elementTypeQuals) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00002587 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00002588 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002589
John McCall3b657512011-01-19 10:06:00 +00002590 void *insertPos = 0;
2591 if (IncompleteArrayType *iat =
2592 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2593 return QualType(iat, 0);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002594
2595 // If the element type isn't canonical, this won't be a canonical type
John McCall3b657512011-01-19 10:06:00 +00002596 // either, so fill in the canonical type field. We also have to pull
2597 // qualifiers off the element type.
2598 QualType canon;
Eli Friedmanc5773c42008-02-15 18:16:39 +00002599
John McCall3b657512011-01-19 10:06:00 +00002600 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2601 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall200fa532012-02-08 00:46:36 +00002602 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall3b657512011-01-19 10:06:00 +00002603 ASM, elementTypeQuals);
John McCall200fa532012-02-08 00:46:36 +00002604 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002605
2606 // Get the new insert position for the node we care about.
John McCall3b657512011-01-19 10:06:00 +00002607 IncompleteArrayType *existing =
2608 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2609 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00002610 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00002611
John McCall3b657512011-01-19 10:06:00 +00002612 IncompleteArrayType *newType = new (*this, TypeAlignment)
2613 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00002614
John McCall3b657512011-01-19 10:06:00 +00002615 IncompleteArrayTypes.InsertNode(newType, insertPos);
2616 Types.push_back(newType);
2617 return QualType(newType, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00002618}
2619
Steve Naroff73322922007-07-18 18:00:27 +00002620/// getVectorType - Return the unique reference to a vector type of
2621/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00002622QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad4ba2a172011-01-12 09:06:06 +00002623 VectorType::VectorKind VecKind) const {
John McCall3b657512011-01-19 10:06:00 +00002624 assert(vecType->isBuiltinType());
Mike Stump1eb44332009-09-09 15:08:12 +00002625
Reid Spencer5f016e22007-07-11 17:01:13 +00002626 // Check if we've already instantiated a vector of this type.
2627 llvm::FoldingSetNodeID ID;
Bob Wilsone86d78c2010-11-10 21:56:12 +00002628 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner788b0fd2010-06-23 06:00:24 +00002629
Reid Spencer5f016e22007-07-11 17:01:13 +00002630 void *InsertPos = 0;
2631 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2632 return QualType(VTP, 0);
2633
2634 // If the element type isn't canonical, this won't be a canonical type either,
2635 // so fill in the canonical type field.
2636 QualType Canonical;
Douglas Gregor255210e2010-08-06 10:14:59 +00002637 if (!vecType.isCanonical()) {
Bob Wilson231da7e2010-11-16 00:32:20 +00002638 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump1eb44332009-09-09 15:08:12 +00002639
Reid Spencer5f016e22007-07-11 17:01:13 +00002640 // Get the new insert position for the node we care about.
2641 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002642 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002643 }
John McCall6b304a02009-09-24 23:30:46 +00002644 VectorType *New = new (*this, TypeAlignment)
Bob Wilsone86d78c2010-11-10 21:56:12 +00002645 VectorType(vecType, NumElts, Canonical, VecKind);
Reid Spencer5f016e22007-07-11 17:01:13 +00002646 VectorTypes.InsertNode(New, InsertPos);
2647 Types.push_back(New);
2648 return QualType(New, 0);
2649}
2650
Nate Begeman213541a2008-04-18 23:10:10 +00002651/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00002652/// the specified element type and size. VectorType must be a built-in type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002653QualType
2654ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor4ac01402011-06-15 16:02:29 +00002655 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump1eb44332009-09-09 15:08:12 +00002656
Steve Naroff73322922007-07-18 18:00:27 +00002657 // Check if we've already instantiated a vector of this type.
2658 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00002659 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsone86d78c2010-11-10 21:56:12 +00002660 VectorType::GenericVector);
Steve Naroff73322922007-07-18 18:00:27 +00002661 void *InsertPos = 0;
2662 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2663 return QualType(VTP, 0);
2664
2665 // If the element type isn't canonical, this won't be a canonical type either,
2666 // so fill in the canonical type field.
2667 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002668 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00002669 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00002670
Steve Naroff73322922007-07-18 18:00:27 +00002671 // Get the new insert position for the node we care about.
2672 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002673 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00002674 }
John McCall6b304a02009-09-24 23:30:46 +00002675 ExtVectorType *New = new (*this, TypeAlignment)
2676 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00002677 VectorTypes.InsertNode(New, InsertPos);
2678 Types.push_back(New);
2679 return QualType(New, 0);
2680}
2681
Jay Foad4ba2a172011-01-12 09:06:06 +00002682QualType
2683ASTContext::getDependentSizedExtVectorType(QualType vecType,
2684 Expr *SizeExpr,
2685 SourceLocation AttrLoc) const {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002686 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00002687 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002688 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002689
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002690 void *InsertPos = 0;
2691 DependentSizedExtVectorType *Canon
2692 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2693 DependentSizedExtVectorType *New;
2694 if (Canon) {
2695 // We already have a canonical version of this array type; use it as
2696 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00002697 New = new (*this, TypeAlignment)
2698 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2699 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002700 } else {
2701 QualType CanonVecTy = getCanonicalType(vecType);
2702 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00002703 New = new (*this, TypeAlignment)
2704 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2705 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002706
2707 DependentSizedExtVectorType *CanonCheck
2708 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2709 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2710 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002711 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2712 } else {
2713 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2714 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00002715 New = new (*this, TypeAlignment)
2716 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002717 }
2718 }
Mike Stump1eb44332009-09-09 15:08:12 +00002719
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00002720 Types.push_back(New);
2721 return QualType(New, 0);
2722}
2723
Douglas Gregor72564e72009-02-26 23:50:07 +00002724/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00002725///
Jay Foad4ba2a172011-01-12 09:06:06 +00002726QualType
2727ASTContext::getFunctionNoProtoType(QualType ResultTy,
2728 const FunctionType::ExtInfo &Info) const {
Roman Divackycfe9af22011-03-01 17:40:53 +00002729 const CallingConv DefaultCC = Info.getCC();
2730 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2731 CC_X86StdCall : DefaultCC;
Reid Spencer5f016e22007-07-11 17:01:13 +00002732 // Unique functions, to guarantee there is only one function of a particular
2733 // structure.
2734 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00002735 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00002736
Reid Spencer5f016e22007-07-11 17:01:13 +00002737 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002738 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00002739 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002740 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002741
Reid Spencer5f016e22007-07-11 17:01:13 +00002742 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00002743 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00002744 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00002745 Canonical =
2746 getFunctionNoProtoType(getCanonicalType(ResultTy),
2747 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump1eb44332009-09-09 15:08:12 +00002748
Reid Spencer5f016e22007-07-11 17:01:13 +00002749 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002750 FunctionNoProtoType *NewIP =
2751 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002752 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002753 }
Mike Stump1eb44332009-09-09 15:08:12 +00002754
Roman Divackycfe9af22011-03-01 17:40:53 +00002755 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall6b304a02009-09-24 23:30:46 +00002756 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divackycfe9af22011-03-01 17:40:53 +00002757 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00002758 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00002759 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002760 return QualType(New, 0);
2761}
2762
Douglas Gregor02dd7982013-01-17 23:36:45 +00002763/// \brief Determine whether \p T is canonical as the result type of a function.
2764static bool isCanonicalResultType(QualType T) {
2765 return T.isCanonical() &&
2766 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2767 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2768}
2769
Reid Spencer5f016e22007-07-11 17:01:13 +00002770/// getFunctionType - Return a normal function type with a typed argument
2771/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad4ba2a172011-01-12 09:06:06 +00002772QualType
Jordan Rosebea522f2013-03-08 21:51:21 +00002773ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad4ba2a172011-01-12 09:06:06 +00002774 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rosebea522f2013-03-08 21:51:21 +00002775 size_t NumArgs = ArgArray.size();
2776
Reid Spencer5f016e22007-07-11 17:01:13 +00002777 // Unique functions, to guarantee there is only one function of a particular
2778 // structure.
2779 llvm::FoldingSetNodeID ID;
Jordan Rosebea522f2013-03-08 21:51:21 +00002780 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
2781 *this);
Reid Spencer5f016e22007-07-11 17:01:13 +00002782
2783 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002784 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00002785 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002786 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00002787
2788 // Determine whether the type being created is already canonical or not.
Richard Smitheefb3d52012-02-10 09:58:53 +00002789 bool isCanonical =
Douglas Gregor02dd7982013-01-17 23:36:45 +00002790 EPI.ExceptionSpecType == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smitheefb3d52012-02-10 09:58:53 +00002791 !EPI.HasTrailingReturn;
Reid Spencer5f016e22007-07-11 17:01:13 +00002792 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002793 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00002794 isCanonical = false;
2795
Roman Divackycfe9af22011-03-01 17:40:53 +00002796 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2797 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2798 CC_X86StdCall : DefaultCC;
John McCalle23cf432010-12-14 08:05:40 +00002799
Reid Spencer5f016e22007-07-11 17:01:13 +00002800 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00002801 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002802 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00002803 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002804 SmallVector<QualType, 16> CanonicalArgs;
Reid Spencer5f016e22007-07-11 17:01:13 +00002805 CanonicalArgs.reserve(NumArgs);
2806 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002807 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00002808
John McCalle23cf432010-12-14 08:05:40 +00002809 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smitheefb3d52012-02-10 09:58:53 +00002810 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002811 CanonicalEPI.ExceptionSpecType = EST_None;
2812 CanonicalEPI.NumExceptions = 0;
John McCalle23cf432010-12-14 08:05:40 +00002813 CanonicalEPI.ExtInfo
2814 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2815
Douglas Gregor02dd7982013-01-17 23:36:45 +00002816 // Result types do not have ARC lifetime qualifiers.
2817 QualType CanResultTy = getCanonicalType(ResultTy);
2818 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2819 Qualifiers Qs = CanResultTy.getQualifiers();
2820 Qs.removeObjCLifetime();
2821 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2822 }
2823
Jordan Rosebea522f2013-03-08 21:51:21 +00002824 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl465226e2009-05-27 22:11:52 +00002825
Reid Spencer5f016e22007-07-11 17:01:13 +00002826 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002827 FunctionProtoType *NewIP =
2828 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002829 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002830 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002831
John McCallf85e1932011-06-15 23:02:42 +00002832 // FunctionProtoType objects are allocated with extra bytes after
2833 // them for three variable size arrays at the end:
2834 // - parameter types
2835 // - exception types
2836 // - consumed-arguments flags
2837 // Instead of the exception types, there could be a noexcept
Richard Smithb9d0b762012-07-27 04:22:15 +00002838 // expression, or information used to resolve the exception
2839 // specification.
John McCalle23cf432010-12-14 08:05:40 +00002840 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redl60618fa2011-03-12 11:50:43 +00002841 NumArgs * sizeof(QualType);
Richard Smithb9d0b762012-07-27 04:22:15 +00002842 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redl60618fa2011-03-12 11:50:43 +00002843 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithb9d0b762012-07-27 04:22:15 +00002844 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002845 Size += sizeof(Expr*);
Richard Smithe6975e92012-04-17 00:58:00 +00002846 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smith13bffc52012-04-19 00:08:28 +00002847 Size += 2 * sizeof(FunctionDecl*);
Richard Smithb9d0b762012-07-27 04:22:15 +00002848 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2849 Size += sizeof(FunctionDecl*);
Sebastian Redl60618fa2011-03-12 11:50:43 +00002850 }
John McCallf85e1932011-06-15 23:02:42 +00002851 if (EPI.ConsumedArguments)
2852 Size += NumArgs * sizeof(bool);
2853
John McCalle23cf432010-12-14 08:05:40 +00002854 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divackycfe9af22011-03-01 17:40:53 +00002855 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2856 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Jordan Rosebea522f2013-03-08 21:51:21 +00002857 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00002858 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00002859 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002860 return QualType(FTP, 0);
2861}
2862
John McCall3cb0ebd2010-03-10 03:28:59 +00002863#ifndef NDEBUG
2864static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2865 if (!isa<CXXRecordDecl>(D)) return false;
2866 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2867 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2868 return true;
2869 if (RD->getDescribedClassTemplate() &&
2870 !isa<ClassTemplateSpecializationDecl>(RD))
2871 return true;
2872 return false;
2873}
2874#endif
2875
2876/// getInjectedClassNameType - Return the unique reference to the
2877/// injected class name type for the specified templated declaration.
2878QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00002879 QualType TST) const {
John McCall3cb0ebd2010-03-10 03:28:59 +00002880 assert(NeedsInjectedClassNameType(Decl));
2881 if (Decl->TypeForDecl) {
2882 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregoref96ee02012-01-14 16:38:05 +00002883 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00002884 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2885 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2886 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2887 } else {
John McCallf4c73712011-01-19 06:33:43 +00002888 Type *newType =
John McCall31f17ec2010-04-27 00:57:59 +00002889 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCallf4c73712011-01-19 06:33:43 +00002890 Decl->TypeForDecl = newType;
2891 Types.push_back(newType);
John McCall3cb0ebd2010-03-10 03:28:59 +00002892 }
2893 return QualType(Decl->TypeForDecl, 0);
2894}
2895
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002896/// getTypeDeclType - Return the unique reference to the type for the
2897/// specified type declaration.
Jay Foad4ba2a172011-01-12 09:06:06 +00002898QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00002899 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00002900 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00002901
Richard Smith162e1c12011-04-15 14:24:37 +00002902 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002903 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00002904
John McCallbecb8d52010-03-10 06:48:02 +00002905 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2906 "Template type parameter types are always available.");
2907
John McCall19c85762010-02-16 03:57:14 +00002908 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002909 assert(!Record->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002910 "struct/union has previous declaration");
2911 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002912 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00002913 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00002914 assert(!Enum->getPreviousDecl() &&
John McCallbecb8d52010-03-10 06:48:02 +00002915 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002916 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00002917 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00002918 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCallf4c73712011-01-19 06:33:43 +00002919 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2920 Decl->TypeForDecl = newType;
2921 Types.push_back(newType);
Mike Stump9fdbab32009-07-31 02:02:20 +00002922 } else
John McCallbecb8d52010-03-10 06:48:02 +00002923 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002924
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002925 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002926}
2927
Reid Spencer5f016e22007-07-11 17:01:13 +00002928/// getTypedefType - Return the unique reference to the type for the
Richard Smith162e1c12011-04-15 14:24:37 +00002929/// specified typedef name decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002930QualType
Richard Smith162e1c12011-04-15 14:24:37 +00002931ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2932 QualType Canonical) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002933 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002934
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002935 if (Canonical.isNull())
2936 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCallf4c73712011-01-19 06:33:43 +00002937 TypedefType *newType = new(*this, TypeAlignment)
John McCall6b304a02009-09-24 23:30:46 +00002938 TypedefType(Type::Typedef, Decl, Canonical);
John McCallf4c73712011-01-19 06:33:43 +00002939 Decl->TypeForDecl = newType;
2940 Types.push_back(newType);
2941 return QualType(newType, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002942}
2943
Jay Foad4ba2a172011-01-12 09:06:06 +00002944QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002945 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2946
Douglas Gregoref96ee02012-01-14 16:38:05 +00002947 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002948 if (PrevDecl->TypeForDecl)
2949 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2950
John McCallf4c73712011-01-19 06:33:43 +00002951 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2952 Decl->TypeForDecl = newType;
2953 Types.push_back(newType);
2954 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002955}
2956
Jay Foad4ba2a172011-01-12 09:06:06 +00002957QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002958 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2959
Douglas Gregoref96ee02012-01-14 16:38:05 +00002960 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002961 if (PrevDecl->TypeForDecl)
2962 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2963
John McCallf4c73712011-01-19 06:33:43 +00002964 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2965 Decl->TypeForDecl = newType;
2966 Types.push_back(newType);
2967 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002968}
2969
John McCall9d156a72011-01-06 01:58:22 +00002970QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2971 QualType modifiedType,
2972 QualType equivalentType) {
2973 llvm::FoldingSetNodeID id;
2974 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2975
2976 void *insertPos = 0;
2977 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2978 if (type) return QualType(type, 0);
2979
2980 QualType canon = getCanonicalType(equivalentType);
2981 type = new (*this, TypeAlignment)
2982 AttributedType(canon, attrKind, modifiedType, equivalentType);
2983
2984 Types.push_back(type);
2985 AttributedTypes.InsertNode(type, insertPos);
2986
2987 return QualType(type, 0);
2988}
2989
2990
John McCall49a832b2009-10-18 09:09:24 +00002991/// \brief Retrieve a substitution-result type.
2992QualType
2993ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad4ba2a172011-01-12 09:06:06 +00002994 QualType Replacement) const {
John McCall467b27b2009-10-22 20:10:53 +00002995 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00002996 && "replacement types must always be canonical");
2997
2998 llvm::FoldingSetNodeID ID;
2999 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
3000 void *InsertPos = 0;
3001 SubstTemplateTypeParmType *SubstParm
3002 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3003
3004 if (!SubstParm) {
3005 SubstParm = new (*this, TypeAlignment)
3006 SubstTemplateTypeParmType(Parm, Replacement);
3007 Types.push_back(SubstParm);
3008 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3009 }
3010
3011 return QualType(SubstParm, 0);
3012}
3013
Douglas Gregorc3069d62011-01-14 02:55:32 +00003014/// \brief Retrieve a
3015QualType ASTContext::getSubstTemplateTypeParmPackType(
3016 const TemplateTypeParmType *Parm,
3017 const TemplateArgument &ArgPack) {
3018#ifndef NDEBUG
3019 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
3020 PEnd = ArgPack.pack_end();
3021 P != PEnd; ++P) {
3022 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3023 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
3024 }
3025#endif
3026
3027 llvm::FoldingSetNodeID ID;
3028 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
3029 void *InsertPos = 0;
3030 if (SubstTemplateTypeParmPackType *SubstParm
3031 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3032 return QualType(SubstParm, 0);
3033
3034 QualType Canon;
3035 if (!Parm->isCanonicalUnqualified()) {
3036 Canon = getCanonicalType(QualType(Parm, 0));
3037 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3038 ArgPack);
3039 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3040 }
3041
3042 SubstTemplateTypeParmPackType *SubstParm
3043 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3044 ArgPack);
3045 Types.push_back(SubstParm);
3046 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3047 return QualType(SubstParm, 0);
3048}
3049
Douglas Gregorfab9d672009-02-05 23:33:38 +00003050/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00003051/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003052/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00003053QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003054 bool ParameterPack,
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003055 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregorfab9d672009-02-05 23:33:38 +00003056 llvm::FoldingSetNodeID ID;
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003057 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregorfab9d672009-02-05 23:33:38 +00003058 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003059 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00003060 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3061
3062 if (TypeParm)
3063 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00003064
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003065 if (TTPDecl) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003066 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003067 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003068
3069 TemplateTypeParmType *TypeCheck
3070 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3071 assert(!TypeCheck && "Template type parameter canonical type broken");
3072 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00003073 } else
John McCall6b304a02009-09-24 23:30:46 +00003074 TypeParm = new (*this, TypeAlignment)
3075 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00003076
3077 Types.push_back(TypeParm);
3078 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3079
3080 return QualType(TypeParm, 0);
3081}
3082
John McCall3cb0ebd2010-03-10 03:28:59 +00003083TypeSourceInfo *
3084ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3085 SourceLocation NameLoc,
3086 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003087 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003088 assert(!Name.getAsDependentTemplateName() &&
3089 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00003090 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCall3cb0ebd2010-03-10 03:28:59 +00003091
3092 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie39e6ab42013-02-18 22:06:02 +00003093 TemplateSpecializationTypeLoc TL =
3094 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara55d23c92012-02-06 14:41:24 +00003095 TL.setTemplateKeywordLoc(SourceLocation());
John McCall3cb0ebd2010-03-10 03:28:59 +00003096 TL.setTemplateNameLoc(NameLoc);
3097 TL.setLAngleLoc(Args.getLAngleLoc());
3098 TL.setRAngleLoc(Args.getRAngleLoc());
3099 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3100 TL.setArgLocInfo(i, Args[i].getLocInfo());
3101 return DI;
3102}
3103
Mike Stump1eb44332009-09-09 15:08:12 +00003104QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00003105ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00003106 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003107 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003108 assert(!Template.getAsDependentTemplateName() &&
3109 "No dependent template names here!");
3110
John McCalld5532b62009-11-23 01:53:49 +00003111 unsigned NumArgs = Args.size();
3112
Chris Lattner5f9e2722011-07-23 10:55:15 +00003113 SmallVector<TemplateArgument, 4> ArgVec;
John McCall833ca992009-10-29 08:12:44 +00003114 ArgVec.reserve(NumArgs);
3115 for (unsigned i = 0; i != NumArgs; ++i)
3116 ArgVec.push_back(Args[i].getArgument());
3117
John McCall31f17ec2010-04-27 00:57:59 +00003118 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003119 Underlying);
John McCall833ca992009-10-29 08:12:44 +00003120}
3121
Douglas Gregorb70126a2012-02-03 17:16:23 +00003122#ifndef NDEBUG
3123static bool hasAnyPackExpansions(const TemplateArgument *Args,
3124 unsigned NumArgs) {
3125 for (unsigned I = 0; I != NumArgs; ++I)
3126 if (Args[I].isPackExpansion())
3127 return true;
3128
3129 return true;
3130}
3131#endif
3132
John McCall833ca992009-10-29 08:12:44 +00003133QualType
3134ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003135 const TemplateArgument *Args,
3136 unsigned NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003137 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003138 assert(!Template.getAsDependentTemplateName() &&
3139 "No dependent template names here!");
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00003140 // Look through qualified template names.
3141 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3142 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003143
Douglas Gregorb70126a2012-02-03 17:16:23 +00003144 bool IsTypeAlias =
Richard Smith3e4c6c42011-05-05 21:57:07 +00003145 Template.getAsTemplateDecl() &&
3146 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00003147 QualType CanonType;
3148 if (!Underlying.isNull())
3149 CanonType = getCanonicalType(Underlying);
3150 else {
Douglas Gregorb70126a2012-02-03 17:16:23 +00003151 // We can get here with an alias template when the specialization contains
3152 // a pack expansion that does not match up with a parameter pack.
3153 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3154 "Caller must compute aliased type");
3155 IsTypeAlias = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00003156 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3157 NumArgs);
3158 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00003159
Douglas Gregor1275ae02009-07-28 23:00:59 +00003160 // Allocate the (non-canonical) template specialization type, but don't
3161 // try to unique it: these types typically have location information that
3162 // we don't unique and don't want to lose.
Richard Smith3e4c6c42011-05-05 21:57:07 +00003163 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3164 sizeof(TemplateArgument) * NumArgs +
Douglas Gregorb70126a2012-02-03 17:16:23 +00003165 (IsTypeAlias? sizeof(QualType) : 0),
John McCall6b304a02009-09-24 23:30:46 +00003166 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00003167 TemplateSpecializationType *Spec
Douglas Gregorb70126a2012-02-03 17:16:23 +00003168 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3169 IsTypeAlias ? Underlying : QualType());
Mike Stump1eb44332009-09-09 15:08:12 +00003170
Douglas Gregor55f6b142009-02-09 18:46:07 +00003171 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00003172 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00003173}
3174
Mike Stump1eb44332009-09-09 15:08:12 +00003175QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003176ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3177 const TemplateArgument *Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00003178 unsigned NumArgs) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003179 assert(!Template.getAsDependentTemplateName() &&
3180 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00003181
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00003182 // Look through qualified template names.
3183 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3184 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00003185
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003186 // Build the canonical template specialization type.
3187 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003188 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003189 CanonArgs.reserve(NumArgs);
3190 for (unsigned I = 0; I != NumArgs; ++I)
3191 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3192
3193 // Determine whether this canonical template specialization type already
3194 // exists.
3195 llvm::FoldingSetNodeID ID;
3196 TemplateSpecializationType::Profile(ID, CanonTemplate,
3197 CanonArgs.data(), NumArgs, *this);
3198
3199 void *InsertPos = 0;
3200 TemplateSpecializationType *Spec
3201 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3202
3203 if (!Spec) {
3204 // Allocate a new canonical template specialization type.
3205 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3206 sizeof(TemplateArgument) * NumArgs),
3207 TypeAlignment);
3208 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3209 CanonArgs.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00003210 QualType(), QualType());
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00003211 Types.push_back(Spec);
3212 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3213 }
3214
3215 assert(Spec->isDependentType() &&
3216 "Non-dependent template-id type must have a canonical type");
3217 return QualType(Spec, 0);
3218}
3219
3220QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003221ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3222 NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00003223 QualType NamedType) const {
Douglas Gregore4e5b052009-03-19 00:18:19 +00003224 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003225 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003226
3227 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003228 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003229 if (T)
3230 return QualType(T, 0);
3231
Douglas Gregor789b1f62010-02-04 18:10:26 +00003232 QualType Canon = NamedType;
3233 if (!Canon.isCanonical()) {
3234 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003235 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3236 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00003237 (void)CheckT;
3238 }
3239
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003240 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003241 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003242 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00003243 return QualType(T, 0);
3244}
3245
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003246QualType
Jay Foad4ba2a172011-01-12 09:06:06 +00003247ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003248 llvm::FoldingSetNodeID ID;
3249 ParenType::Profile(ID, InnerType);
3250
3251 void *InsertPos = 0;
3252 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3253 if (T)
3254 return QualType(T, 0);
3255
3256 QualType Canon = InnerType;
3257 if (!Canon.isCanonical()) {
3258 Canon = getCanonicalType(InnerType);
3259 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3260 assert(!CheckT && "Paren canonical type broken");
3261 (void)CheckT;
3262 }
3263
3264 T = new (*this) ParenType(InnerType, Canon);
3265 Types.push_back(T);
3266 ParenTypes.InsertNode(T, InsertPos);
3267 return QualType(T, 0);
3268}
3269
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003270QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3271 NestedNameSpecifier *NNS,
3272 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00003273 QualType Canon) const {
Douglas Gregord57959a2009-03-27 23:10:48 +00003274 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
3275
3276 if (Canon.isNull()) {
3277 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003278 ElaboratedTypeKeyword CanonKeyword = Keyword;
3279 if (Keyword == ETK_None)
3280 CanonKeyword = ETK_Typename;
3281
3282 if (CanonNNS != NNS || CanonKeyword != Keyword)
3283 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00003284 }
3285
3286 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003287 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00003288
3289 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00003290 DependentNameType *T
3291 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00003292 if (T)
3293 return QualType(T, 0);
3294
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003295 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00003296 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00003297 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00003298 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00003299}
3300
Mike Stump1eb44332009-09-09 15:08:12 +00003301QualType
John McCall33500952010-06-11 00:33:02 +00003302ASTContext::getDependentTemplateSpecializationType(
3303 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00003304 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00003305 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00003306 const TemplateArgumentListInfo &Args) const {
John McCall33500952010-06-11 00:33:02 +00003307 // TODO: avoid this copy
Chris Lattner5f9e2722011-07-23 10:55:15 +00003308 SmallVector<TemplateArgument, 16> ArgCopy;
John McCall33500952010-06-11 00:33:02 +00003309 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3310 ArgCopy.push_back(Args[I].getArgument());
3311 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3312 ArgCopy.size(),
3313 ArgCopy.data());
3314}
3315
3316QualType
3317ASTContext::getDependentTemplateSpecializationType(
3318 ElaboratedTypeKeyword Keyword,
3319 NestedNameSpecifier *NNS,
3320 const IdentifierInfo *Name,
3321 unsigned NumArgs,
Jay Foad4ba2a172011-01-12 09:06:06 +00003322 const TemplateArgument *Args) const {
Douglas Gregoraa2187d2011-02-28 00:04:36 +00003323 assert((!NNS || NNS->isDependent()) &&
3324 "nested-name-specifier must be dependent");
Douglas Gregor17343172009-04-01 00:28:59 +00003325
Douglas Gregor789b1f62010-02-04 18:10:26 +00003326 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00003327 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3328 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003329
3330 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00003331 DependentTemplateSpecializationType *T
3332 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003333 if (T)
3334 return QualType(T, 0);
3335
John McCall33500952010-06-11 00:33:02 +00003336 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003337
John McCall33500952010-06-11 00:33:02 +00003338 ElaboratedTypeKeyword CanonKeyword = Keyword;
3339 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3340
3341 bool AnyNonCanonArgs = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003342 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCall33500952010-06-11 00:33:02 +00003343 for (unsigned I = 0; I != NumArgs; ++I) {
3344 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3345 if (!CanonArgs[I].structurallyEquals(Args[I]))
3346 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00003347 }
3348
John McCall33500952010-06-11 00:33:02 +00003349 QualType Canon;
3350 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3351 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3352 Name, NumArgs,
3353 CanonArgs.data());
3354
3355 // Find the insert position again.
3356 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3357 }
3358
3359 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3360 sizeof(TemplateArgument) * NumArgs),
3361 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00003362 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00003363 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00003364 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00003365 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00003366 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00003367}
3368
Douglas Gregorcded4f62011-01-14 17:04:44 +00003369QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikiedc84cd52013-02-20 22:23:23 +00003370 Optional<unsigned> NumExpansions) {
Douglas Gregor7536dd52010-12-20 02:24:11 +00003371 llvm::FoldingSetNodeID ID;
Douglas Gregorcded4f62011-01-14 17:04:44 +00003372 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003373
3374 assert(Pattern->containsUnexpandedParameterPack() &&
3375 "Pack expansions must expand one or more parameter packs");
3376 void *InsertPos = 0;
3377 PackExpansionType *T
3378 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3379 if (T)
3380 return QualType(T, 0);
3381
3382 QualType Canon;
3383 if (!Pattern.isCanonical()) {
Richard Smithd8672ef2012-07-16 00:20:35 +00003384 Canon = getCanonicalType(Pattern);
3385 // The canonical type might not contain an unexpanded parameter pack, if it
3386 // contains an alias template specialization which ignores one of its
3387 // parameters.
3388 if (Canon->containsUnexpandedParameterPack()) {
3389 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003390
Richard Smithd8672ef2012-07-16 00:20:35 +00003391 // Find the insert position again, in case we inserted an element into
3392 // PackExpansionTypes and invalidated our insert position.
3393 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3394 }
Douglas Gregor7536dd52010-12-20 02:24:11 +00003395 }
3396
Douglas Gregorcded4f62011-01-14 17:04:44 +00003397 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00003398 Types.push_back(T);
3399 PackExpansionTypes.InsertNode(T, InsertPos);
3400 return QualType(T, 0);
3401}
3402
Chris Lattner88cb27a2008-04-07 04:56:42 +00003403/// CmpProtocolNames - Comparison predicate for sorting protocols
3404/// alphabetically.
3405static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3406 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003407 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00003408}
3409
John McCallc12c5bb2010-05-15 11:32:37 +00003410static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00003411 unsigned NumProtocols) {
3412 if (NumProtocols == 0) return true;
3413
Douglas Gregor61cc2962012-01-02 02:00:30 +00003414 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3415 return false;
3416
John McCall54e14c42009-10-22 22:37:11 +00003417 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregor61cc2962012-01-02 02:00:30 +00003418 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3419 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCall54e14c42009-10-22 22:37:11 +00003420 return false;
3421 return true;
3422}
3423
3424static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00003425 unsigned &NumProtocols) {
3426 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00003427
Chris Lattner88cb27a2008-04-07 04:56:42 +00003428 // Sort protocols, keyed by name.
3429 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3430
Douglas Gregor61cc2962012-01-02 02:00:30 +00003431 // Canonicalize.
3432 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3433 Protocols[I] = Protocols[I]->getCanonicalDecl();
3434
Chris Lattner88cb27a2008-04-07 04:56:42 +00003435 // Remove duplicates.
3436 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3437 NumProtocols = ProtocolsEnd-Protocols;
3438}
3439
John McCallc12c5bb2010-05-15 11:32:37 +00003440QualType ASTContext::getObjCObjectType(QualType BaseType,
3441 ObjCProtocolDecl * const *Protocols,
Jay Foad4ba2a172011-01-12 09:06:06 +00003442 unsigned NumProtocols) const {
John McCallc12c5bb2010-05-15 11:32:37 +00003443 // If the base type is an interface and there aren't any protocols
3444 // to add, then the interface type will do just fine.
3445 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3446 return BaseType;
3447
3448 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003449 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00003450 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003451 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00003452 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3453 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003454
John McCallc12c5bb2010-05-15 11:32:37 +00003455 // Build the canonical type, which has the canonical base type and
3456 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00003457 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00003458 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3459 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3460 if (!ProtocolsSorted) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003461 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer02379412010-04-27 17:12:11 +00003462 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00003463 unsigned UniqueCount = NumProtocols;
3464
John McCall54e14c42009-10-22 22:37:11 +00003465 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00003466 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3467 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00003468 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00003469 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3470 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00003471 }
3472
3473 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00003474 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3475 }
3476
3477 unsigned Size = sizeof(ObjCObjectTypeImpl);
3478 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3479 void *Mem = Allocate(Size, TypeAlignment);
3480 ObjCObjectTypeImpl *T =
3481 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3482
3483 Types.push_back(T);
3484 ObjCObjectTypes.InsertNode(T, InsertPos);
3485 return QualType(T, 0);
3486}
3487
3488/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3489/// the given object type.
Jay Foad4ba2a172011-01-12 09:06:06 +00003490QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCallc12c5bb2010-05-15 11:32:37 +00003491 llvm::FoldingSetNodeID ID;
3492 ObjCObjectPointerType::Profile(ID, ObjectT);
3493
3494 void *InsertPos = 0;
3495 if (ObjCObjectPointerType *QT =
3496 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3497 return QualType(QT, 0);
3498
3499 // Find the canonical object type.
3500 QualType Canonical;
3501 if (!ObjectT.isCanonical()) {
3502 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3503
3504 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00003505 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3506 }
3507
Douglas Gregorfd6a0882010-02-08 22:59:26 +00003508 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00003509 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3510 ObjCObjectPointerType *QType =
3511 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00003512
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003513 Types.push_back(QType);
3514 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00003515 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003516}
Chris Lattner88cb27a2008-04-07 04:56:42 +00003517
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003518/// getObjCInterfaceType - Return the unique reference to the type for the
3519/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregor0af55012011-12-16 03:12:41 +00003520QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3521 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003522 if (Decl->TypeForDecl)
3523 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00003524
Douglas Gregor0af55012011-12-16 03:12:41 +00003525 if (PrevDecl) {
3526 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3527 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3528 return QualType(PrevDecl->TypeForDecl, 0);
3529 }
3530
Douglas Gregor8d2dbbf2011-12-16 16:34:57 +00003531 // Prefer the definition, if there is one.
3532 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3533 Decl = Def;
3534
Douglas Gregordeacbdc2010-08-11 12:19:30 +00003535 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3536 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3537 Decl->TypeForDecl = T;
3538 Types.push_back(T);
3539 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00003540}
3541
Douglas Gregor72564e72009-02-26 23:50:07 +00003542/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3543/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00003544/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00003545/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00003546/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00003547QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003548 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00003549 if (tofExpr->isTypeDependent()) {
3550 llvm::FoldingSetNodeID ID;
3551 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00003552
Douglas Gregorb1975722009-07-30 23:18:24 +00003553 void *InsertPos = 0;
3554 DependentTypeOfExprType *Canon
3555 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3556 if (Canon) {
3557 // We already have a "canonical" version of an identical, dependent
3558 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00003559 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00003560 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00003561 } else {
Douglas Gregorb1975722009-07-30 23:18:24 +00003562 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00003563 Canon
3564 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00003565 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3566 toe = Canon;
3567 }
3568 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003569 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00003570 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00003571 }
Steve Naroff9752f252007-08-01 18:02:17 +00003572 Types.push_back(toe);
3573 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00003574}
3575
Steve Naroff9752f252007-08-01 18:02:17 +00003576/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3577/// TypeOfType AST's. The only motivation to unique these nodes would be
3578/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00003579/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00003580/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00003581QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00003582 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00003583 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00003584 Types.push_back(tot);
3585 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00003586}
3587
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00003588
Anders Carlsson395b4752009-06-24 19:06:50 +00003589/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3590/// DecltypeType AST's. The only motivation to unique these nodes would be
3591/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00003592/// an issue. This doesn't effect the type checker, since it operates
David Blaikie39e02032011-11-06 22:28:03 +00003593/// on canonical types (which are always unique).
Douglas Gregorf8af9822012-02-12 18:42:33 +00003594QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00003595 DecltypeType *dt;
Douglas Gregor561f8122011-07-01 01:22:09 +00003596
3597 // C++0x [temp.type]p2:
3598 // If an expression e involves a template parameter, decltype(e) denotes a
3599 // unique dependent type. Two such decltype-specifiers refer to the same
3600 // type only if their expressions are equivalent (14.5.6.1).
3601 if (e->isInstantiationDependent()) {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003602 llvm::FoldingSetNodeID ID;
3603 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00003604
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003605 void *InsertPos = 0;
3606 DependentDecltypeType *Canon
3607 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3608 if (Canon) {
3609 // We already have a "canonical" version of an equivalent, dependent
3610 // decltype type. Use that as our canonical type.
Richard Smith0d729102012-08-13 20:08:14 +00003611 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003612 QualType((DecltypeType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00003613 } else {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003614 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00003615 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00003616 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3617 dt = Canon;
3618 }
3619 } else {
Douglas Gregorf8af9822012-02-12 18:42:33 +00003620 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3621 getCanonicalType(UnderlyingType));
Douglas Gregordd0257c2009-07-08 00:03:05 +00003622 }
Anders Carlsson395b4752009-06-24 19:06:50 +00003623 Types.push_back(dt);
3624 return QualType(dt, 0);
3625}
3626
Sean Huntca63c202011-05-24 22:41:36 +00003627/// getUnaryTransformationType - We don't unique these, since the memory
3628/// savings are minimal and these are rare.
3629QualType ASTContext::getUnaryTransformType(QualType BaseType,
3630 QualType UnderlyingType,
3631 UnaryTransformType::UTTKind Kind)
3632 const {
3633 UnaryTransformType *Ty =
Douglas Gregor69d97752011-05-25 17:51:54 +00003634 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3635 Kind,
3636 UnderlyingType->isDependentType() ?
Peter Collingbourne12fc4b02012-03-05 16:02:06 +00003637 QualType() : getCanonicalType(UnderlyingType));
Sean Huntca63c202011-05-24 22:41:36 +00003638 Types.push_back(Ty);
3639 return QualType(Ty, 0);
3640}
3641
Richard Smith60e141e2013-05-04 07:00:32 +00003642/// getAutoType - Return the uniqued reference to the 'auto' type which has been
3643/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3644/// canonical deduced-but-dependent 'auto' type.
3645QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
Richard Smithdc7a4f52013-04-30 13:56:41 +00003646 bool IsDependent) const {
Richard Smith60e141e2013-05-04 07:00:32 +00003647 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
3648 return getAutoDeductType();
3649
3650 // Look in the folding set for an existing type.
Richard Smith483b9f32011-02-21 20:05:19 +00003651 void *InsertPos = 0;
Richard Smith60e141e2013-05-04 07:00:32 +00003652 llvm::FoldingSetNodeID ID;
3653 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
3654 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3655 return QualType(AT, 0);
Richard Smith483b9f32011-02-21 20:05:19 +00003656
Richard Smitha2c36462013-04-26 16:15:35 +00003657 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smithdc7a4f52013-04-30 13:56:41 +00003658 IsDecltypeAuto,
3659 IsDependent);
Richard Smith483b9f32011-02-21 20:05:19 +00003660 Types.push_back(AT);
3661 if (InsertPos)
3662 AutoTypes.InsertNode(AT, InsertPos);
3663 return QualType(AT, 0);
Richard Smith34b41d92011-02-20 03:19:35 +00003664}
3665
Eli Friedmanb001de72011-10-06 23:00:33 +00003666/// getAtomicType - Return the uniqued reference to the atomic type for
3667/// the given value type.
3668QualType ASTContext::getAtomicType(QualType T) const {
3669 // Unique pointers, to guarantee there is only one pointer of a particular
3670 // structure.
3671 llvm::FoldingSetNodeID ID;
3672 AtomicType::Profile(ID, T);
3673
3674 void *InsertPos = 0;
3675 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3676 return QualType(AT, 0);
3677
3678 // If the atomic value type isn't canonical, this won't be a canonical type
3679 // either, so fill in the canonical type field.
3680 QualType Canonical;
3681 if (!T.isCanonical()) {
3682 Canonical = getAtomicType(getCanonicalType(T));
3683
3684 // Get the new insert position for the node we care about.
3685 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3686 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3687 }
3688 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3689 Types.push_back(New);
3690 AtomicTypes.InsertNode(New, InsertPos);
3691 return QualType(New, 0);
3692}
3693
Richard Smithad762fc2011-04-14 22:09:26 +00003694/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3695QualType ASTContext::getAutoDeductType() const {
3696 if (AutoDeductTy.isNull())
Richard Smith60e141e2013-05-04 07:00:32 +00003697 AutoDeductTy = QualType(
3698 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
3699 /*dependent*/false),
3700 0);
Richard Smithad762fc2011-04-14 22:09:26 +00003701 return AutoDeductTy;
3702}
3703
3704/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3705QualType ASTContext::getAutoRRefDeductType() const {
3706 if (AutoRRefDeductTy.isNull())
3707 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3708 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3709 return AutoRRefDeductTy;
3710}
3711
Reid Spencer5f016e22007-07-11 17:01:13 +00003712/// getTagDeclType - Return the unique reference to the type for the
3713/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad4ba2a172011-01-12 09:06:06 +00003714QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenekd778f882007-11-26 21:16:01 +00003715 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00003716 // FIXME: What is the design on getTagDeclType when it requires casting
3717 // away const? mutable?
3718 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003719}
3720
Mike Stump1eb44332009-09-09 15:08:12 +00003721/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3722/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3723/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00003724CanQualType ASTContext::getSizeType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003725 return getFromTargetType(Target->getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00003726}
3727
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003728/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3729CanQualType ASTContext::getIntMaxType() const {
3730 return getFromTargetType(Target->getIntMaxType());
3731}
3732
3733/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3734CanQualType ASTContext::getUIntMaxType() const {
3735 return getFromTargetType(Target->getUIntMaxType());
3736}
3737
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00003738/// getSignedWCharType - Return the type of "signed wchar_t".
3739/// Used when in C++, as a GCC extension.
3740QualType ASTContext::getSignedWCharType() const {
3741 // FIXME: derive from "Target" ?
3742 return WCharTy;
3743}
3744
3745/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3746/// Used when in C++, as a GCC extension.
3747QualType ASTContext::getUnsignedWCharType() const {
3748 // FIXME: derive from "Target" ?
3749 return UnsignedIntTy;
3750}
3751
Enea Zaffanella9677eb82013-01-26 17:08:37 +00003752QualType ASTContext::getIntPtrType() const {
3753 return getFromTargetType(Target->getIntPtrType());
3754}
3755
3756QualType ASTContext::getUIntPtrType() const {
3757 return getCorrespondingUnsignedType(getIntPtrType());
3758}
3759
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003760/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattner8b9023b2007-07-13 03:05:23 +00003761/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3762QualType ASTContext::getPointerDiffType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003763 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00003764}
3765
Eli Friedman6902e412012-11-27 02:58:24 +00003766/// \brief Return the unique type for "pid_t" defined in
3767/// <sys/types.h>. We need this to compute the correct type for vfork().
3768QualType ASTContext::getProcessIDType() const {
3769 return getFromTargetType(Target->getProcessIDType());
3770}
3771
Chris Lattnere6327742008-04-02 05:18:44 +00003772//===----------------------------------------------------------------------===//
3773// Type Operators
3774//===----------------------------------------------------------------------===//
3775
Jay Foad4ba2a172011-01-12 09:06:06 +00003776CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCall54e14c42009-10-22 22:37:11 +00003777 // Push qualifiers into arrays, and then discard any remaining
3778 // qualifiers.
3779 T = getCanonicalType(T);
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003780 T = getVariableArrayDecayedType(T);
John McCall54e14c42009-10-22 22:37:11 +00003781 const Type *Ty = T.getTypePtr();
John McCall54e14c42009-10-22 22:37:11 +00003782 QualType Result;
3783 if (isa<ArrayType>(Ty)) {
3784 Result = getArrayDecayedType(QualType(Ty,0));
3785 } else if (isa<FunctionType>(Ty)) {
3786 Result = getPointerType(QualType(Ty, 0));
3787 } else {
3788 Result = QualType(Ty, 0);
3789 }
3790
3791 return CanQualType::CreateUnsafe(Result);
3792}
3793
John McCall62c28c82011-01-18 07:41:22 +00003794QualType ASTContext::getUnqualifiedArrayType(QualType type,
3795 Qualifiers &quals) {
3796 SplitQualType splitType = type.getSplitUnqualifiedType();
3797
3798 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3799 // the unqualified desugared type and then drops it on the floor.
3800 // We then have to strip that sugar back off with
3801 // getUnqualifiedDesugaredType(), which is silly.
3802 const ArrayType *AT =
John McCall200fa532012-02-08 00:46:36 +00003803 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall62c28c82011-01-18 07:41:22 +00003804
3805 // If we don't have an array, just use the results in splitType.
Douglas Gregor9dadd942010-05-17 18:45:21 +00003806 if (!AT) {
John McCall200fa532012-02-08 00:46:36 +00003807 quals = splitType.Quals;
3808 return QualType(splitType.Ty, 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003809 }
3810
John McCall62c28c82011-01-18 07:41:22 +00003811 // Otherwise, recurse on the array's element type.
3812 QualType elementType = AT->getElementType();
3813 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3814
3815 // If that didn't change the element type, AT has no qualifiers, so we
3816 // can just use the results in splitType.
3817 if (elementType == unqualElementType) {
3818 assert(quals.empty()); // from the recursive call
John McCall200fa532012-02-08 00:46:36 +00003819 quals = splitType.Quals;
3820 return QualType(splitType.Ty, 0);
John McCall62c28c82011-01-18 07:41:22 +00003821 }
3822
3823 // Otherwise, add in the qualifiers from the outermost type, then
3824 // build the type back up.
John McCall200fa532012-02-08 00:46:36 +00003825 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003826
Douglas Gregor9dadd942010-05-17 18:45:21 +00003827 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003828 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003829 CAT->getSizeModifier(), 0);
3830 }
3831
Douglas Gregor9dadd942010-05-17 18:45:21 +00003832 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003833 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003834 }
3835
Douglas Gregor9dadd942010-05-17 18:45:21 +00003836 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003837 return getVariableArrayType(unqualElementType,
John McCall3fa5cae2010-10-26 07:05:15 +00003838 VAT->getSizeExpr(),
Douglas Gregor9dadd942010-05-17 18:45:21 +00003839 VAT->getSizeModifier(),
3840 VAT->getIndexTypeCVRQualifiers(),
3841 VAT->getBracketsRange());
3842 }
3843
3844 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall62c28c82011-01-18 07:41:22 +00003845 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003846 DSAT->getSizeModifier(), 0,
3847 SourceRange());
3848}
3849
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003850/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3851/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3852/// they point to and return true. If T1 and T2 aren't pointer types
3853/// or pointer-to-member types, or if they are not similar at this
3854/// level, returns false and leaves T1 and T2 unchanged. Top-level
3855/// qualifiers on T1 and T2 are ignored. This function will typically
3856/// be called in a loop that successively "unwraps" pointer and
3857/// pointer-to-member types to compare them at each level.
3858bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3859 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3860 *T2PtrType = T2->getAs<PointerType>();
3861 if (T1PtrType && T2PtrType) {
3862 T1 = T1PtrType->getPointeeType();
3863 T2 = T2PtrType->getPointeeType();
3864 return true;
3865 }
3866
3867 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3868 *T2MPType = T2->getAs<MemberPointerType>();
3869 if (T1MPType && T2MPType &&
3870 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3871 QualType(T2MPType->getClass(), 0))) {
3872 T1 = T1MPType->getPointeeType();
3873 T2 = T2MPType->getPointeeType();
3874 return true;
3875 }
3876
David Blaikie4e4d0842012-03-11 07:00:24 +00003877 if (getLangOpts().ObjC1) {
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003878 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3879 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3880 if (T1OPType && T2OPType) {
3881 T1 = T1OPType->getPointeeType();
3882 T2 = T2OPType->getPointeeType();
3883 return true;
3884 }
3885 }
3886
3887 // FIXME: Block pointers, too?
3888
3889 return false;
3890}
3891
Jay Foad4ba2a172011-01-12 09:06:06 +00003892DeclarationNameInfo
3893ASTContext::getNameForTemplate(TemplateName Name,
3894 SourceLocation NameLoc) const {
John McCall14606042011-06-30 08:33:18 +00003895 switch (Name.getKind()) {
3896 case TemplateName::QualifiedTemplate:
3897 case TemplateName::Template:
Abramo Bagnara25777432010-08-11 22:01:17 +00003898 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCall14606042011-06-30 08:33:18 +00003899 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3900 NameLoc);
Abramo Bagnara25777432010-08-11 22:01:17 +00003901
John McCall14606042011-06-30 08:33:18 +00003902 case TemplateName::OverloadedTemplate: {
3903 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3904 // DNInfo work in progress: CHECKME: what about DNLoc?
3905 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3906 }
3907
3908 case TemplateName::DependentTemplate: {
3909 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnara25777432010-08-11 22:01:17 +00003910 DeclarationName DName;
John McCall80ad16f2009-11-24 18:42:40 +00003911 if (DTN->isIdentifier()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00003912 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3913 return DeclarationNameInfo(DName, NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003914 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00003915 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3916 // DNInfo work in progress: FIXME: source locations?
3917 DeclarationNameLoc DNLoc;
3918 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3919 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3920 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003921 }
3922 }
3923
John McCall14606042011-06-30 08:33:18 +00003924 case TemplateName::SubstTemplateTemplateParm: {
3925 SubstTemplateTemplateParmStorage *subst
3926 = Name.getAsSubstTemplateTemplateParm();
3927 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3928 NameLoc);
3929 }
3930
3931 case TemplateName::SubstTemplateTemplateParmPack: {
3932 SubstTemplateTemplateParmPackStorage *subst
3933 = Name.getAsSubstTemplateTemplateParmPack();
3934 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3935 NameLoc);
3936 }
3937 }
3938
3939 llvm_unreachable("bad template name kind!");
John McCall80ad16f2009-11-24 18:42:40 +00003940}
3941
Jay Foad4ba2a172011-01-12 09:06:06 +00003942TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCall14606042011-06-30 08:33:18 +00003943 switch (Name.getKind()) {
3944 case TemplateName::QualifiedTemplate:
3945 case TemplateName::Template: {
3946 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003947 if (TemplateTemplateParmDecl *TTP
John McCall14606042011-06-30 08:33:18 +00003948 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003949 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3950
3951 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00003952 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003953 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003954
John McCall14606042011-06-30 08:33:18 +00003955 case TemplateName::OverloadedTemplate:
3956 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump1eb44332009-09-09 15:08:12 +00003957
John McCall14606042011-06-30 08:33:18 +00003958 case TemplateName::DependentTemplate: {
3959 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3960 assert(DTN && "Non-dependent template names must refer to template decls.");
3961 return DTN->CanonicalTemplateName;
3962 }
3963
3964 case TemplateName::SubstTemplateTemplateParm: {
3965 SubstTemplateTemplateParmStorage *subst
3966 = Name.getAsSubstTemplateTemplateParm();
3967 return getCanonicalTemplateName(subst->getReplacement());
3968 }
3969
3970 case TemplateName::SubstTemplateTemplateParmPack: {
3971 SubstTemplateTemplateParmPackStorage *subst
3972 = Name.getAsSubstTemplateTemplateParmPack();
3973 TemplateTemplateParmDecl *canonParameter
3974 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3975 TemplateArgument canonArgPack
3976 = getCanonicalTemplateArgument(subst->getArgumentPack());
3977 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3978 }
3979 }
3980
3981 llvm_unreachable("bad template name!");
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003982}
3983
Douglas Gregordb0d4b72009-11-11 23:06:43 +00003984bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3985 X = getCanonicalTemplateName(X);
3986 Y = getCanonicalTemplateName(Y);
3987 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3988}
3989
Mike Stump1eb44332009-09-09 15:08:12 +00003990TemplateArgument
Jay Foad4ba2a172011-01-12 09:06:06 +00003991ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregor1275ae02009-07-28 23:00:59 +00003992 switch (Arg.getKind()) {
3993 case TemplateArgument::Null:
3994 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003995
Douglas Gregor1275ae02009-07-28 23:00:59 +00003996 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00003997 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003998
Douglas Gregord2008e22012-04-06 22:40:38 +00003999 case TemplateArgument::Declaration: {
Eli Friedmand7a6b162012-09-26 02:36:12 +00004000 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
4001 return TemplateArgument(D, Arg.isDeclForReferenceParam());
Douglas Gregord2008e22012-04-06 22:40:38 +00004002 }
Mike Stump1eb44332009-09-09 15:08:12 +00004003
Eli Friedmand7a6b162012-09-26 02:36:12 +00004004 case TemplateArgument::NullPtr:
4005 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4006 /*isNullPtr*/true);
4007
Douglas Gregor788cd062009-11-11 01:00:40 +00004008 case TemplateArgument::Template:
4009 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregora7fc9012011-01-05 18:58:31 +00004010
4011 case TemplateArgument::TemplateExpansion:
4012 return TemplateArgument(getCanonicalTemplateName(
4013 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregor2be29f42011-01-14 23:41:42 +00004014 Arg.getNumTemplateExpansions());
Douglas Gregora7fc9012011-01-05 18:58:31 +00004015
Douglas Gregor1275ae02009-07-28 23:00:59 +00004016 case TemplateArgument::Integral:
Benjamin Kramer85524372012-06-07 15:09:51 +00004017 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00004018
Douglas Gregor1275ae02009-07-28 23:00:59 +00004019 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00004020 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00004021
Douglas Gregor1275ae02009-07-28 23:00:59 +00004022 case TemplateArgument::Pack: {
Douglas Gregor87dd6972010-12-20 16:52:59 +00004023 if (Arg.pack_size() == 0)
4024 return Arg;
4025
Douglas Gregor910f8002010-11-07 23:05:16 +00004026 TemplateArgument *CanonArgs
4027 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregor1275ae02009-07-28 23:00:59 +00004028 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004029 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00004030 AEnd = Arg.pack_end();
4031 A != AEnd; (void)++A, ++Idx)
4032 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00004033
Douglas Gregor910f8002010-11-07 23:05:16 +00004034 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregor1275ae02009-07-28 23:00:59 +00004035 }
4036 }
4037
4038 // Silence GCC warning
David Blaikieb219cfc2011-09-23 05:06:16 +00004039 llvm_unreachable("Unhandled template argument kind");
Douglas Gregor1275ae02009-07-28 23:00:59 +00004040}
4041
Douglas Gregord57959a2009-03-27 23:10:48 +00004042NestedNameSpecifier *
Jay Foad4ba2a172011-01-12 09:06:06 +00004043ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump1eb44332009-09-09 15:08:12 +00004044 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00004045 return 0;
4046
4047 switch (NNS->getKind()) {
4048 case NestedNameSpecifier::Identifier:
4049 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00004050 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00004051 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4052 NNS->getAsIdentifier());
4053
4054 case NestedNameSpecifier::Namespace:
4055 // A namespace is canonical; build a nested-name-specifier with
4056 // this namespace and no prefix.
Douglas Gregor14aba762011-02-24 02:36:08 +00004057 return NestedNameSpecifier::Create(*this, 0,
4058 NNS->getAsNamespace()->getOriginalNamespace());
4059
4060 case NestedNameSpecifier::NamespaceAlias:
4061 // A namespace is canonical; build a nested-name-specifier with
4062 // this namespace and no prefix.
4063 return NestedNameSpecifier::Create(*this, 0,
4064 NNS->getAsNamespaceAlias()->getNamespace()
4065 ->getOriginalNamespace());
Douglas Gregord57959a2009-03-27 23:10:48 +00004066
4067 case NestedNameSpecifier::TypeSpec:
4068 case NestedNameSpecifier::TypeSpecWithTemplate: {
4069 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor264bf662010-11-04 00:09:33 +00004070
4071 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4072 // break it apart into its prefix and identifier, then reconsititute those
4073 // as the canonical nested-name-specifier. This is required to canonicalize
4074 // a dependent nested-name-specifier involving typedefs of dependent-name
4075 // types, e.g.,
4076 // typedef typename T::type T1;
4077 // typedef typename T1::type T2;
Eli Friedman16412ef2012-03-03 04:09:56 +00004078 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4079 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor264bf662010-11-04 00:09:33 +00004080 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor264bf662010-11-04 00:09:33 +00004081
Eli Friedman16412ef2012-03-03 04:09:56 +00004082 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4083 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4084 // first place?
John McCall3b657512011-01-19 10:06:00 +00004085 return NestedNameSpecifier::Create(*this, 0, false,
4086 const_cast<Type*>(T.getTypePtr()));
Douglas Gregord57959a2009-03-27 23:10:48 +00004087 }
4088
4089 case NestedNameSpecifier::Global:
4090 // The global specifier is canonical and unique.
4091 return NNS;
4092 }
4093
David Blaikie7530c032012-01-17 06:56:22 +00004094 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregord57959a2009-03-27 23:10:48 +00004095}
4096
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004097
Jay Foad4ba2a172011-01-12 09:06:06 +00004098const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004099 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004100 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004101 // Handle the common positive case fast.
4102 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4103 return AT;
4104 }
Mike Stump1eb44332009-09-09 15:08:12 +00004105
John McCall0953e762009-09-24 19:53:00 +00004106 // Handle the common negative case fast.
John McCall3b657512011-01-19 10:06:00 +00004107 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004108 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004109
John McCall0953e762009-09-24 19:53:00 +00004110 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004111 // implements C99 6.7.3p8: "If the specification of an array type includes
4112 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00004113
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004114 // If we get here, we either have type qualifiers on the type, or we have
4115 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00004116 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00004117
John McCall3b657512011-01-19 10:06:00 +00004118 SplitQualType split = T.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00004119 Qualifiers qs = split.Quals;
Mike Stump1eb44332009-09-09 15:08:12 +00004120
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004121 // If we have a simple case, just return now.
John McCall200fa532012-02-08 00:46:36 +00004122 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall3b657512011-01-19 10:06:00 +00004123 if (ATy == 0 || qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004124 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00004125
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004126 // Otherwise, we have an array and we have qualifiers on it. Push the
4127 // qualifiers into the array element type and return a new array type.
John McCall3b657512011-01-19 10:06:00 +00004128 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump1eb44332009-09-09 15:08:12 +00004129
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004130 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4131 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4132 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004133 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004134 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4135 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4136 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004137 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00004138
Mike Stump1eb44332009-09-09 15:08:12 +00004139 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00004140 = dyn_cast<DependentSizedArrayType>(ATy))
4141 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00004142 getDependentSizedArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00004143 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00004144 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004145 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004146 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00004147
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004148 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004149 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00004150 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004151 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00004152 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004153 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00004154}
4155
Abramo Bagnaraad9689f2012-05-17 12:44:05 +00004156QualType ASTContext::getAdjustedParameterType(QualType T) const {
Douglas Gregor79e6bd32011-07-12 04:42:08 +00004157 // C99 6.7.5.3p7:
4158 // A declaration of a parameter as "array of type" shall be
4159 // adjusted to "qualified pointer to type", where the type
4160 // qualifiers (if any) are those specified within the [ and ] of
4161 // the array type derivation.
4162 if (T->isArrayType())
4163 return getArrayDecayedType(T);
4164
4165 // C99 6.7.5.3p8:
4166 // A declaration of a parameter as "function returning type"
4167 // shall be adjusted to "pointer to function returning type", as
4168 // in 6.3.2.1.
4169 if (T->isFunctionType())
4170 return getPointerType(T);
4171
4172 return T;
4173}
4174
Abramo Bagnaraad9689f2012-05-17 12:44:05 +00004175QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor79e6bd32011-07-12 04:42:08 +00004176 T = getVariableArrayDecayedType(T);
4177 T = getAdjustedParameterType(T);
4178 return T.getUnqualifiedType();
4179}
4180
Chris Lattnere6327742008-04-02 05:18:44 +00004181/// getArrayDecayedType - Return the properly qualified result of decaying the
4182/// specified array type to a pointer. This operation is non-trivial when
4183/// handling typedefs etc. The canonical type of "T" must be an array type,
4184/// this returns a pointer to a properly qualified element of the array.
4185///
4186/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad4ba2a172011-01-12 09:06:06 +00004187QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004188 // Get the element type with 'getAsArrayType' so that we don't lose any
4189 // typedefs in the element type of the array. This also handles propagation
4190 // of type qualifiers from the array type into the element type if present
4191 // (C99 6.7.3p8).
4192 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4193 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00004194
Chris Lattnerc63a1f22008-08-04 07:31:14 +00004195 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00004196
4197 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00004198 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00004199}
4200
John McCall3b657512011-01-19 10:06:00 +00004201QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4202 return getBaseElementType(array->getElementType());
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00004203}
4204
John McCall3b657512011-01-19 10:06:00 +00004205QualType ASTContext::getBaseElementType(QualType type) const {
4206 Qualifiers qs;
4207 while (true) {
4208 SplitQualType split = type.getSplitDesugaredType();
John McCall200fa532012-02-08 00:46:36 +00004209 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall3b657512011-01-19 10:06:00 +00004210 if (!array) break;
Mike Stump1eb44332009-09-09 15:08:12 +00004211
John McCall3b657512011-01-19 10:06:00 +00004212 type = array->getElementType();
John McCall200fa532012-02-08 00:46:36 +00004213 qs.addConsistentQualifiers(split.Quals);
John McCall3b657512011-01-19 10:06:00 +00004214 }
Mike Stump1eb44332009-09-09 15:08:12 +00004215
John McCall3b657512011-01-19 10:06:00 +00004216 return getQualifiedType(type, qs);
Anders Carlsson6183a992008-12-21 03:44:36 +00004217}
4218
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004219/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00004220uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004221ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4222 uint64_t ElementCount = 1;
4223 do {
4224 ElementCount *= CA->getSize().getZExtValue();
Richard Smithd5e83942012-12-06 03:04:50 +00004225 CA = dyn_cast_or_null<ConstantArrayType>(
4226 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian0de78992009-08-21 16:31:06 +00004227 } while (CA);
4228 return ElementCount;
4229}
4230
Reid Spencer5f016e22007-07-11 17:01:13 +00004231/// getFloatingRank - Return a relative rank for floating point types.
4232/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00004233static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00004234 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00004235 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00004236
John McCall183700f2009-09-21 23:43:11 +00004237 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4238 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004239 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00004240 case BuiltinType::Half: return HalfRank;
Reid Spencer5f016e22007-07-11 17:01:13 +00004241 case BuiltinType::Float: return FloatRank;
4242 case BuiltinType::Double: return DoubleRank;
4243 case BuiltinType::LongDouble: return LongDoubleRank;
4244 }
4245}
4246
Mike Stump1eb44332009-09-09 15:08:12 +00004247/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4248/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00004249/// 'typeDomain' is a real floating point or complex type.
4250/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00004251QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4252 QualType Domain) const {
4253 FloatingRank EltRank = getFloatingRank(Size);
4254 if (Domain->isComplexType()) {
4255 switch (EltRank) {
David Blaikie561d3ab2012-01-17 02:30:50 +00004256 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Narofff1448a02007-08-27 01:27:54 +00004257 case FloatRank: return FloatComplexTy;
4258 case DoubleRank: return DoubleComplexTy;
4259 case LongDoubleRank: return LongDoubleComplexTy;
4260 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004261 }
Chris Lattner1361b112008-04-06 23:58:54 +00004262
4263 assert(Domain->isRealFloatingType() && "Unknown domain!");
4264 switch (EltRank) {
Joey Gouly19dbb202013-01-23 11:56:20 +00004265 case HalfRank: return HalfTy;
Chris Lattner1361b112008-04-06 23:58:54 +00004266 case FloatRank: return FloatTy;
4267 case DoubleRank: return DoubleTy;
4268 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00004269 }
David Blaikie561d3ab2012-01-17 02:30:50 +00004270 llvm_unreachable("getFloatingRank(): illegal value for rank");
Reid Spencer5f016e22007-07-11 17:01:13 +00004271}
4272
Chris Lattner7cfeb082008-04-06 23:55:33 +00004273/// getFloatingTypeOrder - Compare the rank of the two specified floating
4274/// point types, ignoring the domain of the type (i.e. 'double' ==
4275/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00004276/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00004277int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnera75cea32008-04-06 23:38:49 +00004278 FloatingRank LHSR = getFloatingRank(LHS);
4279 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004280
Chris Lattnera75cea32008-04-06 23:38:49 +00004281 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00004282 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00004283 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00004284 return 1;
4285 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00004286}
4287
Chris Lattnerf52ab252008-04-06 22:59:24 +00004288/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4289/// routine will assert if passed a built-in type that isn't an integer or enum,
4290/// or if it is not canonicalized.
John McCallf4c73712011-01-19 06:33:43 +00004291unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCall467b27b2009-10-22 20:10:53 +00004292 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00004293
Chris Lattnerf52ab252008-04-06 22:59:24 +00004294 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004295 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattner7cfeb082008-04-06 23:55:33 +00004296 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004297 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004298 case BuiltinType::Char_S:
4299 case BuiltinType::Char_U:
4300 case BuiltinType::SChar:
4301 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004302 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004303 case BuiltinType::Short:
4304 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004305 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004306 case BuiltinType::Int:
4307 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004308 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004309 case BuiltinType::Long:
4310 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004311 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00004312 case BuiltinType::LongLong:
4313 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00004314 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00004315 case BuiltinType::Int128:
4316 case BuiltinType::UInt128:
4317 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00004318 }
4319}
4320
Eli Friedman04e83572009-08-20 04:21:42 +00004321/// \brief Whether this is a promotable bitfield reference according
4322/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4323///
4324/// \returns the type this bit-field will promote to, or NULL if no
4325/// promotion occurs.
Jay Foad4ba2a172011-01-12 09:06:06 +00004326QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregorceafbde2010-05-24 20:13:53 +00004327 if (E->isTypeDependent() || E->isValueDependent())
4328 return QualType();
4329
John McCall993f43f2013-05-06 21:39:12 +00004330 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman04e83572009-08-20 04:21:42 +00004331 if (!Field)
4332 return QualType();
4333
4334 QualType FT = Field->getType();
4335
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004336 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman04e83572009-08-20 04:21:42 +00004337 uint64_t IntSize = getTypeSize(IntTy);
4338 // GCC extension compatibility: if the bit-field size is less than or equal
4339 // to the size of int, it gets promoted no matter what its type is.
4340 // For instance, unsigned long bf : 4 gets promoted to signed int.
4341 if (BitWidth < IntSize)
4342 return IntTy;
4343
4344 if (BitWidth == IntSize)
4345 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4346
4347 // Types bigger than int are not subject to promotions, and therefore act
4348 // like the base type.
4349 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4350 // is ridiculous.
4351 return QualType();
4352}
4353
Eli Friedmana95d7572009-08-19 07:44:53 +00004354/// getPromotedIntegerType - Returns the type that Promotable will
4355/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4356/// integer type.
Jay Foad4ba2a172011-01-12 09:06:06 +00004357QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedmana95d7572009-08-19 07:44:53 +00004358 assert(!Promotable.isNull());
4359 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00004360 if (const EnumType *ET = Promotable->getAs<EnumType>())
4361 return ET->getDecl()->getPromotionType();
Eli Friedman68a2dc42011-10-26 07:22:48 +00004362
4363 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4364 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4365 // (3.9.1) can be converted to a prvalue of the first of the following
4366 // types that can represent all the values of its underlying type:
4367 // int, unsigned int, long int, unsigned long int, long long int, or
4368 // unsigned long long int [...]
4369 // FIXME: Is there some better way to compute this?
4370 if (BT->getKind() == BuiltinType::WChar_S ||
4371 BT->getKind() == BuiltinType::WChar_U ||
4372 BT->getKind() == BuiltinType::Char16 ||
4373 BT->getKind() == BuiltinType::Char32) {
4374 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4375 uint64_t FromSize = getTypeSize(BT);
4376 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4377 LongLongTy, UnsignedLongLongTy };
4378 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4379 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4380 if (FromSize < ToSize ||
4381 (FromSize == ToSize &&
4382 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4383 return PromoteTypes[Idx];
4384 }
4385 llvm_unreachable("char type should fit into long long");
4386 }
4387 }
4388
4389 // At this point, we should have a signed or unsigned integer type.
Eli Friedmana95d7572009-08-19 07:44:53 +00004390 if (Promotable->isSignedIntegerType())
4391 return IntTy;
Eli Friedman5b64e772012-11-15 01:21:59 +00004392 uint64_t PromotableSize = getIntWidth(Promotable);
4393 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedmana95d7572009-08-19 07:44:53 +00004394 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4395 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4396}
4397
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00004398/// \brief Recurses in pointer/array types until it finds an objc retainable
4399/// type and returns its ownership.
4400Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4401 while (!T.isNull()) {
4402 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4403 return T.getObjCLifetime();
4404 if (T->isArrayType())
4405 T = getBaseElementType(T);
4406 else if (const PointerType *PT = T->getAs<PointerType>())
4407 T = PT->getPointeeType();
4408 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis28445f02011-07-01 23:01:46 +00004409 T = RT->getPointeeType();
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00004410 else
4411 break;
4412 }
4413
4414 return Qualifiers::OCL_None;
4415}
4416
Mike Stump1eb44332009-09-09 15:08:12 +00004417/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00004418/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00004419/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00004420int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCallf4c73712011-01-19 06:33:43 +00004421 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4422 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00004423 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004424
Chris Lattnerf52ab252008-04-06 22:59:24 +00004425 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4426 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00004427
Chris Lattner7cfeb082008-04-06 23:55:33 +00004428 unsigned LHSRank = getIntegerRank(LHSC);
4429 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00004430
Chris Lattner7cfeb082008-04-06 23:55:33 +00004431 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4432 if (LHSRank == RHSRank) return 0;
4433 return LHSRank > RHSRank ? 1 : -1;
4434 }
Mike Stump1eb44332009-09-09 15:08:12 +00004435
Chris Lattner7cfeb082008-04-06 23:55:33 +00004436 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4437 if (LHSUnsigned) {
4438 // If the unsigned [LHS] type is larger, return it.
4439 if (LHSRank >= RHSRank)
4440 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004441
Chris Lattner7cfeb082008-04-06 23:55:33 +00004442 // If the signed type can represent all values of the unsigned type, it
4443 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00004444 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00004445 return -1;
4446 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00004447
Chris Lattner7cfeb082008-04-06 23:55:33 +00004448 // If the unsigned [RHS] type is larger, return it.
4449 if (RHSRank >= LHSRank)
4450 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00004451
Chris Lattner7cfeb082008-04-06 23:55:33 +00004452 // If the signed type can represent all values of the unsigned type, it
4453 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00004454 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00004455 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00004456}
Anders Carlsson71993dd2007-08-17 05:31:46 +00004457
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004458static RecordDecl *
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004459CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
4460 DeclContext *DC, IdentifierInfo *Id) {
4461 SourceLocation Loc;
David Blaikie4e4d0842012-03-11 07:00:24 +00004462 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004463 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004464 else
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004465 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004466}
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004467
Mike Stump1eb44332009-09-09 15:08:12 +00004468// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00004469QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson71993dd2007-08-17 05:31:46 +00004470 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00004471 CFConstantStringTypeDecl =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004472 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004473 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00004474 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004475
Anders Carlssonf06273f2007-11-19 00:25:30 +00004476 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00004477
Anders Carlsson71993dd2007-08-17 05:31:46 +00004478 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00004479 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00004480 // int flags;
4481 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00004482 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00004483 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00004484 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00004485 FieldTypes[3] = LongTy;
4486
Anders Carlsson71993dd2007-08-17 05:31:46 +00004487 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00004488 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00004489 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004490 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00004491 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00004492 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00004493 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004494 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004495 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004496 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004497 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00004498 }
4499
Douglas Gregor838db382010-02-11 01:19:42 +00004500 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00004501 }
Mike Stump1eb44332009-09-09 15:08:12 +00004502
Anders Carlsson71993dd2007-08-17 05:31:46 +00004503 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00004504}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004505
Fariborz Jahanianf7992132013-01-04 18:45:40 +00004506QualType ASTContext::getObjCSuperType() const {
4507 if (ObjCSuperType.isNull()) {
4508 RecordDecl *ObjCSuperTypeDecl =
4509 CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get("objc_super"));
4510 TUDecl->addDecl(ObjCSuperTypeDecl);
4511 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4512 }
4513 return ObjCSuperType;
4514}
4515
Douglas Gregor319ac892009-04-23 22:29:11 +00004516void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004517 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00004518 assert(Rec && "Invalid CFConstantStringType");
4519 CFConstantStringTypeDecl = Rec->getDecl();
4520}
4521
Jay Foad4ba2a172011-01-12 09:06:06 +00004522QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpadaaad32009-10-20 02:12:22 +00004523 if (BlockDescriptorType)
4524 return getTagDeclType(BlockDescriptorType);
4525
4526 RecordDecl *T;
4527 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004528 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004529 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00004530 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00004531
4532 QualType FieldTypes[] = {
4533 UnsignedLongTy,
4534 UnsignedLongTy,
4535 };
4536
4537 const char *FieldNames[] = {
4538 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00004539 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00004540 };
4541
4542 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004543 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00004544 SourceLocation(),
4545 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004546 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00004547 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004548 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004549 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004550 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00004551 T->addDecl(Field);
4552 }
4553
Douglas Gregor838db382010-02-11 01:19:42 +00004554 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00004555
4556 BlockDescriptorType = T;
4557
4558 return getTagDeclType(BlockDescriptorType);
4559}
4560
Jay Foad4ba2a172011-01-12 09:06:06 +00004561QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stump083c25e2009-10-22 00:49:09 +00004562 if (BlockDescriptorExtendedType)
4563 return getTagDeclType(BlockDescriptorExtendedType);
4564
4565 RecordDecl *T;
4566 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004567 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00004568 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00004569 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00004570
4571 QualType FieldTypes[] = {
4572 UnsignedLongTy,
4573 UnsignedLongTy,
4574 getPointerType(VoidPtrTy),
4575 getPointerType(VoidPtrTy)
4576 };
4577
4578 const char *FieldNames[] = {
4579 "reserved",
4580 "Size",
4581 "CopyFuncPtr",
4582 "DestroyFuncPtr"
4583 };
4584
4585 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004586 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stump083c25e2009-10-22 00:49:09 +00004587 SourceLocation(),
4588 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00004589 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00004590 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00004591 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00004592 ICIS_NoInit);
John McCall2888b652010-04-30 21:35:41 +00004593 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00004594 T->addDecl(Field);
4595 }
4596
Douglas Gregor838db382010-02-11 01:19:42 +00004597 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00004598
4599 BlockDescriptorExtendedType = T;
4600
4601 return getTagDeclType(BlockDescriptorExtendedType);
4602}
4603
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00004604/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4605/// requires copy/dispose. Note that this must match the logic
4606/// in buildByrefHelpers.
4607bool ASTContext::BlockRequiresCopying(QualType Ty,
4608 const VarDecl *D) {
4609 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4610 const Expr *copyExpr = getBlockVarCopyInits(D);
4611 if (!copyExpr && record->hasTrivialDestructor()) return false;
4612
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004613 return true;
Fariborz Jahaniane38be612010-11-17 00:21:28 +00004614 }
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00004615
4616 if (!Ty->isObjCRetainableType()) return false;
4617
4618 Qualifiers qs = Ty.getQualifiers();
4619
4620 // If we have lifetime, that dominates.
4621 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4622 assert(getLangOpts().ObjCAutoRefCount);
4623
4624 switch (lifetime) {
4625 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4626
4627 // These are just bits as far as the runtime is concerned.
4628 case Qualifiers::OCL_ExplicitNone:
4629 case Qualifiers::OCL_Autoreleasing:
4630 return false;
4631
4632 // Tell the runtime that this is ARC __weak, called by the
4633 // byref routines.
4634 case Qualifiers::OCL_Weak:
4635 // ARC __strong __block variables need to be retained.
4636 case Qualifiers::OCL_Strong:
4637 return true;
4638 }
4639 llvm_unreachable("fell out of lifetime switch!");
4640 }
4641 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4642 Ty->isObjCObjectPointerType());
Mike Stumpaf7b44d2009-10-21 18:16:27 +00004643}
4644
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00004645bool ASTContext::getByrefLifetime(QualType Ty,
4646 Qualifiers::ObjCLifetime &LifeTime,
4647 bool &HasByrefExtendedLayout) const {
4648
4649 if (!getLangOpts().ObjC1 ||
4650 getLangOpts().getGC() != LangOptions::NonGC)
4651 return false;
4652
4653 HasByrefExtendedLayout = false;
Fariborz Jahanian34db84f2012-12-11 19:58:01 +00004654 if (Ty->isRecordType()) {
Fariborz Jahanian3ca23d72012-11-14 17:15:51 +00004655 HasByrefExtendedLayout = true;
4656 LifeTime = Qualifiers::OCL_None;
4657 }
4658 else if (getLangOpts().ObjCAutoRefCount)
4659 LifeTime = Ty.getObjCLifetime();
4660 // MRR.
4661 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4662 LifeTime = Qualifiers::OCL_ExplicitNone;
4663 else
4664 LifeTime = Qualifiers::OCL_None;
4665 return true;
4666}
4667
Douglas Gregore97179c2011-09-08 01:46:34 +00004668TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4669 if (!ObjCInstanceTypeDecl)
4670 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4671 getTranslationUnitDecl(),
4672 SourceLocation(),
4673 SourceLocation(),
4674 &Idents.get("instancetype"),
4675 getTrivialTypeSourceInfo(getObjCIdType()));
4676 return ObjCInstanceTypeDecl;
4677}
4678
Anders Carlssone8c49532007-10-29 06:33:42 +00004679// This returns true if a type has been typedefed to BOOL:
4680// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00004681static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00004682 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00004683 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4684 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00004685
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004686 return false;
4687}
4688
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004689/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004690/// purpose.
Jay Foad4ba2a172011-01-12 09:06:06 +00004691CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregorf968d832011-05-27 01:19:52 +00004692 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4693 return CharUnits::Zero();
4694
Ken Dyck199c3d62010-01-11 17:06:35 +00004695 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00004696
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004697 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004698 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004699 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004700 // Treat arrays as pointers, since that's how they're passed in.
4701 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004702 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004703 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00004704}
4705
4706static inline
4707std::string charUnitsToString(const CharUnits &CU) {
4708 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004709}
4710
John McCall6b5a61b2011-02-07 10:33:21 +00004711/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00004712/// declaration.
John McCall6b5a61b2011-02-07 10:33:21 +00004713std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4714 std::string S;
4715
David Chisnall5e530af2009-11-17 19:33:30 +00004716 const BlockDecl *Decl = Expr->getBlockDecl();
4717 QualType BlockTy =
4718 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4719 // Encode result type.
Fariborz Jahanian3d145f62012-11-15 19:02:45 +00004720 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian06cffc02012-11-14 23:11:38 +00004721 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None,
4722 BlockTy->getAs<FunctionType>()->getResultType(),
4723 S, true /*Extended*/);
4724 else
4725 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(),
4726 S);
David Chisnall5e530af2009-11-17 19:33:30 +00004727 // Compute size of all parameters.
4728 // Start with computing size of a pointer in number of bytes.
4729 // FIXME: There might(should) be a better way of doing this computation!
4730 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004731 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4732 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00004733 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00004734 E = Decl->param_end(); PI != E; ++PI) {
4735 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004736 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahanian075a5432012-06-30 00:48:59 +00004737 if (sz.isZero())
4738 continue;
Ken Dyck199c3d62010-01-11 17:06:35 +00004739 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00004740 ParmOffset += sz;
4741 }
4742 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00004743 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00004744 // Block pointer and offset.
4745 S += "@?0";
David Chisnall5e530af2009-11-17 19:33:30 +00004746
4747 // Argument types.
4748 ParmOffset = PtrSize;
4749 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4750 Decl->param_end(); PI != E; ++PI) {
4751 ParmVarDecl *PVDecl = *PI;
4752 QualType PType = PVDecl->getOriginalType();
4753 if (const ArrayType *AT =
4754 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4755 // Use array's original type only if it has known number of
4756 // elements.
4757 if (!isa<ConstantArrayType>(AT))
4758 PType = PVDecl->getType();
4759 } else if (PType->isFunctionType())
4760 PType = PVDecl->getType();
Fariborz Jahanian3d145f62012-11-15 19:02:45 +00004761 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian06cffc02012-11-14 23:11:38 +00004762 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4763 S, true /*Extended*/);
4764 else
4765 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00004766 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004767 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00004768 }
John McCall6b5a61b2011-02-07 10:33:21 +00004769
4770 return S;
David Chisnall5e530af2009-11-17 19:33:30 +00004771}
4772
Douglas Gregorf968d832011-05-27 01:19:52 +00004773bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall5389f482010-12-30 14:05:53 +00004774 std::string& S) {
4775 // Encode result type.
4776 getObjCEncodingForType(Decl->getResultType(), S);
4777 CharUnits ParmOffset;
4778 // Compute size of all parameters.
4779 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4780 E = Decl->param_end(); PI != E; ++PI) {
4781 QualType PType = (*PI)->getType();
4782 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004783 if (sz.isZero())
Fariborz Jahanian7e68ba52012-06-29 22:54:56 +00004784 continue;
4785
David Chisnall5389f482010-12-30 14:05:53 +00004786 assert (sz.isPositive() &&
Douglas Gregorf968d832011-05-27 01:19:52 +00004787 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall5389f482010-12-30 14:05:53 +00004788 ParmOffset += sz;
4789 }
4790 S += charUnitsToString(ParmOffset);
4791 ParmOffset = CharUnits::Zero();
4792
4793 // Argument types.
4794 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4795 E = Decl->param_end(); PI != E; ++PI) {
4796 ParmVarDecl *PVDecl = *PI;
4797 QualType PType = PVDecl->getOriginalType();
4798 if (const ArrayType *AT =
4799 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4800 // Use array's original type only if it has known number of
4801 // elements.
4802 if (!isa<ConstantArrayType>(AT))
4803 PType = PVDecl->getType();
4804 } else if (PType->isFunctionType())
4805 PType = PVDecl->getType();
4806 getObjCEncodingForType(PType, S);
4807 S += charUnitsToString(ParmOffset);
4808 ParmOffset += getObjCEncodingTypeSize(PType);
4809 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004810
4811 return false;
David Chisnall5389f482010-12-30 14:05:53 +00004812}
4813
Bob Wilsondc8dab62011-11-30 01:57:58 +00004814/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4815/// method parameter or return type. If Extended, include class names and
4816/// block object types.
4817void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4818 QualType T, std::string& S,
4819 bool Extended) const {
4820 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4821 getObjCEncodingForTypeQualifier(QT, S);
4822 // Encode parameter type.
4823 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4824 true /*OutermostType*/,
4825 false /*EncodingProperty*/,
4826 false /*StructField*/,
4827 Extended /*EncodeBlockParameters*/,
4828 Extended /*EncodeClassNames*/);
4829}
4830
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004831/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004832/// declaration.
Douglas Gregorf968d832011-05-27 01:19:52 +00004833bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilsondc8dab62011-11-30 01:57:58 +00004834 std::string& S,
4835 bool Extended) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004836 // FIXME: This is not very efficient.
Bob Wilsondc8dab62011-11-30 01:57:58 +00004837 // Encode return type.
4838 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4839 Decl->getResultType(), S, Extended);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004840 // Compute size of all parameters.
4841 // Start with computing size of a pointer in number of bytes.
4842 // FIXME: There might(should) be a better way of doing this computation!
4843 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004844 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004845 // The first two arguments (self and _cmd) are pointers; account for
4846 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00004847 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004848 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004849 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00004850 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004851 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004852 if (sz.isZero())
Fariborz Jahanian7e68ba52012-06-29 22:54:56 +00004853 continue;
4854
Ken Dyck199c3d62010-01-11 17:06:35 +00004855 assert (sz.isPositive() &&
4856 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004857 ParmOffset += sz;
4858 }
Ken Dyck199c3d62010-01-11 17:06:35 +00004859 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004860 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00004861 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00004862
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004863 // Argument types.
4864 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004865 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004866 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004867 const ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00004868 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00004869 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00004870 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4871 // Use array's original type only if it has known number of
4872 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00004873 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00004874 PType = PVDecl->getType();
4875 } else if (PType->isFunctionType())
4876 PType = PVDecl->getType();
Bob Wilsondc8dab62011-11-30 01:57:58 +00004877 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4878 PType, S, Extended);
Ken Dyck199c3d62010-01-11 17:06:35 +00004879 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004880 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004881 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004882
4883 return false;
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004884}
4885
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004886/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004887/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004888/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4889/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00004890/// Property attributes are stored as a comma-delimited C string. The simple
4891/// attributes readonly and bycopy are encoded as single characters. The
4892/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4893/// encoded as single characters, followed by an identifier. Property types
4894/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004895/// these attributes are defined by the following enumeration:
4896/// @code
4897/// enum PropertyAttributes {
4898/// kPropertyReadOnly = 'R', // property is read-only.
4899/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4900/// kPropertyByref = '&', // property is a reference to the value last assigned
4901/// kPropertyDynamic = 'D', // property is dynamic
4902/// kPropertyGetter = 'G', // followed by getter selector name
4903/// kPropertySetter = 'S', // followed by setter selector name
4904/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson0d4cb852012-03-22 17:48:02 +00004905/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004906/// kPropertyWeak = 'W' // 'weak' property
4907/// kPropertyStrong = 'P' // property GC'able
4908/// kPropertyNonAtomic = 'N' // property non-atomic
4909/// };
4910/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00004911void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004912 const Decl *Container,
Jay Foad4ba2a172011-01-12 09:06:06 +00004913 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004914 // Collect information from the property implementation decl(s).
4915 bool Dynamic = false;
4916 ObjCPropertyImplDecl *SynthesizePID = 0;
4917
4918 // FIXME: Duplicated code due to poor abstraction.
4919 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00004920 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004921 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4922 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004923 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004924 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00004925 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004926 if (PID->getPropertyDecl() == PD) {
4927 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4928 Dynamic = true;
4929 } else {
4930 SynthesizePID = PID;
4931 }
4932 }
4933 }
4934 } else {
Chris Lattner61710852008-10-05 17:34:18 +00004935 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004936 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004937 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004938 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00004939 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004940 if (PID->getPropertyDecl() == PD) {
4941 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4942 Dynamic = true;
4943 } else {
4944 SynthesizePID = PID;
4945 }
4946 }
Mike Stump1eb44332009-09-09 15:08:12 +00004947 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004948 }
4949 }
4950
4951 // FIXME: This is not very efficient.
4952 S = "T";
4953
4954 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004955 // GCC has some special rules regarding encoding of properties which
4956 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00004957 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004958 true /* outermost type */,
4959 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004960
4961 if (PD->isReadOnly()) {
4962 S += ",R";
Nico Weberd7ceab32013-05-08 23:47:40 +00004963 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
4964 S += ",C";
4965 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
4966 S += ",&";
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004967 } else {
4968 switch (PD->getSetterKind()) {
4969 case ObjCPropertyDecl::Assign: break;
4970 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00004971 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian3a02b442011-08-12 20:47:08 +00004972 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004973 }
4974 }
4975
4976 // It really isn't clear at all what this means, since properties
4977 // are "dynamic by default".
4978 if (Dynamic)
4979 S += ",D";
4980
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004981 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4982 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00004983
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004984 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4985 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004986 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004987 }
4988
4989 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4990 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004991 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004992 }
4993
4994 if (SynthesizePID) {
4995 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4996 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00004997 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004998 }
4999
5000 // FIXME: OBJCGC: weak & strong
5001}
5002
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005003/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00005004/// Another legacy compatibility encoding: 32-bit longs are encoded as
5005/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005006/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5007///
5008void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00005009 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00005010 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad4ba2a172011-01-12 09:06:06 +00005011 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005012 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00005013 else
Jay Foad4ba2a172011-01-12 09:06:06 +00005014 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005015 PointeeTy = IntTy;
5016 }
5017 }
5018}
5019
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00005020void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad4ba2a172011-01-12 09:06:06 +00005021 const FieldDecl *Field) const {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00005022 // We follow the behavior of gcc, expanding structures which are
5023 // directly pointed to, and expanding embedded structures. Note that
5024 // these rules are sufficient to prevent recursive encoding of the
5025 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00005026 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00005027 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00005028}
5029
John McCall3624e9e2012-12-20 02:45:14 +00005030static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5031 BuiltinType::Kind kind) {
5032 switch (kind) {
David Chisnall64fd7e82010-06-04 01:10:52 +00005033 case BuiltinType::Void: return 'v';
5034 case BuiltinType::Bool: return 'B';
5035 case BuiltinType::Char_U:
5036 case BuiltinType::UChar: return 'C';
John McCall3624e9e2012-12-20 02:45:14 +00005037 case BuiltinType::Char16:
David Chisnall64fd7e82010-06-04 01:10:52 +00005038 case BuiltinType::UShort: return 'S';
John McCall3624e9e2012-12-20 02:45:14 +00005039 case BuiltinType::Char32:
David Chisnall64fd7e82010-06-04 01:10:52 +00005040 case BuiltinType::UInt: return 'I';
5041 case BuiltinType::ULong:
John McCall3624e9e2012-12-20 02:45:14 +00005042 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnall64fd7e82010-06-04 01:10:52 +00005043 case BuiltinType::UInt128: return 'T';
5044 case BuiltinType::ULongLong: return 'Q';
5045 case BuiltinType::Char_S:
5046 case BuiltinType::SChar: return 'c';
5047 case BuiltinType::Short: return 's';
Chris Lattner3f59c972010-12-25 23:25:43 +00005048 case BuiltinType::WChar_S:
5049 case BuiltinType::WChar_U:
David Chisnall64fd7e82010-06-04 01:10:52 +00005050 case BuiltinType::Int: return 'i';
5051 case BuiltinType::Long:
John McCall3624e9e2012-12-20 02:45:14 +00005052 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnall64fd7e82010-06-04 01:10:52 +00005053 case BuiltinType::LongLong: return 'q';
5054 case BuiltinType::Int128: return 't';
5055 case BuiltinType::Float: return 'f';
5056 case BuiltinType::Double: return 'd';
Daniel Dunbar3a0be842010-10-11 21:13:48 +00005057 case BuiltinType::LongDouble: return 'D';
John McCall3624e9e2012-12-20 02:45:14 +00005058 case BuiltinType::NullPtr: return '*'; // like char*
5059
5060 case BuiltinType::Half:
5061 // FIXME: potentially need @encodes for these!
5062 return ' ';
5063
5064 case BuiltinType::ObjCId:
5065 case BuiltinType::ObjCClass:
5066 case BuiltinType::ObjCSel:
5067 llvm_unreachable("@encoding ObjC primitive type");
5068
5069 // OpenCL and placeholder types don't need @encodings.
5070 case BuiltinType::OCLImage1d:
5071 case BuiltinType::OCLImage1dArray:
5072 case BuiltinType::OCLImage1dBuffer:
5073 case BuiltinType::OCLImage2d:
5074 case BuiltinType::OCLImage2dArray:
5075 case BuiltinType::OCLImage3d:
Guy Benyeie6b9d802013-01-20 12:31:11 +00005076 case BuiltinType::OCLEvent:
Guy Benyei21f18c42013-02-07 10:55:47 +00005077 case BuiltinType::OCLSampler:
John McCall3624e9e2012-12-20 02:45:14 +00005078 case BuiltinType::Dependent:
5079#define BUILTIN_TYPE(KIND, ID)
5080#define PLACEHOLDER_TYPE(KIND, ID) \
5081 case BuiltinType::KIND:
5082#include "clang/AST/BuiltinTypes.def"
5083 llvm_unreachable("invalid builtin type for @encode");
David Chisnall64fd7e82010-06-04 01:10:52 +00005084 }
David Blaikie719e53f2013-01-09 17:48:41 +00005085 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnall64fd7e82010-06-04 01:10:52 +00005086}
5087
Douglas Gregor5471bc82011-09-08 17:18:35 +00005088static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5089 EnumDecl *Enum = ET->getDecl();
5090
5091 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5092 if (!Enum->isFixed())
5093 return 'i';
5094
5095 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall3624e9e2012-12-20 02:45:14 +00005096 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5097 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor5471bc82011-09-08 17:18:35 +00005098}
5099
Jay Foad4ba2a172011-01-12 09:06:06 +00005100static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00005101 QualType T, const FieldDecl *FD) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005102 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00005103 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00005104 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5105 // The GNU runtime requires more information; bitfields are encoded as b,
5106 // then the offset (in bits) of the first element, then the type of the
5107 // bitfield, then the size in bits. For example, in this structure:
5108 //
5109 // struct
5110 // {
5111 // int integer;
5112 // int flags:2;
5113 // };
5114 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5115 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5116 // information is not especially sensible, but we're stuck with it for
5117 // compatibility with GCC, although providing it breaks anything that
5118 // actually uses runtime introspection and wants to work on both runtimes...
John McCall260611a2012-06-20 06:18:46 +00005119 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnall64fd7e82010-06-04 01:10:52 +00005120 const RecordDecl *RD = FD->getParent();
5121 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedman82905742011-07-07 01:54:01 +00005122 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor5471bc82011-09-08 17:18:35 +00005123 if (const EnumType *ET = T->getAs<EnumType>())
5124 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall3624e9e2012-12-20 02:45:14 +00005125 else {
5126 const BuiltinType *BT = T->castAs<BuiltinType>();
5127 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5128 }
David Chisnall64fd7e82010-06-04 01:10:52 +00005129 }
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005130 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00005131}
5132
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00005133// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00005134void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5135 bool ExpandPointedToStructures,
5136 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00005137 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00005138 bool OutermostType,
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005139 bool EncodingProperty,
Bob Wilsondc8dab62011-11-30 01:57:58 +00005140 bool StructField,
5141 bool EncodeBlockParameters,
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005142 bool EncodeClassNames,
5143 bool EncodePointerToObjCTypedef) const {
John McCall3624e9e2012-12-20 02:45:14 +00005144 CanQualType CT = getCanonicalType(T);
5145 switch (CT->getTypeClass()) {
5146 case Type::Builtin:
5147 case Type::Enum:
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005148 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00005149 return EncodeBitField(this, S, T, FD);
John McCall3624e9e2012-12-20 02:45:14 +00005150 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5151 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5152 else
5153 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005154 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005155
John McCall3624e9e2012-12-20 02:45:14 +00005156 case Type::Complex: {
5157 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlssonc612f7b2009-04-09 21:55:45 +00005158 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00005159 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00005160 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005161 return;
5162 }
John McCall3624e9e2012-12-20 02:45:14 +00005163
5164 case Type::Atomic: {
5165 const AtomicType *AT = T->castAs<AtomicType>();
5166 S += 'A';
5167 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, 0,
5168 false, false);
5169 return;
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00005170 }
John McCall3624e9e2012-12-20 02:45:14 +00005171
5172 // encoding for pointer or reference types.
5173 case Type::Pointer:
5174 case Type::LValueReference:
5175 case Type::RValueReference: {
5176 QualType PointeeTy;
5177 if (isa<PointerType>(CT)) {
5178 const PointerType *PT = T->castAs<PointerType>();
5179 if (PT->isObjCSelType()) {
5180 S += ':';
5181 return;
5182 }
5183 PointeeTy = PT->getPointeeType();
5184 } else {
5185 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5186 }
5187
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005188 bool isReadOnly = false;
5189 // For historical/compatibility reasons, the read-only qualifier of the
5190 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5191 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00005192 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00005193 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005194 if (OutermostType && T.isConstQualified()) {
5195 isReadOnly = true;
5196 S += 'r';
5197 }
Mike Stump9fdbab32009-07-31 02:02:20 +00005198 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005199 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00005200 while (P->getAs<PointerType>())
5201 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005202 if (P.isConstQualified()) {
5203 isReadOnly = true;
5204 S += 'r';
5205 }
5206 }
5207 if (isReadOnly) {
5208 // Another legacy compatibility encoding. Some ObjC qualifier and type
5209 // combinations need to be rearranged.
5210 // Rewrite "in const" from "nr" to "rn"
Chris Lattner5f9e2722011-07-23 10:55:15 +00005211 if (StringRef(S).endswith("nr"))
Benjamin Kramer02379412010-04-27 17:12:11 +00005212 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005213 }
Mike Stump1eb44332009-09-09 15:08:12 +00005214
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005215 if (PointeeTy->isCharType()) {
5216 // char pointer types should be encoded as '*' unless it is a
5217 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00005218 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005219 S += '*';
5220 return;
5221 }
Ted Kremenek6217b802009-07-29 21:53:49 +00005222 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00005223 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5224 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5225 S += '#';
5226 return;
5227 }
5228 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5229 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5230 S += '@';
5231 return;
5232 }
5233 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005234 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005235 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00005236 getLegacyIntegralTypeEncoding(PointeeTy);
5237
Mike Stump1eb44332009-09-09 15:08:12 +00005238 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005239 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005240 return;
5241 }
John McCall3624e9e2012-12-20 02:45:14 +00005242
5243 case Type::ConstantArray:
5244 case Type::IncompleteArray:
5245 case Type::VariableArray: {
5246 const ArrayType *AT = cast<ArrayType>(CT);
5247
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005248 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlsson559a8332009-02-22 01:38:57 +00005249 // Incomplete arrays are encoded as a pointer to the array element.
5250 S += '^';
5251
Mike Stump1eb44332009-09-09 15:08:12 +00005252 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00005253 false, ExpandStructures, FD);
5254 } else {
5255 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00005256
Fariborz Jahanian48eff6c2013-06-04 16:04:37 +00005257 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5258 S += llvm::utostr(CAT->getSize().getZExtValue());
5259 else {
Anders Carlsson559a8332009-02-22 01:38:57 +00005260 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005261 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5262 "Unknown array type!");
Anders Carlsson559a8332009-02-22 01:38:57 +00005263 S += '0';
5264 }
Mike Stump1eb44332009-09-09 15:08:12 +00005265
5266 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00005267 false, ExpandStructures, FD);
5268 S += ']';
5269 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005270 return;
5271 }
Mike Stump1eb44332009-09-09 15:08:12 +00005272
John McCall3624e9e2012-12-20 02:45:14 +00005273 case Type::FunctionNoProto:
5274 case Type::FunctionProto:
Anders Carlssonc0a87b72007-10-30 00:06:20 +00005275 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005276 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005277
John McCall3624e9e2012-12-20 02:45:14 +00005278 case Type::Record: {
5279 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005280 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00005281 // Anonymous structures print as '?'
5282 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5283 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00005284 if (ClassTemplateSpecializationDecl *Spec
5285 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5286 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer5eada842013-02-22 15:46:01 +00005287 llvm::raw_string_ostream OS(S);
5288 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor910f8002010-11-07 23:05:16 +00005289 TemplateArgs.data(),
5290 TemplateArgs.size(),
Douglas Gregor30c42402011-09-27 22:38:19 +00005291 (*this).getPrintingPolicy());
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00005292 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00005293 } else {
5294 S += '?';
5295 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00005296 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00005297 S += '=';
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005298 if (!RDecl->isUnion()) {
5299 getObjCEncodingForStructureImpl(RDecl, S, FD);
5300 } else {
5301 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5302 FieldEnd = RDecl->field_end();
5303 Field != FieldEnd; ++Field) {
5304 if (FD) {
5305 S += '"';
5306 S += Field->getNameAsString();
5307 S += '"';
5308 }
Mike Stump1eb44332009-09-09 15:08:12 +00005309
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005310 // Special case bit-fields.
5311 if (Field->isBitField()) {
5312 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie581deb32012-06-06 20:45:41 +00005313 *Field);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005314 } else {
5315 QualType qt = Field->getType();
5316 getLegacyIntegralTypeEncoding(qt);
5317 getObjCEncodingForTypeImpl(qt, S, false, true,
5318 FD, /*OutermostType*/false,
5319 /*EncodingProperty*/false,
5320 /*StructField*/true);
5321 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005322 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00005323 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00005324 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00005325 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005326 return;
5327 }
Mike Stump1eb44332009-09-09 15:08:12 +00005328
John McCall3624e9e2012-12-20 02:45:14 +00005329 case Type::BlockPointer: {
5330 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff21a98b12009-02-02 18:24:29 +00005331 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilsondc8dab62011-11-30 01:57:58 +00005332 if (EncodeBlockParameters) {
John McCall3624e9e2012-12-20 02:45:14 +00005333 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilsondc8dab62011-11-30 01:57:58 +00005334
5335 S += '<';
5336 // Block return type
5337 getObjCEncodingForTypeImpl(FT->getResultType(), S,
5338 ExpandPointedToStructures, ExpandStructures,
5339 FD,
5340 false /* OutermostType */,
5341 EncodingProperty,
5342 false /* StructField */,
5343 EncodeBlockParameters,
5344 EncodeClassNames);
5345 // Block self
5346 S += "@?";
5347 // Block parameters
5348 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
5349 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
5350 E = FPT->arg_type_end(); I && (I != E); ++I) {
5351 getObjCEncodingForTypeImpl(*I, S,
5352 ExpandPointedToStructures,
5353 ExpandStructures,
5354 FD,
5355 false /* OutermostType */,
5356 EncodingProperty,
5357 false /* StructField */,
5358 EncodeBlockParameters,
5359 EncodeClassNames);
5360 }
5361 }
5362 S += '>';
5363 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005364 return;
5365 }
Mike Stump1eb44332009-09-09 15:08:12 +00005366
John McCall3624e9e2012-12-20 02:45:14 +00005367 case Type::ObjCObject:
5368 case Type::ObjCInterface: {
5369 // Ignore protocol qualifiers when mangling at this level.
5370 T = T->castAs<ObjCObjectType>()->getBaseType();
John McCallc12c5bb2010-05-15 11:32:37 +00005371
John McCall3624e9e2012-12-20 02:45:14 +00005372 // The assumption seems to be that this assert will succeed
5373 // because nested levels will have filtered out 'id' and 'Class'.
5374 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005375 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00005376 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005377 S += '{';
5378 const IdentifierInfo *II = OI->getIdentifier();
5379 S += II->getName();
5380 S += '=';
Jordy Rosedb8264e2011-07-22 02:08:32 +00005381 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00005382 DeepCollectObjCIvars(OI, true, Ivars);
5383 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00005384 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00005385 if (Field->isBitField())
5386 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005387 else
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005388 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5389 false, false, false, false, false,
5390 EncodePointerToObjCTypedef);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005391 }
5392 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005393 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00005394 }
Mike Stump1eb44332009-09-09 15:08:12 +00005395
John McCall3624e9e2012-12-20 02:45:14 +00005396 case Type::ObjCObjectPointer: {
5397 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff14108da2009-07-10 23:34:53 +00005398 if (OPT->isObjCIdType()) {
5399 S += '@';
5400 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005401 }
Mike Stump1eb44332009-09-09 15:08:12 +00005402
Steve Naroff27d20a22009-10-28 22:03:49 +00005403 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5404 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5405 // Since this is a binary compatibility issue, need to consult with runtime
5406 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00005407 S += '#';
5408 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005409 }
Mike Stump1eb44332009-09-09 15:08:12 +00005410
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005411 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005412 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00005413 ExpandPointedToStructures,
5414 ExpandStructures, FD);
Bob Wilsondc8dab62011-11-30 01:57:58 +00005415 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff14108da2009-07-10 23:34:53 +00005416 // Note that we do extended encoding of protocol qualifer list
5417 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00005418 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005419 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5420 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00005421 S += '<';
5422 S += (*I)->getNameAsString();
5423 S += '>';
5424 }
5425 S += '"';
5426 }
5427 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005428 }
Mike Stump1eb44332009-09-09 15:08:12 +00005429
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005430 QualType PointeeTy = OPT->getPointeeType();
5431 if (!EncodingProperty &&
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005432 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5433 !EncodePointerToObjCTypedef) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005434 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00005435 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005436 // {...};
5437 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00005438 getObjCEncodingForTypeImpl(PointeeTy, S,
5439 false, ExpandPointedToStructures,
Fariborz Jahanian17c1a2e2013-02-15 21:14:50 +00005440 NULL,
5441 false, false, false, false, false,
5442 /*EncodePointerToObjCTypedef*/true);
Steve Naroff14108da2009-07-10 23:34:53 +00005443 return;
5444 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005445
5446 S += '@';
Bob Wilsondc8dab62011-11-30 01:57:58 +00005447 if (OPT->getInterfaceDecl() &&
5448 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005449 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00005450 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00005451 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5452 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005453 S += '<';
5454 S += (*I)->getNameAsString();
5455 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00005456 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00005457 S += '"';
5458 }
5459 return;
5460 }
Mike Stump1eb44332009-09-09 15:08:12 +00005461
John McCall532ec7b2010-05-17 23:56:34 +00005462 // gcc just blithely ignores member pointers.
John McCall3624e9e2012-12-20 02:45:14 +00005463 // FIXME: we shoul do better than that. 'M' is available.
5464 case Type::MemberPointer:
John McCall532ec7b2010-05-17 23:56:34 +00005465 return;
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005466
John McCall3624e9e2012-12-20 02:45:14 +00005467 case Type::Vector:
5468 case Type::ExtVector:
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005469 // This matches gcc's encoding, even though technically it is
5470 // insufficient.
5471 // FIXME. We should do a better job than gcc.
5472 return;
John McCall3624e9e2012-12-20 02:45:14 +00005473
Richard Smithdc7a4f52013-04-30 13:56:41 +00005474 case Type::Auto:
5475 // We could see an undeduced auto type here during error recovery.
5476 // Just ignore it.
5477 return;
5478
John McCall3624e9e2012-12-20 02:45:14 +00005479#define ABSTRACT_TYPE(KIND, BASE)
5480#define TYPE(KIND, BASE)
5481#define DEPENDENT_TYPE(KIND, BASE) \
5482 case Type::KIND:
5483#define NON_CANONICAL_TYPE(KIND, BASE) \
5484 case Type::KIND:
5485#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5486 case Type::KIND:
5487#include "clang/AST/TypeNodes.def"
5488 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00005489 }
John McCall3624e9e2012-12-20 02:45:14 +00005490 llvm_unreachable("bad type kind!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00005491}
5492
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005493void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5494 std::string &S,
5495 const FieldDecl *FD,
5496 bool includeVBases) const {
5497 assert(RDecl && "Expected non-null RecordDecl");
5498 assert(!RDecl->isUnion() && "Should not be called for unions");
5499 if (!RDecl->getDefinition())
5500 return;
5501
5502 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5503 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5504 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5505
5506 if (CXXRec) {
5507 for (CXXRecordDecl::base_class_iterator
5508 BI = CXXRec->bases_begin(),
5509 BE = CXXRec->bases_end(); BI != BE; ++BI) {
5510 if (!BI->isVirtual()) {
5511 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005512 if (base->isEmpty())
5513 continue;
Benjamin Kramerd4f51982012-07-04 18:45:14 +00005514 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005515 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5516 std::make_pair(offs, base));
5517 }
5518 }
5519 }
5520
5521 unsigned i = 0;
5522 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5523 FieldEnd = RDecl->field_end();
5524 Field != FieldEnd; ++Field, ++i) {
5525 uint64_t offs = layout.getFieldOffset(i);
5526 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie581deb32012-06-06 20:45:41 +00005527 std::make_pair(offs, *Field));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005528 }
5529
5530 if (CXXRec && includeVBases) {
5531 for (CXXRecordDecl::base_class_iterator
5532 BI = CXXRec->vbases_begin(),
5533 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
5534 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005535 if (base->isEmpty())
5536 continue;
Benjamin Kramerd4f51982012-07-04 18:45:14 +00005537 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Argyrios Kyrtzidis19aa8602011-09-26 18:14:24 +00005538 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
5539 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5540 std::make_pair(offs, base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005541 }
5542 }
5543
5544 CharUnits size;
5545 if (CXXRec) {
5546 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5547 } else {
5548 size = layout.getSize();
5549 }
5550
5551 uint64_t CurOffs = 0;
5552 std::multimap<uint64_t, NamedDecl *>::iterator
5553 CurLayObj = FieldOrBaseOffsets.begin();
5554
Douglas Gregor58db7a52012-04-27 22:30:01 +00005555 if (CXXRec && CXXRec->isDynamicClass() &&
5556 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005557 if (FD) {
5558 S += "\"_vptr$";
5559 std::string recname = CXXRec->getNameAsString();
5560 if (recname.empty()) recname = "?";
5561 S += recname;
5562 S += '"';
5563 }
5564 S += "^^?";
5565 CurOffs += getTypeSize(VoidPtrTy);
5566 }
5567
5568 if (!RDecl->hasFlexibleArrayMember()) {
5569 // Mark the end of the structure.
5570 uint64_t offs = toBits(size);
5571 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5572 std::make_pair(offs, (NamedDecl*)0));
5573 }
5574
5575 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5576 assert(CurOffs <= CurLayObj->first);
5577
5578 if (CurOffs < CurLayObj->first) {
5579 uint64_t padding = CurLayObj->first - CurOffs;
5580 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5581 // packing/alignment of members is different that normal, in which case
5582 // the encoding will be out-of-sync with the real layout.
5583 // If the runtime switches to just consider the size of types without
5584 // taking into account alignment, we could make padding explicit in the
5585 // encoding (e.g. using arrays of chars). The encoding strings would be
5586 // longer then though.
5587 CurOffs += padding;
5588 }
5589
5590 NamedDecl *dcl = CurLayObj->second;
5591 if (dcl == 0)
5592 break; // reached end of structure.
5593
5594 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5595 // We expand the bases without their virtual bases since those are going
5596 // in the initial structure. Note that this differs from gcc which
5597 // expands virtual bases each time one is encountered in the hierarchy,
5598 // making the encoding type bigger than it really is.
5599 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00005600 assert(!base->isEmpty());
5601 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005602 } else {
5603 FieldDecl *field = cast<FieldDecl>(dcl);
5604 if (FD) {
5605 S += '"';
5606 S += field->getNameAsString();
5607 S += '"';
5608 }
5609
5610 if (field->isBitField()) {
5611 EncodeBitField(this, S, field->getType(), field);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005612 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00005613 } else {
5614 QualType qt = field->getType();
5615 getLegacyIntegralTypeEncoding(qt);
5616 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5617 /*OutermostType*/false,
5618 /*EncodingProperty*/false,
5619 /*StructField*/true);
5620 CurOffs += getTypeSize(field->getType());
5621 }
5622 }
5623 }
5624}
5625
Mike Stump1eb44332009-09-09 15:08:12 +00005626void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00005627 std::string& S) const {
5628 if (QT & Decl::OBJC_TQ_In)
5629 S += 'n';
5630 if (QT & Decl::OBJC_TQ_Inout)
5631 S += 'N';
5632 if (QT & Decl::OBJC_TQ_Out)
5633 S += 'o';
5634 if (QT & Decl::OBJC_TQ_Bycopy)
5635 S += 'O';
5636 if (QT & Decl::OBJC_TQ_Byref)
5637 S += 'R';
5638 if (QT & Decl::OBJC_TQ_Oneway)
5639 S += 'V';
5640}
5641
Douglas Gregor4dfd02a2011-08-12 05:46:01 +00005642TypedefDecl *ASTContext::getObjCIdDecl() const {
5643 if (!ObjCIdDecl) {
5644 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5645 T = getObjCObjectPointerType(T);
5646 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
5647 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5648 getTranslationUnitDecl(),
5649 SourceLocation(), SourceLocation(),
5650 &Idents.get("id"), IdInfo);
5651 }
5652
5653 return ObjCIdDecl;
Steve Naroff7e219e42007-10-15 14:41:52 +00005654}
5655
Douglas Gregor7a27ea52011-08-12 06:17:30 +00005656TypedefDecl *ASTContext::getObjCSelDecl() const {
5657 if (!ObjCSelDecl) {
5658 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5659 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5660 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5661 getTranslationUnitDecl(),
5662 SourceLocation(), SourceLocation(),
5663 &Idents.get("SEL"), SelInfo);
5664 }
5665 return ObjCSelDecl;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00005666}
5667
Douglas Gregor79d67262011-08-12 05:59:41 +00005668TypedefDecl *ASTContext::getObjCClassDecl() const {
5669 if (!ObjCClassDecl) {
5670 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5671 T = getObjCObjectPointerType(T);
5672 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5673 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5674 getTranslationUnitDecl(),
5675 SourceLocation(), SourceLocation(),
5676 &Idents.get("Class"), ClassInfo);
5677 }
5678
5679 return ObjCClassDecl;
Anders Carlsson8baaca52007-10-31 02:53:19 +00005680}
5681
Douglas Gregora6ea10e2012-01-17 18:09:05 +00005682ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5683 if (!ObjCProtocolClassDecl) {
5684 ObjCProtocolClassDecl
5685 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5686 SourceLocation(),
5687 &Idents.get("Protocol"),
5688 /*PrevDecl=*/0,
5689 SourceLocation(), true);
5690 }
5691
5692 return ObjCProtocolClassDecl;
5693}
5694
Meador Ingec5613b22012-06-16 03:34:49 +00005695//===----------------------------------------------------------------------===//
5696// __builtin_va_list Construction Functions
5697//===----------------------------------------------------------------------===//
5698
5699static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5700 // typedef char* __builtin_va_list;
5701 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5702 TypeSourceInfo *TInfo
5703 = Context->getTrivialTypeSourceInfo(CharPtrType);
5704
5705 TypedefDecl *VaListTypeDecl
5706 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5707 Context->getTranslationUnitDecl(),
5708 SourceLocation(), SourceLocation(),
5709 &Context->Idents.get("__builtin_va_list"),
5710 TInfo);
5711 return VaListTypeDecl;
5712}
5713
5714static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5715 // typedef void* __builtin_va_list;
5716 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5717 TypeSourceInfo *TInfo
5718 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5719
5720 TypedefDecl *VaListTypeDecl
5721 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5722 Context->getTranslationUnitDecl(),
5723 SourceLocation(), SourceLocation(),
5724 &Context->Idents.get("__builtin_va_list"),
5725 TInfo);
5726 return VaListTypeDecl;
5727}
5728
Tim Northoverc264e162013-01-31 12:13:10 +00005729static TypedefDecl *
5730CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
5731 RecordDecl *VaListTagDecl;
5732 if (Context->getLangOpts().CPlusPlus) {
5733 // namespace std { struct __va_list {
5734 NamespaceDecl *NS;
5735 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5736 Context->getTranslationUnitDecl(),
5737 /*Inline*/false, SourceLocation(),
5738 SourceLocation(), &Context->Idents.get("std"),
5739 /*PrevDecl*/0);
5740
5741 VaListTagDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5742 Context->getTranslationUnitDecl(),
5743 SourceLocation(), SourceLocation(),
5744 &Context->Idents.get("__va_list"));
5745 VaListTagDecl->setDeclContext(NS);
5746 } else {
5747 // struct __va_list
5748 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5749 Context->getTranslationUnitDecl(),
5750 &Context->Idents.get("__va_list"));
5751 }
5752
5753 VaListTagDecl->startDefinition();
5754
5755 const size_t NumFields = 5;
5756 QualType FieldTypes[NumFields];
5757 const char *FieldNames[NumFields];
5758
5759 // void *__stack;
5760 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
5761 FieldNames[0] = "__stack";
5762
5763 // void *__gr_top;
5764 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
5765 FieldNames[1] = "__gr_top";
5766
5767 // void *__vr_top;
5768 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5769 FieldNames[2] = "__vr_top";
5770
5771 // int __gr_offs;
5772 FieldTypes[3] = Context->IntTy;
5773 FieldNames[3] = "__gr_offs";
5774
5775 // int __vr_offs;
5776 FieldTypes[4] = Context->IntTy;
5777 FieldNames[4] = "__vr_offs";
5778
5779 // Create fields
5780 for (unsigned i = 0; i < NumFields; ++i) {
5781 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5782 VaListTagDecl,
5783 SourceLocation(),
5784 SourceLocation(),
5785 &Context->Idents.get(FieldNames[i]),
5786 FieldTypes[i], /*TInfo=*/0,
5787 /*BitWidth=*/0,
5788 /*Mutable=*/false,
5789 ICIS_NoInit);
5790 Field->setAccess(AS_public);
5791 VaListTagDecl->addDecl(Field);
5792 }
5793 VaListTagDecl->completeDefinition();
5794 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5795 Context->VaListTagTy = VaListTagType;
5796
5797 // } __builtin_va_list;
5798 TypedefDecl *VaListTypedefDecl
5799 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5800 Context->getTranslationUnitDecl(),
5801 SourceLocation(), SourceLocation(),
5802 &Context->Idents.get("__builtin_va_list"),
5803 Context->getTrivialTypeSourceInfo(VaListTagType));
5804
5805 return VaListTypedefDecl;
5806}
5807
Meador Ingec5613b22012-06-16 03:34:49 +00005808static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5809 // typedef struct __va_list_tag {
5810 RecordDecl *VaListTagDecl;
5811
5812 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5813 Context->getTranslationUnitDecl(),
5814 &Context->Idents.get("__va_list_tag"));
5815 VaListTagDecl->startDefinition();
5816
5817 const size_t NumFields = 5;
5818 QualType FieldTypes[NumFields];
5819 const char *FieldNames[NumFields];
5820
5821 // unsigned char gpr;
5822 FieldTypes[0] = Context->UnsignedCharTy;
5823 FieldNames[0] = "gpr";
5824
5825 // unsigned char fpr;
5826 FieldTypes[1] = Context->UnsignedCharTy;
5827 FieldNames[1] = "fpr";
5828
5829 // unsigned short reserved;
5830 FieldTypes[2] = Context->UnsignedShortTy;
5831 FieldNames[2] = "reserved";
5832
5833 // void* overflow_arg_area;
5834 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5835 FieldNames[3] = "overflow_arg_area";
5836
5837 // void* reg_save_area;
5838 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5839 FieldNames[4] = "reg_save_area";
5840
5841 // Create fields
5842 for (unsigned i = 0; i < NumFields; ++i) {
5843 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5844 SourceLocation(),
5845 SourceLocation(),
5846 &Context->Idents.get(FieldNames[i]),
5847 FieldTypes[i], /*TInfo=*/0,
5848 /*BitWidth=*/0,
5849 /*Mutable=*/false,
5850 ICIS_NoInit);
5851 Field->setAccess(AS_public);
5852 VaListTagDecl->addDecl(Field);
5853 }
5854 VaListTagDecl->completeDefinition();
5855 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingefb40e3f2012-07-01 15:57:25 +00005856 Context->VaListTagTy = VaListTagType;
Meador Ingec5613b22012-06-16 03:34:49 +00005857
5858 // } __va_list_tag;
5859 TypedefDecl *VaListTagTypedefDecl
5860 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5861 Context->getTranslationUnitDecl(),
5862 SourceLocation(), SourceLocation(),
5863 &Context->Idents.get("__va_list_tag"),
5864 Context->getTrivialTypeSourceInfo(VaListTagType));
5865 QualType VaListTagTypedefType =
5866 Context->getTypedefType(VaListTagTypedefDecl);
5867
5868 // typedef __va_list_tag __builtin_va_list[1];
5869 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5870 QualType VaListTagArrayType
5871 = Context->getConstantArrayType(VaListTagTypedefType,
5872 Size, ArrayType::Normal, 0);
5873 TypeSourceInfo *TInfo
5874 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5875 TypedefDecl *VaListTypedefDecl
5876 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5877 Context->getTranslationUnitDecl(),
5878 SourceLocation(), SourceLocation(),
5879 &Context->Idents.get("__builtin_va_list"),
5880 TInfo);
5881
5882 return VaListTypedefDecl;
5883}
5884
5885static TypedefDecl *
5886CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5887 // typedef struct __va_list_tag {
5888 RecordDecl *VaListTagDecl;
5889 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5890 Context->getTranslationUnitDecl(),
5891 &Context->Idents.get("__va_list_tag"));
5892 VaListTagDecl->startDefinition();
5893
5894 const size_t NumFields = 4;
5895 QualType FieldTypes[NumFields];
5896 const char *FieldNames[NumFields];
5897
5898 // unsigned gp_offset;
5899 FieldTypes[0] = Context->UnsignedIntTy;
5900 FieldNames[0] = "gp_offset";
5901
5902 // unsigned fp_offset;
5903 FieldTypes[1] = Context->UnsignedIntTy;
5904 FieldNames[1] = "fp_offset";
5905
5906 // void* overflow_arg_area;
5907 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5908 FieldNames[2] = "overflow_arg_area";
5909
5910 // void* reg_save_area;
5911 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5912 FieldNames[3] = "reg_save_area";
5913
5914 // Create fields
5915 for (unsigned i = 0; i < NumFields; ++i) {
5916 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5917 VaListTagDecl,
5918 SourceLocation(),
5919 SourceLocation(),
5920 &Context->Idents.get(FieldNames[i]),
5921 FieldTypes[i], /*TInfo=*/0,
5922 /*BitWidth=*/0,
5923 /*Mutable=*/false,
5924 ICIS_NoInit);
5925 Field->setAccess(AS_public);
5926 VaListTagDecl->addDecl(Field);
5927 }
5928 VaListTagDecl->completeDefinition();
5929 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingefb40e3f2012-07-01 15:57:25 +00005930 Context->VaListTagTy = VaListTagType;
Meador Ingec5613b22012-06-16 03:34:49 +00005931
5932 // } __va_list_tag;
5933 TypedefDecl *VaListTagTypedefDecl
5934 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5935 Context->getTranslationUnitDecl(),
5936 SourceLocation(), SourceLocation(),
5937 &Context->Idents.get("__va_list_tag"),
5938 Context->getTrivialTypeSourceInfo(VaListTagType));
5939 QualType VaListTagTypedefType =
5940 Context->getTypedefType(VaListTagTypedefDecl);
5941
5942 // typedef __va_list_tag __builtin_va_list[1];
5943 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5944 QualType VaListTagArrayType
5945 = Context->getConstantArrayType(VaListTagTypedefType,
5946 Size, ArrayType::Normal,0);
5947 TypeSourceInfo *TInfo
5948 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5949 TypedefDecl *VaListTypedefDecl
5950 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5951 Context->getTranslationUnitDecl(),
5952 SourceLocation(), SourceLocation(),
5953 &Context->Idents.get("__builtin_va_list"),
5954 TInfo);
5955
5956 return VaListTypedefDecl;
5957}
5958
5959static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5960 // typedef int __builtin_va_list[4];
5961 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5962 QualType IntArrayType
5963 = Context->getConstantArrayType(Context->IntTy,
5964 Size, ArrayType::Normal, 0);
5965 TypedefDecl *VaListTypedefDecl
5966 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5967 Context->getTranslationUnitDecl(),
5968 SourceLocation(), SourceLocation(),
5969 &Context->Idents.get("__builtin_va_list"),
5970 Context->getTrivialTypeSourceInfo(IntArrayType));
5971
5972 return VaListTypedefDecl;
5973}
5974
Logan Chieneae5a8202012-10-10 06:56:20 +00005975static TypedefDecl *
5976CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
5977 RecordDecl *VaListDecl;
5978 if (Context->getLangOpts().CPlusPlus) {
5979 // namespace std { struct __va_list {
5980 NamespaceDecl *NS;
5981 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5982 Context->getTranslationUnitDecl(),
5983 /*Inline*/false, SourceLocation(),
5984 SourceLocation(), &Context->Idents.get("std"),
5985 /*PrevDecl*/0);
5986
5987 VaListDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5988 Context->getTranslationUnitDecl(),
5989 SourceLocation(), SourceLocation(),
5990 &Context->Idents.get("__va_list"));
5991
5992 VaListDecl->setDeclContext(NS);
5993
5994 } else {
5995 // struct __va_list {
5996 VaListDecl = CreateRecordDecl(*Context, TTK_Struct,
5997 Context->getTranslationUnitDecl(),
5998 &Context->Idents.get("__va_list"));
5999 }
6000
6001 VaListDecl->startDefinition();
6002
6003 // void * __ap;
6004 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6005 VaListDecl,
6006 SourceLocation(),
6007 SourceLocation(),
6008 &Context->Idents.get("__ap"),
6009 Context->getPointerType(Context->VoidTy),
6010 /*TInfo=*/0,
6011 /*BitWidth=*/0,
6012 /*Mutable=*/false,
6013 ICIS_NoInit);
6014 Field->setAccess(AS_public);
6015 VaListDecl->addDecl(Field);
6016
6017 // };
6018 VaListDecl->completeDefinition();
6019
6020 // typedef struct __va_list __builtin_va_list;
6021 TypeSourceInfo *TInfo
6022 = Context->getTrivialTypeSourceInfo(Context->getRecordType(VaListDecl));
6023
6024 TypedefDecl *VaListTypeDecl
6025 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6026 Context->getTranslationUnitDecl(),
6027 SourceLocation(), SourceLocation(),
6028 &Context->Idents.get("__builtin_va_list"),
6029 TInfo);
6030
6031 return VaListTypeDecl;
6032}
6033
Ulrich Weigandb8409212013-05-06 16:26:41 +00006034static TypedefDecl *
6035CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
6036 // typedef struct __va_list_tag {
6037 RecordDecl *VaListTagDecl;
6038 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
6039 Context->getTranslationUnitDecl(),
6040 &Context->Idents.get("__va_list_tag"));
6041 VaListTagDecl->startDefinition();
6042
6043 const size_t NumFields = 4;
6044 QualType FieldTypes[NumFields];
6045 const char *FieldNames[NumFields];
6046
6047 // long __gpr;
6048 FieldTypes[0] = Context->LongTy;
6049 FieldNames[0] = "__gpr";
6050
6051 // long __fpr;
6052 FieldTypes[1] = Context->LongTy;
6053 FieldNames[1] = "__fpr";
6054
6055 // void *__overflow_arg_area;
6056 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6057 FieldNames[2] = "__overflow_arg_area";
6058
6059 // void *__reg_save_area;
6060 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6061 FieldNames[3] = "__reg_save_area";
6062
6063 // Create fields
6064 for (unsigned i = 0; i < NumFields; ++i) {
6065 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6066 VaListTagDecl,
6067 SourceLocation(),
6068 SourceLocation(),
6069 &Context->Idents.get(FieldNames[i]),
6070 FieldTypes[i], /*TInfo=*/0,
6071 /*BitWidth=*/0,
6072 /*Mutable=*/false,
6073 ICIS_NoInit);
6074 Field->setAccess(AS_public);
6075 VaListTagDecl->addDecl(Field);
6076 }
6077 VaListTagDecl->completeDefinition();
6078 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6079 Context->VaListTagTy = VaListTagType;
6080
6081 // } __va_list_tag;
6082 TypedefDecl *VaListTagTypedefDecl
6083 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6084 Context->getTranslationUnitDecl(),
6085 SourceLocation(), SourceLocation(),
6086 &Context->Idents.get("__va_list_tag"),
6087 Context->getTrivialTypeSourceInfo(VaListTagType));
6088 QualType VaListTagTypedefType =
6089 Context->getTypedefType(VaListTagTypedefDecl);
6090
6091 // typedef __va_list_tag __builtin_va_list[1];
6092 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6093 QualType VaListTagArrayType
6094 = Context->getConstantArrayType(VaListTagTypedefType,
6095 Size, ArrayType::Normal,0);
6096 TypeSourceInfo *TInfo
6097 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
6098 TypedefDecl *VaListTypedefDecl
6099 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6100 Context->getTranslationUnitDecl(),
6101 SourceLocation(), SourceLocation(),
6102 &Context->Idents.get("__builtin_va_list"),
6103 TInfo);
6104
6105 return VaListTypedefDecl;
6106}
6107
Meador Ingec5613b22012-06-16 03:34:49 +00006108static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6109 TargetInfo::BuiltinVaListKind Kind) {
6110 switch (Kind) {
6111 case TargetInfo::CharPtrBuiltinVaList:
6112 return CreateCharPtrBuiltinVaListDecl(Context);
6113 case TargetInfo::VoidPtrBuiltinVaList:
6114 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northoverc264e162013-01-31 12:13:10 +00006115 case TargetInfo::AArch64ABIBuiltinVaList:
6116 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Ingec5613b22012-06-16 03:34:49 +00006117 case TargetInfo::PowerABIBuiltinVaList:
6118 return CreatePowerABIBuiltinVaListDecl(Context);
6119 case TargetInfo::X86_64ABIBuiltinVaList:
6120 return CreateX86_64ABIBuiltinVaListDecl(Context);
6121 case TargetInfo::PNaClABIBuiltinVaList:
6122 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chieneae5a8202012-10-10 06:56:20 +00006123 case TargetInfo::AAPCSABIBuiltinVaList:
6124 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigandb8409212013-05-06 16:26:41 +00006125 case TargetInfo::SystemZBuiltinVaList:
6126 return CreateSystemZBuiltinVaListDecl(Context);
Meador Ingec5613b22012-06-16 03:34:49 +00006127 }
6128
6129 llvm_unreachable("Unhandled __builtin_va_list type kind");
6130}
6131
6132TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
6133 if (!BuiltinVaListDecl)
6134 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
6135
6136 return BuiltinVaListDecl;
6137}
6138
Meador Ingefb40e3f2012-07-01 15:57:25 +00006139QualType ASTContext::getVaListTagType() const {
6140 // Force the creation of VaListTagTy by building the __builtin_va_list
6141 // declaration.
6142 if (VaListTagTy.isNull())
6143 (void) getBuiltinVaListDecl();
6144
6145 return VaListTagTy;
6146}
6147
Ted Kremeneka526c5c2008-01-07 19:49:32 +00006148void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00006149 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00006150 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00006151
Ted Kremeneka526c5c2008-01-07 19:49:32 +00006152 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00006153}
6154
John McCall0bd6feb2009-12-02 08:04:21 +00006155/// \brief Retrieve the template name that corresponds to a non-empty
6156/// lookup.
Jay Foad4ba2a172011-01-12 09:06:06 +00006157TemplateName
6158ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6159 UnresolvedSetIterator End) const {
John McCall0bd6feb2009-12-02 08:04:21 +00006160 unsigned size = End - Begin;
6161 assert(size > 1 && "set is not overloaded!");
6162
6163 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6164 size * sizeof(FunctionTemplateDecl*));
6165 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6166
6167 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00006168 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00006169 NamedDecl *D = *I;
6170 assert(isa<FunctionTemplateDecl>(D) ||
6171 (isa<UsingShadowDecl>(D) &&
6172 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6173 *Storage++ = D;
6174 }
6175
6176 return TemplateName(OT);
6177}
6178
Douglas Gregor7532dc62009-03-30 22:58:21 +00006179/// \brief Retrieve the template name that represents a qualified
6180/// template name such as \c std::vector.
Jay Foad4ba2a172011-01-12 09:06:06 +00006181TemplateName
6182ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6183 bool TemplateKeyword,
6184 TemplateDecl *Template) const {
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00006185 assert(NNS && "Missing nested-name-specifier in qualified template name");
6186
Douglas Gregor789b1f62010-02-04 18:10:26 +00006187 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00006188 llvm::FoldingSetNodeID ID;
6189 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6190
6191 void *InsertPos = 0;
6192 QualifiedTemplateName *QTN =
6193 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6194 if (!QTN) {
Richard Smith2f47cab2012-08-16 01:19:31 +00006195 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6196 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregor7532dc62009-03-30 22:58:21 +00006197 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6198 }
6199
6200 return TemplateName(QTN);
6201}
6202
6203/// \brief Retrieve the template name that represents a dependent
6204/// template name such as \c MetaFun::template apply.
Jay Foad4ba2a172011-01-12 09:06:06 +00006205TemplateName
6206ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6207 const IdentifierInfo *Name) const {
Mike Stump1eb44332009-09-09 15:08:12 +00006208 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00006209 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00006210
6211 llvm::FoldingSetNodeID ID;
6212 DependentTemplateName::Profile(ID, NNS, Name);
6213
6214 void *InsertPos = 0;
6215 DependentTemplateName *QTN =
6216 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6217
6218 if (QTN)
6219 return TemplateName(QTN);
6220
6221 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6222 if (CanonNNS == NNS) {
Richard Smith2f47cab2012-08-16 01:19:31 +00006223 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6224 DependentTemplateName(NNS, Name);
Douglas Gregor7532dc62009-03-30 22:58:21 +00006225 } else {
6226 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smith2f47cab2012-08-16 01:19:31 +00006227 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6228 DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00006229 DependentTemplateName *CheckQTN =
6230 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6231 assert(!CheckQTN && "Dependent type name canonicalization broken");
6232 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00006233 }
6234
6235 DependentTemplateNames.InsertNode(QTN, InsertPos);
6236 return TemplateName(QTN);
6237}
6238
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006239/// \brief Retrieve the template name that represents a dependent
6240/// template name such as \c MetaFun::template operator+.
6241TemplateName
6242ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00006243 OverloadedOperatorKind Operator) const {
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006244 assert((!NNS || NNS->isDependent()) &&
6245 "Nested name specifier must be dependent");
6246
6247 llvm::FoldingSetNodeID ID;
6248 DependentTemplateName::Profile(ID, NNS, Operator);
6249
6250 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00006251 DependentTemplateName *QTN
6252 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006253
6254 if (QTN)
6255 return TemplateName(QTN);
6256
6257 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6258 if (CanonNNS == NNS) {
Richard Smith2f47cab2012-08-16 01:19:31 +00006259 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6260 DependentTemplateName(NNS, Operator);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006261 } else {
6262 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smith2f47cab2012-08-16 01:19:31 +00006263 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6264 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00006265
6266 DependentTemplateName *CheckQTN
6267 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6268 assert(!CheckQTN && "Dependent template name canonicalization broken");
6269 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00006270 }
6271
6272 DependentTemplateNames.InsertNode(QTN, InsertPos);
6273 return TemplateName(QTN);
6274}
6275
Douglas Gregor1aee05d2011-01-15 06:45:20 +00006276TemplateName
John McCall14606042011-06-30 08:33:18 +00006277ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6278 TemplateName replacement) const {
6279 llvm::FoldingSetNodeID ID;
6280 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
6281
6282 void *insertPos = 0;
6283 SubstTemplateTemplateParmStorage *subst
6284 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6285
6286 if (!subst) {
6287 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6288 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6289 }
6290
6291 return TemplateName(subst);
6292}
6293
6294TemplateName
Douglas Gregor1aee05d2011-01-15 06:45:20 +00006295ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6296 const TemplateArgument &ArgPack) const {
6297 ASTContext &Self = const_cast<ASTContext &>(*this);
6298 llvm::FoldingSetNodeID ID;
6299 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
6300
6301 void *InsertPos = 0;
6302 SubstTemplateTemplateParmPackStorage *Subst
6303 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6304
6305 if (!Subst) {
John McCall14606042011-06-30 08:33:18 +00006306 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor1aee05d2011-01-15 06:45:20 +00006307 ArgPack.pack_size(),
6308 ArgPack.pack_begin());
6309 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6310 }
6311
6312 return TemplateName(Subst);
6313}
6314
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006315/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00006316/// TargetInfo, produce the corresponding type. The unsigned @p Type
6317/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00006318CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006319 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00006320 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006321 case TargetInfo::SignedShort: return ShortTy;
6322 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6323 case TargetInfo::SignedInt: return IntTy;
6324 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6325 case TargetInfo::SignedLong: return LongTy;
6326 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6327 case TargetInfo::SignedLongLong: return LongLongTy;
6328 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6329 }
6330
David Blaikieb219cfc2011-09-23 05:06:16 +00006331 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregorb4e66d52008-11-03 14:12:49 +00006332}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00006333
6334//===----------------------------------------------------------------------===//
6335// Type Predicates.
6336//===----------------------------------------------------------------------===//
6337
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00006338/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6339/// garbage collection attribute.
6340///
John McCallae278a32011-01-12 00:34:59 +00006341Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikie4e4d0842012-03-11 07:00:24 +00006342 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCallae278a32011-01-12 00:34:59 +00006343 return Qualifiers::GCNone;
6344
David Blaikie4e4d0842012-03-11 07:00:24 +00006345 assert(getLangOpts().ObjC1);
John McCallae278a32011-01-12 00:34:59 +00006346 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6347
6348 // Default behaviour under objective-C's gc is for ObjC pointers
6349 // (or pointers to them) be treated as though they were declared
6350 // as __strong.
6351 if (GCAttrs == Qualifiers::GCNone) {
6352 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6353 return Qualifiers::Strong;
6354 else if (Ty->isPointerType())
6355 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6356 } else {
6357 // It's not valid to set GC attributes on anything that isn't a
6358 // pointer.
6359#ifndef NDEBUG
6360 QualType CT = Ty->getCanonicalTypeInternal();
6361 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6362 CT = AT->getElementType();
6363 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6364#endif
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00006365 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00006366 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00006367}
6368
Chris Lattner6ac46a42008-04-07 06:51:04 +00006369//===----------------------------------------------------------------------===//
6370// Type Compatibility Testing
6371//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00006372
Mike Stump1eb44332009-09-09 15:08:12 +00006373/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00006374/// compatible.
6375static bool areCompatVectorTypes(const VectorType *LHS,
6376 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00006377 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00006378 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00006379 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00006380}
6381
Douglas Gregor255210e2010-08-06 10:14:59 +00006382bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6383 QualType SecondVec) {
6384 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6385 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6386
6387 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6388 return true;
6389
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00006390 // Treat Neon vector types and most AltiVec vector types as if they are the
6391 // equivalent GCC vector types.
Douglas Gregor255210e2010-08-06 10:14:59 +00006392 const VectorType *First = FirstVec->getAs<VectorType>();
6393 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00006394 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor255210e2010-08-06 10:14:59 +00006395 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00006396 First->getVectorKind() != VectorType::AltiVecPixel &&
6397 First->getVectorKind() != VectorType::AltiVecBool &&
6398 Second->getVectorKind() != VectorType::AltiVecPixel &&
6399 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor255210e2010-08-06 10:14:59 +00006400 return true;
6401
6402 return false;
6403}
6404
Steve Naroff4084c302009-07-23 01:01:38 +00006405//===----------------------------------------------------------------------===//
6406// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6407//===----------------------------------------------------------------------===//
6408
6409/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6410/// inheritance hierarchy of 'rProto'.
Jay Foad4ba2a172011-01-12 09:06:06 +00006411bool
6412ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6413 ObjCProtocolDecl *rProto) const {
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00006414 if (declaresSameEntity(lProto, rProto))
Steve Naroff4084c302009-07-23 01:01:38 +00006415 return true;
6416 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
6417 E = rProto->protocol_end(); PI != E; ++PI)
6418 if (ProtocolCompatibleWithProtocol(lProto, *PI))
6419 return true;
6420 return false;
6421}
6422
Dmitri Gribenko4c3b8a32012-08-28 02:49:14 +00006423/// QualifiedIdConformsQualifiedId - compare id<pr,...> with id<pr1,...>
Steve Naroff4084c302009-07-23 01:01:38 +00006424/// return true if lhs's protocols conform to rhs's protocol; false
6425/// otherwise.
6426bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
6427 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
6428 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
6429 return false;
6430}
6431
Dmitri Gribenko4c3b8a32012-08-28 02:49:14 +00006432/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6433/// Class<pr1, ...>.
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00006434bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6435 QualType rhs) {
6436 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6437 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6438 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6439
6440 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6441 E = lhsQID->qual_end(); I != E; ++I) {
6442 bool match = false;
6443 ObjCProtocolDecl *lhsProto = *I;
6444 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6445 E = rhsOPT->qual_end(); J != E; ++J) {
6446 ObjCProtocolDecl *rhsProto = *J;
6447 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6448 match = true;
6449 break;
6450 }
6451 }
6452 if (!match)
6453 return false;
6454 }
6455 return true;
6456}
6457
Steve Naroff4084c302009-07-23 01:01:38 +00006458/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6459/// ObjCQualifiedIDType.
6460bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6461 bool compare) {
6462 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00006463 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00006464 lhs->isObjCIdType() || lhs->isObjCClassType())
6465 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00006466 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00006467 rhs->isObjCIdType() || rhs->isObjCClassType())
6468 return true;
6469
6470 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00006471 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00006472
Steve Naroff4084c302009-07-23 01:01:38 +00006473 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006474
Steve Naroff4084c302009-07-23 01:01:38 +00006475 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006476 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00006477 // make sure we check the class hierarchy.
6478 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6479 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6480 E = lhsQID->qual_end(); I != E; ++I) {
6481 // when comparing an id<P> on lhs with a static type on rhs,
6482 // see if static class implements all of id's protocols, directly or
6483 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00006484 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00006485 return false;
6486 }
6487 }
6488 // If there are no qualifiers and no interface, we have an 'id'.
6489 return true;
6490 }
Mike Stump1eb44332009-09-09 15:08:12 +00006491 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00006492 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6493 E = lhsQID->qual_end(); I != E; ++I) {
6494 ObjCProtocolDecl *lhsProto = *I;
6495 bool match = false;
6496
6497 // when comparing an id<P> on lhs with a static type on rhs,
6498 // see if static class implements all of id's protocols, directly or
6499 // through its super class and categories.
6500 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6501 E = rhsOPT->qual_end(); J != E; ++J) {
6502 ObjCProtocolDecl *rhsProto = *J;
6503 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6504 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6505 match = true;
6506 break;
6507 }
6508 }
Mike Stump1eb44332009-09-09 15:08:12 +00006509 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00006510 // make sure we check the class hierarchy.
6511 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6512 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6513 E = lhsQID->qual_end(); I != E; ++I) {
6514 // when comparing an id<P> on lhs with a static type on rhs,
6515 // see if static class implements all of id's protocols, directly or
6516 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00006517 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00006518 match = true;
6519 break;
6520 }
6521 }
6522 }
6523 if (!match)
6524 return false;
6525 }
Mike Stump1eb44332009-09-09 15:08:12 +00006526
Steve Naroff4084c302009-07-23 01:01:38 +00006527 return true;
6528 }
Mike Stump1eb44332009-09-09 15:08:12 +00006529
Steve Naroff4084c302009-07-23 01:01:38 +00006530 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6531 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6532
Mike Stump1eb44332009-09-09 15:08:12 +00006533 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00006534 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006535 // If both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00006536 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
6537 E = lhsOPT->qual_end(); I != E; ++I) {
6538 ObjCProtocolDecl *lhsProto = *I;
6539 bool match = false;
6540
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006541 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff4084c302009-07-23 01:01:38 +00006542 // see if static class implements all of id's protocols, directly or
6543 // through its super class and categories.
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006544 // First, lhs protocols in the qualifier list must be found, direct
6545 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff4084c302009-07-23 01:01:38 +00006546 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6547 E = rhsQID->qual_end(); J != E; ++J) {
6548 ObjCProtocolDecl *rhsProto = *J;
6549 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6550 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6551 match = true;
6552 break;
6553 }
6554 }
6555 if (!match)
6556 return false;
6557 }
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00006558
6559 // Static class's protocols, or its super class or category protocols
6560 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6561 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6562 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6563 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6564 // This is rather dubious but matches gcc's behavior. If lhs has
6565 // no type qualifier and its class has no static protocol(s)
6566 // assume that it is mismatch.
6567 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6568 return false;
6569 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6570 LHSInheritedProtocols.begin(),
6571 E = LHSInheritedProtocols.end(); I != E; ++I) {
6572 bool match = false;
6573 ObjCProtocolDecl *lhsProto = (*I);
6574 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6575 E = rhsQID->qual_end(); J != E; ++J) {
6576 ObjCProtocolDecl *rhsProto = *J;
6577 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6578 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6579 match = true;
6580 break;
6581 }
6582 }
6583 if (!match)
6584 return false;
6585 }
6586 }
Steve Naroff4084c302009-07-23 01:01:38 +00006587 return true;
6588 }
6589 return false;
6590}
6591
Eli Friedman3d815e72008-08-22 00:56:42 +00006592/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00006593/// compatible for assignment from RHS to LHS. This handles validation of any
6594/// protocol qualifiers on the LHS or RHS.
6595///
Steve Naroff14108da2009-07-10 23:34:53 +00006596bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6597 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00006598 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6599 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6600
Steve Naroffde2e22d2009-07-15 18:40:39 +00006601 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00006602 if (LHS->isObjCUnqualifiedIdOrClass() ||
6603 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00006604 return true;
6605
John McCallc12c5bb2010-05-15 11:32:37 +00006606 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00006607 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6608 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00006609 false);
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00006610
6611 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6612 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6613 QualType(RHSOPT,0));
6614
John McCallc12c5bb2010-05-15 11:32:37 +00006615 // If we have 2 user-defined types, fall into that path.
6616 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00006617 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00006618
Steve Naroff4084c302009-07-23 01:01:38 +00006619 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00006620}
6621
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006622/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00006623/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006624/// arguments in block literals. When passed as arguments, passing 'A*' where
6625/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6626/// not OK. For the return type, the opposite is not OK.
6627bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6628 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006629 const ObjCObjectPointerType *RHSOPT,
6630 bool BlockReturnType) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00006631 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006632 return true;
6633
6634 if (LHSOPT->isObjCBuiltinType()) {
6635 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6636 }
6637
Fariborz Jahaniana9834482010-04-06 17:23:39 +00006638 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006639 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6640 QualType(RHSOPT,0),
6641 false);
6642
6643 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6644 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6645 if (LHS && RHS) { // We have 2 user-defined types.
6646 if (LHS != RHS) {
6647 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006648 return BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006649 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006650 return !BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006651 }
6652 else
6653 return true;
6654 }
6655 return false;
6656}
6657
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006658/// getIntersectionOfProtocols - This routine finds the intersection of set
6659/// of protocols inherited from two distinct objective-c pointer objects.
6660/// It is used to build composite qualifier list of the composite type of
6661/// the conditional expression involving two objective-c pointer objects.
6662static
6663void getIntersectionOfProtocols(ASTContext &Context,
6664 const ObjCObjectPointerType *LHSOPT,
6665 const ObjCObjectPointerType *RHSOPT,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006666 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006667
John McCallc12c5bb2010-05-15 11:32:37 +00006668 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6669 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6670 assert(LHS->getInterface() && "LHS must have an interface base");
6671 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006672
6673 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6674 unsigned LHSNumProtocols = LHS->getNumProtocols();
6675 if (LHSNumProtocols > 0)
6676 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6677 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006678 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006679 Context.CollectInheritedProtocols(LHS->getInterface(),
6680 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006681 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6682 LHSInheritedProtocols.end());
6683 }
6684
6685 unsigned RHSNumProtocols = RHS->getNumProtocols();
6686 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00006687 ObjCProtocolDecl **RHSProtocols =
6688 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006689 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6690 if (InheritedProtocolSet.count(RHSProtocols[i]))
6691 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier30601782011-08-17 23:08:45 +00006692 } else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006693 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006694 Context.CollectInheritedProtocols(RHS->getInterface(),
6695 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00006696 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6697 RHSInheritedProtocols.begin(),
6698 E = RHSInheritedProtocols.end(); I != E; ++I)
6699 if (InheritedProtocolSet.count((*I)))
6700 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006701 }
6702}
6703
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006704/// areCommonBaseCompatible - Returns common base class of the two classes if
6705/// one found. Note that this is O'2 algorithm. But it will be called as the
6706/// last type comparison in a ?-exp of ObjC pointer types before a
6707/// warning is issued. So, its invokation is extremely rare.
6708QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00006709 const ObjCObjectPointerType *Lptr,
6710 const ObjCObjectPointerType *Rptr) {
6711 const ObjCObjectType *LHS = Lptr->getObjectType();
6712 const ObjCObjectType *RHS = Rptr->getObjectType();
6713 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6714 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor60ef3082011-12-15 00:29:59 +00006715 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006716 return QualType();
6717
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00006718 do {
John McCallc12c5bb2010-05-15 11:32:37 +00006719 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006720 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006721 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCallc12c5bb2010-05-15 11:32:37 +00006722 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6723
6724 QualType Result = QualType(LHS, 0);
6725 if (!Protocols.empty())
6726 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6727 Result = getObjCObjectPointerType(Result);
6728 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00006729 }
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00006730 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00006731
6732 return QualType();
6733}
6734
John McCallc12c5bb2010-05-15 11:32:37 +00006735bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6736 const ObjCObjectType *RHS) {
6737 assert(LHS->getInterface() && "LHS is not an interface type");
6738 assert(RHS->getInterface() && "RHS is not an interface type");
6739
Chris Lattner6ac46a42008-04-07 06:51:04 +00006740 // Verify that the base decls are compatible: the RHS must be a subclass of
6741 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00006742 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00006743 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006744
Chris Lattner6ac46a42008-04-07 06:51:04 +00006745 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6746 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00006747 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00006748 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00006749
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006750 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6751 // more detailed analysis is required.
6752 if (RHS->getNumProtocols() == 0) {
6753 // OK, if LHS is a superclass of RHS *and*
6754 // this superclass is assignment compatible with LHS.
6755 // false otherwise.
Fariborz Jahanian627788c2011-04-12 16:34:14 +00006756 bool IsSuperClass =
6757 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6758 if (IsSuperClass) {
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006759 // OK if conversion of LHS to SuperClass results in narrowing of types
6760 // ; i.e., SuperClass may implement at least one of the protocols
6761 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6762 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6763 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian627788c2011-04-12 16:34:14 +00006764 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00006765 // If super class has no protocols, it is not a match.
6766 if (SuperClassInheritedProtocols.empty())
6767 return false;
6768
6769 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6770 LHSPE = LHS->qual_end();
6771 LHSPI != LHSPE; LHSPI++) {
6772 bool SuperImplementsProtocol = false;
6773 ObjCProtocolDecl *LHSProto = (*LHSPI);
6774
6775 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6776 SuperClassInheritedProtocols.begin(),
6777 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6778 ObjCProtocolDecl *SuperClassProto = (*I);
6779 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6780 SuperImplementsProtocol = true;
6781 break;
6782 }
6783 }
6784 if (!SuperImplementsProtocol)
6785 return false;
6786 }
6787 return true;
6788 }
6789 return false;
6790 }
Mike Stump1eb44332009-09-09 15:08:12 +00006791
John McCallc12c5bb2010-05-15 11:32:37 +00006792 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6793 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006794 LHSPI != LHSPE; LHSPI++) {
6795 bool RHSImplementsProtocol = false;
6796
6797 // If the RHS doesn't implement the protocol on the left, the types
6798 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00006799 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6800 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00006801 RHSPI != RHSPE; RHSPI++) {
6802 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006803 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00006804 break;
6805 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006806 }
6807 // FIXME: For better diagnostics, consider passing back the protocol name.
6808 if (!RHSImplementsProtocol)
6809 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00006810 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00006811 // The RHS implements all protocols listed on the LHS.
6812 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00006813}
6814
Steve Naroff389bf462009-02-12 17:52:19 +00006815bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6816 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00006817 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6818 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00006819
Steve Naroff14108da2009-07-10 23:34:53 +00006820 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00006821 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00006822
6823 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6824 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00006825}
6826
Douglas Gregor569c3162010-08-07 11:51:51 +00006827bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6828 return canAssignObjCInterfaces(
6829 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6830 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6831}
6832
Mike Stump1eb44332009-09-09 15:08:12 +00006833/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00006834/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00006835/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00006836/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor447234d2010-07-29 15:18:02 +00006837bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6838 bool CompareUnqualified) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006839 if (getLangOpts().CPlusPlus)
Douglas Gregor0e709ab2010-02-03 21:02:30 +00006840 return hasSameType(LHS, RHS);
6841
Douglas Gregor447234d2010-07-29 15:18:02 +00006842 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman3d815e72008-08-22 00:56:42 +00006843}
6844
Fariborz Jahanianc286f382011-07-12 22:05:16 +00006845bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanian82378392011-07-12 23:20:13 +00006846 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc286f382011-07-12 22:05:16 +00006847}
6848
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006849bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6850 return !mergeTypes(LHS, RHS, true).isNull();
6851}
6852
Peter Collingbourne48466752010-10-24 18:30:18 +00006853/// mergeTransparentUnionType - if T is a transparent union type and a member
6854/// of T is compatible with SubType, return the merged type, else return
6855/// QualType()
6856QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6857 bool OfBlockPointer,
6858 bool Unqualified) {
6859 if (const RecordType *UT = T->getAsUnionType()) {
6860 RecordDecl *UD = UT->getDecl();
6861 if (UD->hasAttr<TransparentUnionAttr>()) {
6862 for (RecordDecl::field_iterator it = UD->field_begin(),
6863 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbournef91d7572010-12-02 21:00:06 +00006864 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00006865 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6866 if (!MT.isNull())
6867 return MT;
6868 }
6869 }
6870 }
6871
6872 return QualType();
6873}
6874
6875/// mergeFunctionArgumentTypes - merge two types which appear as function
6876/// argument types
6877QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
6878 bool OfBlockPointer,
6879 bool Unqualified) {
6880 // GNU extension: two types are compatible if they appear as a function
6881 // argument, one of the types is a transparent union type and the other
6882 // type is compatible with a union member
6883 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6884 Unqualified);
6885 if (!lmerge.isNull())
6886 return lmerge;
6887
6888 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6889 Unqualified);
6890 if (!rmerge.isNull())
6891 return rmerge;
6892
6893 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6894}
6895
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006896QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor447234d2010-07-29 15:18:02 +00006897 bool OfBlockPointer,
6898 bool Unqualified) {
John McCall183700f2009-09-21 23:43:11 +00006899 const FunctionType *lbase = lhs->getAs<FunctionType>();
6900 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00006901 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6902 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00006903 bool allLTypes = true;
6904 bool allRTypes = true;
6905
6906 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006907 QualType retType;
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00006908 if (OfBlockPointer) {
6909 QualType RHS = rbase->getResultType();
6910 QualType LHS = lbase->getResultType();
6911 bool UnqualifiedResult = Unqualified;
6912 if (!UnqualifiedResult)
6913 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006914 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00006915 }
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006916 else
John McCall8cc246c2010-12-15 01:06:38 +00006917 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6918 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006919 if (retType.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006920
6921 if (Unqualified)
6922 retType = retType.getUnqualifiedType();
6923
6924 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6925 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6926 if (Unqualified) {
6927 LRetType = LRetType.getUnqualifiedType();
6928 RRetType = RRetType.getUnqualifiedType();
6929 }
6930
6931 if (getCanonicalType(retType) != LRetType)
Chris Lattner61710852008-10-05 17:34:18 +00006932 allLTypes = false;
Douglas Gregor447234d2010-07-29 15:18:02 +00006933 if (getCanonicalType(retType) != RRetType)
Chris Lattner61710852008-10-05 17:34:18 +00006934 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00006935
Daniel Dunbar6a15c852010-04-28 16:20:58 +00006936 // FIXME: double check this
6937 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6938 // rbase->getRegParmAttr() != 0 &&
6939 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00006940 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6941 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8cc246c2010-12-15 01:06:38 +00006942
Douglas Gregorab8bbf42010-01-18 17:14:39 +00006943 // Compatible functions must have compatible calling conventions
John McCall8cc246c2010-12-15 01:06:38 +00006944 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00006945 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00006946
John McCall8cc246c2010-12-15 01:06:38 +00006947 // Regparm is part of the calling convention.
Eli Friedmana49218e2011-04-09 08:18:08 +00006948 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6949 return QualType();
John McCall8cc246c2010-12-15 01:06:38 +00006950 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6951 return QualType();
6952
John McCallf85e1932011-06-15 23:02:42 +00006953 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6954 return QualType();
6955
John McCall8cc246c2010-12-15 01:06:38 +00006956 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6957 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8cc246c2010-12-15 01:06:38 +00006958
Rafael Espindola8b8a09e2012-11-29 16:09:03 +00006959 if (lbaseInfo.getNoReturn() != NoReturn)
6960 allLTypes = false;
6961 if (rbaseInfo.getNoReturn() != NoReturn)
6962 allRTypes = false;
6963
John McCallf85e1932011-06-15 23:02:42 +00006964 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00006965
Eli Friedman3d815e72008-08-22 00:56:42 +00006966 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00006967 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6968 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00006969 unsigned lproto_nargs = lproto->getNumArgs();
6970 unsigned rproto_nargs = rproto->getNumArgs();
6971
6972 // Compatible functions must have the same number of arguments
6973 if (lproto_nargs != rproto_nargs)
6974 return QualType();
6975
6976 // Variadic and non-variadic functions aren't compatible
6977 if (lproto->isVariadic() != rproto->isVariadic())
6978 return QualType();
6979
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00006980 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6981 return QualType();
6982
Fariborz Jahanian78213e42011-09-28 21:52:05 +00006983 if (LangOpts.ObjCAutoRefCount &&
6984 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6985 return QualType();
6986
Eli Friedman3d815e72008-08-22 00:56:42 +00006987 // Check argument compatibility
Chris Lattner5f9e2722011-07-23 10:55:15 +00006988 SmallVector<QualType, 10> types;
Eli Friedman3d815e72008-08-22 00:56:42 +00006989 for (unsigned i = 0; i < lproto_nargs; i++) {
6990 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
6991 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00006992 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
6993 OfBlockPointer,
6994 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006995 if (argtype.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006996
6997 if (Unqualified)
6998 argtype = argtype.getUnqualifiedType();
6999
Eli Friedman3d815e72008-08-22 00:56:42 +00007000 types.push_back(argtype);
Douglas Gregor447234d2010-07-29 15:18:02 +00007001 if (Unqualified) {
7002 largtype = largtype.getUnqualifiedType();
7003 rargtype = rargtype.getUnqualifiedType();
7004 }
7005
Chris Lattner61710852008-10-05 17:34:18 +00007006 if (getCanonicalType(argtype) != getCanonicalType(largtype))
7007 allLTypes = false;
7008 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
7009 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00007010 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00007011
Eli Friedman3d815e72008-08-22 00:56:42 +00007012 if (allLTypes) return lhs;
7013 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00007014
7015 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7016 EPI.ExtInfo = einfo;
Jordan Rosebea522f2013-03-08 21:51:21 +00007017 return getFunctionType(retType, types, EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00007018 }
7019
7020 if (lproto) allRTypes = false;
7021 if (rproto) allLTypes = false;
7022
Douglas Gregor72564e72009-02-26 23:50:07 +00007023 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00007024 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00007025 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00007026 if (proto->isVariadic()) return QualType();
7027 // Check that the types are compatible with the types that
7028 // would result from default argument promotions (C99 6.7.5.3p15).
7029 // The only types actually affected are promotable integer
7030 // types and floats, which would be passed as a different
7031 // type depending on whether the prototype is visible.
7032 unsigned proto_nargs = proto->getNumArgs();
7033 for (unsigned i = 0; i < proto_nargs; ++i) {
7034 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00007035
Eli Friedmanc586d5d2012-08-30 00:44:15 +00007036 // Look at the converted type of enum types, since that is the type used
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00007037 // to pass enum values.
Eli Friedmanc586d5d2012-08-30 00:44:15 +00007038 if (const EnumType *Enum = argTy->getAs<EnumType>()) {
7039 argTy = Enum->getDecl()->getIntegerType();
7040 if (argTy.isNull())
7041 return QualType();
7042 }
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00007043
Eli Friedman3d815e72008-08-22 00:56:42 +00007044 if (argTy->isPromotableIntegerType() ||
7045 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
7046 return QualType();
7047 }
7048
7049 if (allLTypes) return lhs;
7050 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00007051
7052 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7053 EPI.ExtInfo = einfo;
Reid Kleckner0567a792013-06-10 20:51:09 +00007054 return getFunctionType(retType, proto->getArgTypes(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00007055 }
7056
7057 if (allLTypes) return lhs;
7058 if (allRTypes) return rhs;
John McCall8cc246c2010-12-15 01:06:38 +00007059 return getFunctionNoProtoType(retType, einfo);
Eli Friedman3d815e72008-08-22 00:56:42 +00007060}
7061
John McCallb9da7132013-03-21 00:10:07 +00007062/// Given that we have an enum type and a non-enum type, try to merge them.
7063static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7064 QualType other, bool isBlockReturnType) {
7065 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7066 // a signed integer type, or an unsigned integer type.
7067 // Compatibility is based on the underlying type, not the promotion
7068 // type.
7069 QualType underlyingType = ET->getDecl()->getIntegerType();
7070 if (underlyingType.isNull()) return QualType();
7071 if (Context.hasSameType(underlyingType, other))
7072 return other;
7073
7074 // In block return types, we're more permissive and accept any
7075 // integral type of the same size.
7076 if (isBlockReturnType && other->isIntegerType() &&
7077 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7078 return other;
7079
7080 return QualType();
7081}
7082
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00007083QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor447234d2010-07-29 15:18:02 +00007084 bool OfBlockPointer,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00007085 bool Unqualified, bool BlockReturnType) {
Bill Wendling43d69752007-12-03 07:33:35 +00007086 // C++ [expr]: If an expression initially has the type "reference to T", the
7087 // type is adjusted to "T" prior to any further analysis, the expression
7088 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00007089 // expression is an lvalue unless the reference is an rvalue reference and
7090 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00007091 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7092 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor447234d2010-07-29 15:18:02 +00007093
7094 if (Unqualified) {
7095 LHS = LHS.getUnqualifiedType();
7096 RHS = RHS.getUnqualifiedType();
7097 }
Douglas Gregor0e709ab2010-02-03 21:02:30 +00007098
Eli Friedman3d815e72008-08-22 00:56:42 +00007099 QualType LHSCan = getCanonicalType(LHS),
7100 RHSCan = getCanonicalType(RHS);
7101
7102 // If two types are identical, they are compatible.
7103 if (LHSCan == RHSCan)
7104 return LHS;
7105
John McCall0953e762009-09-24 19:53:00 +00007106 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00007107 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7108 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00007109 if (LQuals != RQuals) {
7110 // If any of these qualifiers are different, we have a type
7111 // mismatch.
7112 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCallf85e1932011-06-15 23:02:42 +00007113 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7114 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall0953e762009-09-24 19:53:00 +00007115 return QualType();
7116
7117 // Exactly one GC qualifier difference is allowed: __strong is
7118 // okay if the other type has no GC qualifier but is an Objective
7119 // C object pointer (i.e. implicitly strong by default). We fix
7120 // this by pretending that the unqualified type was actually
7121 // qualified __strong.
7122 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7123 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7124 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7125
7126 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7127 return QualType();
7128
7129 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7130 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7131 }
7132 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7133 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7134 }
Eli Friedman3d815e72008-08-22 00:56:42 +00007135 return QualType();
John McCall0953e762009-09-24 19:53:00 +00007136 }
7137
7138 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00007139
Eli Friedman852d63b2009-06-01 01:22:52 +00007140 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7141 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00007142
Chris Lattner1adb8832008-01-14 05:45:46 +00007143 // We want to consider the two function types to be the same for these
7144 // comparisons, just force one to the other.
7145 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7146 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00007147
7148 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00007149 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7150 LHSClass = Type::ConstantArray;
7151 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7152 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00007153
John McCallc12c5bb2010-05-15 11:32:37 +00007154 // ObjCInterfaces are just specialized ObjCObjects.
7155 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7156 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7157
Nate Begeman213541a2008-04-18 23:10:10 +00007158 // Canonicalize ExtVector -> Vector.
7159 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7160 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00007161
Chris Lattnera36a61f2008-04-07 05:43:21 +00007162 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00007163 if (LHSClass != RHSClass) {
John McCallb9da7132013-03-21 00:10:07 +00007164 // Note that we only have special rules for turning block enum
7165 // returns into block int returns, not vice-versa.
John McCall183700f2009-09-21 23:43:11 +00007166 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCallb9da7132013-03-21 00:10:07 +00007167 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmanbab96962008-02-12 08:46:17 +00007168 }
John McCall183700f2009-09-21 23:43:11 +00007169 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCallb9da7132013-03-21 00:10:07 +00007170 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmanbab96962008-02-12 08:46:17 +00007171 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00007172 // allow block pointer type to match an 'id' type.
Fariborz Jahanian41963632012-01-26 17:08:50 +00007173 if (OfBlockPointer && !BlockReturnType) {
7174 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7175 return LHS;
7176 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7177 return RHS;
7178 }
Fariborz Jahaniane7cff2c2012-01-26 00:45:38 +00007179
Eli Friedman3d815e72008-08-22 00:56:42 +00007180 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00007181 }
Eli Friedman3d815e72008-08-22 00:56:42 +00007182
Steve Naroff4a746782008-01-09 22:43:08 +00007183 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00007184 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00007185#define TYPE(Class, Base)
7186#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00007187#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00007188#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7189#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7190#include "clang/AST/TypeNodes.def"
David Blaikieb219cfc2011-09-23 05:06:16 +00007191 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregor72564e72009-02-26 23:50:07 +00007192
Richard Smithdc7a4f52013-04-30 13:56:41 +00007193 case Type::Auto:
Sebastian Redl7c80bd62009-03-16 23:22:08 +00007194 case Type::LValueReference:
7195 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00007196 case Type::MemberPointer:
David Blaikieb219cfc2011-09-23 05:06:16 +00007197 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregor72564e72009-02-26 23:50:07 +00007198
John McCallc12c5bb2010-05-15 11:32:37 +00007199 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00007200 case Type::IncompleteArray:
7201 case Type::VariableArray:
7202 case Type::FunctionProto:
7203 case Type::ExtVector:
David Blaikieb219cfc2011-09-23 05:06:16 +00007204 llvm_unreachable("Types are eliminated above");
Douglas Gregor72564e72009-02-26 23:50:07 +00007205
Chris Lattner1adb8832008-01-14 05:45:46 +00007206 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00007207 {
7208 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00007209 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7210 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00007211 if (Unqualified) {
7212 LHSPointee = LHSPointee.getUnqualifiedType();
7213 RHSPointee = RHSPointee.getUnqualifiedType();
7214 }
7215 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7216 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00007217 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00007218 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00007219 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00007220 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00007221 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00007222 return getPointerType(ResultType);
7223 }
Steve Naroffc0febd52008-12-10 17:49:55 +00007224 case Type::BlockPointer:
7225 {
7226 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00007227 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7228 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00007229 if (Unqualified) {
7230 LHSPointee = LHSPointee.getUnqualifiedType();
7231 RHSPointee = RHSPointee.getUnqualifiedType();
7232 }
7233 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7234 Unqualified);
Steve Naroffc0febd52008-12-10 17:49:55 +00007235 if (ResultType.isNull()) return QualType();
7236 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7237 return LHS;
7238 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7239 return RHS;
7240 return getBlockPointerType(ResultType);
7241 }
Eli Friedmanb001de72011-10-06 23:00:33 +00007242 case Type::Atomic:
7243 {
7244 // Merge two pointer types, while trying to preserve typedef info
7245 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7246 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7247 if (Unqualified) {
7248 LHSValue = LHSValue.getUnqualifiedType();
7249 RHSValue = RHSValue.getUnqualifiedType();
7250 }
7251 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7252 Unqualified);
7253 if (ResultType.isNull()) return QualType();
7254 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7255 return LHS;
7256 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7257 return RHS;
7258 return getAtomicType(ResultType);
7259 }
Chris Lattner1adb8832008-01-14 05:45:46 +00007260 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00007261 {
7262 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7263 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7264 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7265 return QualType();
7266
7267 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7268 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor447234d2010-07-29 15:18:02 +00007269 if (Unqualified) {
7270 LHSElem = LHSElem.getUnqualifiedType();
7271 RHSElem = RHSElem.getUnqualifiedType();
7272 }
7273
7274 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00007275 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00007276 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7277 return LHS;
7278 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7279 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00007280 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7281 ArrayType::ArraySizeModifier(), 0);
7282 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7283 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00007284 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7285 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00007286 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7287 return LHS;
7288 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7289 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00007290 if (LVAT) {
7291 // FIXME: This isn't correct! But tricky to implement because
7292 // the array's size has to be the size of LHS, but the type
7293 // has to be different.
7294 return LHS;
7295 }
7296 if (RVAT) {
7297 // FIXME: This isn't correct! But tricky to implement because
7298 // the array's size has to be the size of RHS, but the type
7299 // has to be different.
7300 return RHS;
7301 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00007302 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7303 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00007304 return getIncompleteArrayType(ResultType,
7305 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00007306 }
Chris Lattner1adb8832008-01-14 05:45:46 +00007307 case Type::FunctionNoProto:
Douglas Gregor447234d2010-07-29 15:18:02 +00007308 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregor72564e72009-02-26 23:50:07 +00007309 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00007310 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00007311 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00007312 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00007313 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00007314 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00007315 case Type::Complex:
7316 // Distinct complex types are incompatible.
7317 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00007318 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00007319 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00007320 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7321 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00007322 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00007323 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00007324 case Type::ObjCObject: {
7325 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00007326 // FIXME: This should be type compatibility, e.g. whether
7327 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00007328 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7329 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7330 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00007331 return LHS;
7332
Eli Friedman3d815e72008-08-22 00:56:42 +00007333 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00007334 }
Steve Naroff14108da2009-07-10 23:34:53 +00007335 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00007336 if (OfBlockPointer) {
7337 if (canAssignObjCInterfacesInBlockPointer(
7338 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00007339 RHS->getAs<ObjCObjectPointerType>(),
7340 BlockReturnType))
David Blaikie7530c032012-01-17 06:56:22 +00007341 return LHS;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00007342 return QualType();
7343 }
John McCall183700f2009-09-21 23:43:11 +00007344 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7345 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00007346 return LHS;
7347
Steve Naroffbc76dd02008-12-10 22:14:21 +00007348 return QualType();
David Blaikie7530c032012-01-17 06:56:22 +00007349 }
Steve Naroffec0550f2007-10-15 20:41:53 +00007350 }
Douglas Gregor72564e72009-02-26 23:50:07 +00007351
David Blaikie7530c032012-01-17 06:56:22 +00007352 llvm_unreachable("Invalid Type::Class!");
Steve Naroffec0550f2007-10-15 20:41:53 +00007353}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00007354
Fariborz Jahanian78213e42011-09-28 21:52:05 +00007355bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7356 const FunctionProtoType *FromFunctionType,
7357 const FunctionProtoType *ToFunctionType) {
7358 if (FromFunctionType->hasAnyConsumedArgs() !=
7359 ToFunctionType->hasAnyConsumedArgs())
7360 return false;
7361 FunctionProtoType::ExtProtoInfo FromEPI =
7362 FromFunctionType->getExtProtoInfo();
7363 FunctionProtoType::ExtProtoInfo ToEPI =
7364 ToFunctionType->getExtProtoInfo();
7365 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
7366 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
7367 ArgIdx != NumArgs; ++ArgIdx) {
7368 if (FromEPI.ConsumedArguments[ArgIdx] !=
7369 ToEPI.ConsumedArguments[ArgIdx])
7370 return false;
7371 }
7372 return true;
7373}
7374
Fariborz Jahanian2390a722010-05-19 21:37:30 +00007375/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7376/// 'RHS' attributes and returns the merged version; including for function
7377/// return types.
7378QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7379 QualType LHSCan = getCanonicalType(LHS),
7380 RHSCan = getCanonicalType(RHS);
7381 // If two types are identical, they are compatible.
7382 if (LHSCan == RHSCan)
7383 return LHS;
7384 if (RHSCan->isFunctionType()) {
7385 if (!LHSCan->isFunctionType())
7386 return QualType();
7387 QualType OldReturnType =
7388 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
7389 QualType NewReturnType =
7390 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
7391 QualType ResReturnType =
7392 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7393 if (ResReturnType.isNull())
7394 return QualType();
7395 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7396 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7397 // In either case, use OldReturnType to build the new function type.
7398 const FunctionType *F = LHS->getAs<FunctionType>();
7399 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalle23cf432010-12-14 08:05:40 +00007400 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7401 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner0567a792013-06-10 20:51:09 +00007402 QualType ResultType =
7403 getFunctionType(OldReturnType, FPT->getArgTypes(), EPI);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00007404 return ResultType;
7405 }
7406 }
7407 return QualType();
7408 }
7409
7410 // If the qualifiers are different, the types can still be merged.
7411 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7412 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7413 if (LQuals != RQuals) {
7414 // If any of these qualifiers are different, we have a type mismatch.
7415 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7416 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7417 return QualType();
7418
7419 // Exactly one GC qualifier difference is allowed: __strong is
7420 // okay if the other type has no GC qualifier but is an Objective
7421 // C object pointer (i.e. implicitly strong by default). We fix
7422 // this by pretending that the unqualified type was actually
7423 // qualified __strong.
7424 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7425 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7426 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7427
7428 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7429 return QualType();
7430
7431 if (GC_L == Qualifiers::Strong)
7432 return LHS;
7433 if (GC_R == Qualifiers::Strong)
7434 return RHS;
7435 return QualType();
7436 }
7437
7438 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7439 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7440 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7441 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7442 if (ResQT == LHSBaseQT)
7443 return LHS;
7444 if (ResQT == RHSBaseQT)
7445 return RHS;
7446 }
7447 return QualType();
7448}
7449
Chris Lattner5426bf62008-04-07 07:01:58 +00007450//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00007451// Integer Predicates
7452//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00007453
Jay Foad4ba2a172011-01-12 09:06:06 +00007454unsigned ASTContext::getIntWidth(QualType T) const {
John McCallf4c73712011-01-19 06:33:43 +00007455 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00007456 T = ET->getDecl()->getIntegerType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00007457 if (T->isBooleanType())
7458 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00007459 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00007460 return (unsigned)getTypeSize(T);
7461}
7462
Abramo Bagnara762f1592012-09-09 10:21:24 +00007463QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregorf6094622010-07-23 15:58:24 +00007464 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00007465
7466 // Turn <4 x signed int> -> <4 x unsigned int>
7467 if (const VectorType *VTy = T->getAs<VectorType>())
7468 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsone86d78c2010-11-10 21:56:12 +00007469 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattner6a2b9262009-10-17 20:33:28 +00007470
7471 // For enums, we return the unsigned version of the base type.
7472 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00007473 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00007474
7475 const BuiltinType *BTy = T->getAs<BuiltinType>();
7476 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00007477 switch (BTy->getKind()) {
7478 case BuiltinType::Char_S:
7479 case BuiltinType::SChar:
7480 return UnsignedCharTy;
7481 case BuiltinType::Short:
7482 return UnsignedShortTy;
7483 case BuiltinType::Int:
7484 return UnsignedIntTy;
7485 case BuiltinType::Long:
7486 return UnsignedLongTy;
7487 case BuiltinType::LongLong:
7488 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00007489 case BuiltinType::Int128:
7490 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00007491 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00007492 llvm_unreachable("Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00007493 }
7494}
7495
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00007496ASTMutationListener::~ASTMutationListener() { }
7497
Richard Smith9dadfab2013-05-11 05:45:24 +00007498void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7499 QualType ReturnType) {}
Chris Lattner86df27b2009-06-14 00:45:47 +00007500
7501//===----------------------------------------------------------------------===//
7502// Builtin Type Computation
7503//===----------------------------------------------------------------------===//
7504
7505/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattner33daae62010-10-01 22:42:38 +00007506/// pointer over the consumed characters. This returns the resultant type. If
7507/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7508/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7509/// a vector of "i*".
Chris Lattner14e0e742010-10-01 22:53:11 +00007510///
7511/// RequiresICE is filled in on return to indicate whether the value is required
7512/// to be an Integer Constant Expression.
Jay Foad4ba2a172011-01-12 09:06:06 +00007513static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00007514 ASTContext::GetBuiltinTypeError &Error,
Chris Lattner14e0e742010-10-01 22:53:11 +00007515 bool &RequiresICE,
Chris Lattner33daae62010-10-01 22:42:38 +00007516 bool AllowTypeModifiers) {
Chris Lattner86df27b2009-06-14 00:45:47 +00007517 // Modifiers.
7518 int HowLong = 0;
7519 bool Signed = false, Unsigned = false;
Chris Lattner14e0e742010-10-01 22:53:11 +00007520 RequiresICE = false;
Chris Lattner393bd8e2010-10-01 07:13:18 +00007521
Chris Lattner33daae62010-10-01 22:42:38 +00007522 // Read the prefixed modifiers first.
Chris Lattner86df27b2009-06-14 00:45:47 +00007523 bool Done = false;
7524 while (!Done) {
7525 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00007526 default: Done = true; --Str; break;
Chris Lattner393bd8e2010-10-01 07:13:18 +00007527 case 'I':
Chris Lattner14e0e742010-10-01 22:53:11 +00007528 RequiresICE = true;
Chris Lattner393bd8e2010-10-01 07:13:18 +00007529 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007530 case 'S':
7531 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7532 assert(!Signed && "Can't use 'S' modifier multiple times!");
7533 Signed = true;
7534 break;
7535 case 'U':
7536 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7537 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7538 Unsigned = true;
7539 break;
7540 case 'L':
7541 assert(HowLong <= 2 && "Can't have LLLL modifier");
7542 ++HowLong;
7543 break;
7544 }
7545 }
7546
7547 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00007548
Chris Lattner86df27b2009-06-14 00:45:47 +00007549 // Read the base type.
7550 switch (*Str++) {
David Blaikieb219cfc2011-09-23 05:06:16 +00007551 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattner86df27b2009-06-14 00:45:47 +00007552 case 'v':
7553 assert(HowLong == 0 && !Signed && !Unsigned &&
7554 "Bad modifiers used with 'v'!");
7555 Type = Context.VoidTy;
7556 break;
7557 case 'f':
7558 assert(HowLong == 0 && !Signed && !Unsigned &&
7559 "Bad modifiers used with 'f'!");
7560 Type = Context.FloatTy;
7561 break;
7562 case 'd':
7563 assert(HowLong < 2 && !Signed && !Unsigned &&
7564 "Bad modifiers used with 'd'!");
7565 if (HowLong)
7566 Type = Context.LongDoubleTy;
7567 else
7568 Type = Context.DoubleTy;
7569 break;
7570 case 's':
7571 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7572 if (Unsigned)
7573 Type = Context.UnsignedShortTy;
7574 else
7575 Type = Context.ShortTy;
7576 break;
7577 case 'i':
7578 if (HowLong == 3)
7579 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7580 else if (HowLong == 2)
7581 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7582 else if (HowLong == 1)
7583 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7584 else
7585 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7586 break;
7587 case 'c':
7588 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7589 if (Signed)
7590 Type = Context.SignedCharTy;
7591 else if (Unsigned)
7592 Type = Context.UnsignedCharTy;
7593 else
7594 Type = Context.CharTy;
7595 break;
7596 case 'b': // boolean
7597 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7598 Type = Context.BoolTy;
7599 break;
7600 case 'z': // size_t.
7601 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7602 Type = Context.getSizeType();
7603 break;
7604 case 'F':
7605 Type = Context.getCFConstantStringType();
7606 break;
Fariborz Jahanianba8bda02010-11-09 21:38:20 +00007607 case 'G':
7608 Type = Context.getObjCIdType();
7609 break;
7610 case 'H':
7611 Type = Context.getObjCSelType();
7612 break;
Fariborz Jahanianf7992132013-01-04 18:45:40 +00007613 case 'M':
7614 Type = Context.getObjCSuperType();
7615 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007616 case 'a':
7617 Type = Context.getBuiltinVaListType();
7618 assert(!Type.isNull() && "builtin va list type not initialized!");
7619 break;
7620 case 'A':
7621 // This is a "reference" to a va_list; however, what exactly
7622 // this means depends on how va_list is defined. There are two
7623 // different kinds of va_list: ones passed by value, and ones
7624 // passed by reference. An example of a by-value va_list is
7625 // x86, where va_list is a char*. An example of by-ref va_list
7626 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7627 // we want this argument to be a char*&; for x86-64, we want
7628 // it to be a __va_list_tag*.
7629 Type = Context.getBuiltinVaListType();
7630 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattner14e0e742010-10-01 22:53:11 +00007631 if (Type->isArrayType())
Chris Lattner86df27b2009-06-14 00:45:47 +00007632 Type = Context.getArrayDecayedType(Type);
Chris Lattner14e0e742010-10-01 22:53:11 +00007633 else
Chris Lattner86df27b2009-06-14 00:45:47 +00007634 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00007635 break;
7636 case 'V': {
7637 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00007638 unsigned NumElements = strtoul(Str, &End, 10);
7639 assert(End != Str && "Missing vector size");
Chris Lattner86df27b2009-06-14 00:45:47 +00007640 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00007641
Chris Lattner14e0e742010-10-01 22:53:11 +00007642 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7643 RequiresICE, false);
7644 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattner33daae62010-10-01 22:42:38 +00007645
7646 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner788b0fd2010-06-23 06:00:24 +00007647 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00007648 VectorType::GenericVector);
Chris Lattner86df27b2009-06-14 00:45:47 +00007649 break;
7650 }
Douglas Gregorb4bc99b2012-06-07 18:08:25 +00007651 case 'E': {
7652 char *End;
7653
7654 unsigned NumElements = strtoul(Str, &End, 10);
7655 assert(End != Str && "Missing vector size");
7656
7657 Str = End;
7658
7659 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7660 false);
7661 Type = Context.getExtVectorType(ElementType, NumElements);
7662 break;
7663 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00007664 case 'X': {
Chris Lattner14e0e742010-10-01 22:53:11 +00007665 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7666 false);
7667 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregord3a23b22009-09-28 21:45:01 +00007668 Type = Context.getComplexType(ElementType);
7669 break;
Fariborz Jahaniancc075e42011-08-23 23:33:09 +00007670 }
7671 case 'Y' : {
7672 Type = Context.getPointerDiffType();
7673 break;
7674 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00007675 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00007676 Type = Context.getFILEType();
7677 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00007678 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00007679 return QualType();
7680 }
Mike Stumpfd612db2009-07-28 23:47:15 +00007681 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00007682 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00007683 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00007684 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00007685 else
7686 Type = Context.getjmp_bufType();
7687
Mike Stumpfd612db2009-07-28 23:47:15 +00007688 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00007689 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00007690 return QualType();
7691 }
7692 break;
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +00007693 case 'K':
7694 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7695 Type = Context.getucontext_tType();
7696
7697 if (Type.isNull()) {
7698 Error = ASTContext::GE_Missing_ucontext;
7699 return QualType();
7700 }
7701 break;
Eli Friedman6902e412012-11-27 02:58:24 +00007702 case 'p':
7703 Type = Context.getProcessIDType();
7704 break;
Mike Stump782fa302009-07-28 02:25:19 +00007705 }
Mike Stump1eb44332009-09-09 15:08:12 +00007706
Chris Lattner33daae62010-10-01 22:42:38 +00007707 // If there are modifiers and if we're allowed to parse them, go for it.
7708 Done = !AllowTypeModifiers;
Chris Lattner86df27b2009-06-14 00:45:47 +00007709 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00007710 switch (char c = *Str++) {
Chris Lattner33daae62010-10-01 22:42:38 +00007711 default: Done = true; --Str; break;
7712 case '*':
7713 case '&': {
7714 // Both pointers and references can have their pointee types
7715 // qualified with an address space.
7716 char *End;
7717 unsigned AddrSpace = strtoul(Str, &End, 10);
7718 if (End != Str && AddrSpace != 0) {
7719 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7720 Str = End;
7721 }
7722 if (c == '*')
7723 Type = Context.getPointerType(Type);
7724 else
7725 Type = Context.getLValueReferenceType(Type);
7726 break;
7727 }
7728 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7729 case 'C':
7730 Type = Type.withConst();
7731 break;
7732 case 'D':
7733 Type = Context.getVolatileType(Type);
7734 break;
Ted Kremenek18932a02012-01-20 21:40:12 +00007735 case 'R':
7736 Type = Type.withRestrict();
7737 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00007738 }
7739 }
Chris Lattner393bd8e2010-10-01 07:13:18 +00007740
Chris Lattner14e0e742010-10-01 22:53:11 +00007741 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner393bd8e2010-10-01 07:13:18 +00007742 "Integer constant 'I' type must be an integer");
Mike Stump1eb44332009-09-09 15:08:12 +00007743
Chris Lattner86df27b2009-06-14 00:45:47 +00007744 return Type;
7745}
7746
7747/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattner33daae62010-10-01 22:42:38 +00007748QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattner14e0e742010-10-01 22:53:11 +00007749 GetBuiltinTypeError &Error,
Jay Foad4ba2a172011-01-12 09:06:06 +00007750 unsigned *IntegerConstantArgs) const {
Chris Lattner33daae62010-10-01 22:42:38 +00007751 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump1eb44332009-09-09 15:08:12 +00007752
Chris Lattner5f9e2722011-07-23 10:55:15 +00007753 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00007754
Chris Lattner14e0e742010-10-01 22:53:11 +00007755 bool RequiresICE = false;
Chris Lattner86df27b2009-06-14 00:45:47 +00007756 Error = GE_None;
Chris Lattner14e0e742010-10-01 22:53:11 +00007757 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7758 RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00007759 if (Error != GE_None)
7760 return QualType();
Chris Lattner14e0e742010-10-01 22:53:11 +00007761
7762 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7763
Chris Lattner86df27b2009-06-14 00:45:47 +00007764 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattner14e0e742010-10-01 22:53:11 +00007765 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00007766 if (Error != GE_None)
7767 return QualType();
7768
Chris Lattner14e0e742010-10-01 22:53:11 +00007769 // If this argument is required to be an IntegerConstantExpression and the
7770 // caller cares, fill in the bitmask we return.
7771 if (RequiresICE && IntegerConstantArgs)
7772 *IntegerConstantArgs |= 1 << ArgTypes.size();
7773
Chris Lattner86df27b2009-06-14 00:45:47 +00007774 // Do array -> pointer decay. The builtin should use the decayed type.
7775 if (Ty->isArrayType())
7776 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00007777
Chris Lattner86df27b2009-06-14 00:45:47 +00007778 ArgTypes.push_back(Ty);
7779 }
7780
7781 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7782 "'.' should only occur at end of builtin type list!");
7783
John McCall00ccbef2010-12-21 00:44:39 +00007784 FunctionType::ExtInfo EI;
7785 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7786
7787 bool Variadic = (TypeStr[0] == '.');
7788
7789 // We really shouldn't be making a no-proto type here, especially in C++.
7790 if (ArgTypes.empty() && Variadic)
7791 return getFunctionNoProtoType(ResType, EI);
Douglas Gregorce056bc2010-02-21 22:15:06 +00007792
John McCalle23cf432010-12-14 08:05:40 +00007793 FunctionProtoType::ExtProtoInfo EPI;
John McCall00ccbef2010-12-21 00:44:39 +00007794 EPI.ExtInfo = EI;
7795 EPI.Variadic = Variadic;
John McCalle23cf432010-12-14 08:05:40 +00007796
Jordan Rosebea522f2013-03-08 21:51:21 +00007797 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattner86df27b2009-06-14 00:45:47 +00007798}
Eli Friedmana95d7572009-08-19 07:44:53 +00007799
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007800GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007801 if (!FD->isExternallyVisible())
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007802 return GVA_Internal;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007803
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007804 GVALinkage External = GVA_StrongExternal;
7805 switch (FD->getTemplateSpecializationKind()) {
7806 case TSK_Undeclared:
7807 case TSK_ExplicitSpecialization:
7808 External = GVA_StrongExternal;
7809 break;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007810
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007811 case TSK_ExplicitInstantiationDefinition:
7812 return GVA_ExplicitTemplateInstantiation;
7813
7814 case TSK_ExplicitInstantiationDeclaration:
7815 case TSK_ImplicitInstantiation:
7816 External = GVA_TemplateInstantiation;
7817 break;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007818 }
7819
7820 if (!FD->isInlined())
7821 return External;
7822
David Blaikie4e4d0842012-03-11 07:00:24 +00007823 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007824 // GNU or C99 inline semantics. Determine whether this symbol should be
7825 // externally visible.
7826 if (FD->isInlineDefinitionExternallyVisible())
7827 return External;
7828
7829 // C99 inline semantics, where the symbol is not externally visible.
7830 return GVA_C99Inline;
7831 }
7832
7833 // C++0x [temp.explicit]p9:
7834 // [ Note: The intent is that an inline function that is the subject of
7835 // an explicit instantiation declaration will still be implicitly
7836 // instantiated when used so that the body can be considered for
7837 // inlining, but that no out-of-line copy of the inline function would be
7838 // generated in the translation unit. -- end note ]
7839 if (FD->getTemplateSpecializationKind()
7840 == TSK_ExplicitInstantiationDeclaration)
7841 return GVA_C99Inline;
7842
7843 return GVA_CXXInline;
7844}
7845
7846GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007847 if (!VD->isExternallyVisible())
7848 return GVA_Internal;
7849
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007850 // If this is a static data member, compute the kind of template
7851 // specialization. Otherwise, this variable is not part of a
7852 // template.
7853 TemplateSpecializationKind TSK = TSK_Undeclared;
7854 if (VD->isStaticDataMember())
7855 TSK = VD->getTemplateSpecializationKind();
7856
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007857 switch (TSK) {
7858 case TSK_Undeclared:
7859 case TSK_ExplicitSpecialization:
7860 return GVA_StrongExternal;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007861
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007862 case TSK_ExplicitInstantiationDeclaration:
7863 llvm_unreachable("Variable should not be instantiated");
7864 // Fall through to treat this like any other instantiation.
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007865
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007866 case TSK_ExplicitInstantiationDefinition:
7867 return GVA_ExplicitTemplateInstantiation;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007868
Rafael Espindola181e3ec2013-05-13 00:12:11 +00007869 case TSK_ImplicitInstantiation:
7870 return GVA_TemplateInstantiation;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007871 }
Rafael Espindola77b50252013-05-13 14:05:53 +00007872
7873 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007874}
7875
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +00007876bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007877 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7878 if (!VD->isFileVarDecl())
7879 return false;
Richard Smithf396ad92013-04-01 20:22:16 +00007880 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7881 // We never need to emit an uninstantiated function template.
7882 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
7883 return false;
7884 } else
7885 return false;
7886
7887 // If this is a member of a class template, we do not need to emit it.
7888 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007889 return false;
7890
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00007891 // Weak references don't produce any output by themselves.
7892 if (D->hasAttr<WeakRefAttr>())
7893 return false;
7894
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007895 // Aliases and used decls are required.
7896 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7897 return true;
7898
7899 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7900 // Forward declarations aren't required.
Sean Hunt10620eb2011-05-06 20:44:56 +00007901 if (!FD->doesThisDeclarationHaveABody())
Nick Lewyckydce67a72011-07-18 05:26:13 +00007902 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007903
7904 // Constructors and destructors are required.
7905 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7906 return true;
7907
John McCalld5617ee2013-01-25 22:31:03 +00007908 // The key function for a class is required. This rule only comes
7909 // into play when inline functions can be key functions, though.
7910 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7911 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7912 const CXXRecordDecl *RD = MD->getParent();
7913 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7914 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
7915 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7916 return true;
7917 }
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007918 }
7919 }
7920
7921 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7922
7923 // static, static inline, always_inline, and extern inline functions can
7924 // always be deferred. Normal inline functions can be deferred in C99/C++.
7925 // Implicit template instantiations can also be deferred in C++.
7926 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev3a5aca82012-02-02 06:06:34 +00007927 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007928 return false;
7929 return true;
7930 }
Douglas Gregor94da1582011-09-10 00:22:34 +00007931
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007932 const VarDecl *VD = cast<VarDecl>(D);
7933 assert(VD->isFileVarDecl() && "Expected file scoped var");
7934
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00007935 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7936 return false;
7937
Richard Smith5f9a7e32012-11-12 21:38:00 +00007938 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007939 GVALinkage L = GetGVALinkageForVariable(VD);
Richard Smith5f9a7e32012-11-12 21:38:00 +00007940 if (L != GVA_Internal && L != GVA_TemplateInstantiation)
7941 return true;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007942
Richard Smith5f9a7e32012-11-12 21:38:00 +00007943 // Variables that have destruction with side-effects are required.
7944 if (VD->getType().isDestructedType())
7945 return true;
7946
7947 // Variables that have initialization with side-effects are required.
7948 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
7949 return true;
7950
7951 return false;
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00007952}
Charles Davis071cc7d2010-08-16 03:33:14 +00007953
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007954CallingConv ASTContext::getDefaultCXXMethodCallConv(bool isVariadic) {
Charles Davisee743f92010-11-09 18:04:24 +00007955 // Pass through to the C++ ABI object
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007956 return ABI->getDefaultMethodCallConv(isVariadic);
7957}
7958
7959CallingConv ASTContext::getCanonicalCallConv(CallingConv CC) const {
John McCallb8b2c9d2013-01-25 22:30:49 +00007960 if (CC == CC_C && !LangOpts.MRTD &&
7961 getTargetInfo().getCXXABI().isMemberFunctionCCDefault())
Timur Iskhodzhanov8f88a1d2012-07-12 09:50:54 +00007962 return CC_Default;
7963 return CC;
Charles Davisee743f92010-11-09 18:04:24 +00007964}
7965
Jay Foad4ba2a172011-01-12 09:06:06 +00007966bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlssondae0cb52010-11-25 01:51:53 +00007967 // Pass through to the C++ ABI object
7968 return ABI->isNearlyEmpty(RD);
7969}
7970
Peter Collingbourne14110472011-01-13 18:57:25 +00007971MangleContext *ASTContext::createMangleContext() {
John McCallb8b2c9d2013-01-25 22:30:49 +00007972 switch (Target->getCXXABI().getKind()) {
Tim Northoverc264e162013-01-31 12:13:10 +00007973 case TargetCXXABI::GenericAArch64:
John McCallb8b2c9d2013-01-25 22:30:49 +00007974 case TargetCXXABI::GenericItanium:
7975 case TargetCXXABI::GenericARM:
7976 case TargetCXXABI::iOS:
Peter Collingbourne14110472011-01-13 18:57:25 +00007977 return createItaniumMangleContext(*this, getDiagnostics());
John McCallb8b2c9d2013-01-25 22:30:49 +00007978 case TargetCXXABI::Microsoft:
Peter Collingbourne14110472011-01-13 18:57:25 +00007979 return createMicrosoftMangleContext(*this, getDiagnostics());
7980 }
David Blaikieb219cfc2011-09-23 05:06:16 +00007981 llvm_unreachable("Unsupported ABI");
Peter Collingbourne14110472011-01-13 18:57:25 +00007982}
7983
Charles Davis071cc7d2010-08-16 03:33:14 +00007984CXXABI::~CXXABI() {}
Ted Kremenekba29bd22011-04-28 04:53:38 +00007985
7986size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek0c8cd1a2011-07-27 18:41:12 +00007987 return ASTRecordLayouts.getMemorySize()
7988 + llvm::capacity_in_bytes(ObjCLayouts)
7989 + llvm::capacity_in_bytes(KeyFunctions)
7990 + llvm::capacity_in_bytes(ObjCImpls)
7991 + llvm::capacity_in_bytes(BlockVarCopyInits)
7992 + llvm::capacity_in_bytes(DeclAttrs)
7993 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
7994 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
7995 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
7996 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
7997 + llvm::capacity_in_bytes(OverriddenMethods)
7998 + llvm::capacity_in_bytes(Types)
Francois Pichetaf0f4d02011-08-14 03:52:19 +00007999 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet0d95f0d2011-08-14 14:28:49 +00008000 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekba29bd22011-04-28 04:53:38 +00008001}
Ted Kremenekd211cb72011-10-06 05:00:56 +00008002
David Blaikie66cff722012-11-14 01:52:05 +00008003void ASTContext::addUnnamedTag(const TagDecl *Tag) {
8004 // FIXME: This mangling should be applied to function local classes too
8005 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl() ||
Rafael Espindola5bbb0582013-05-28 14:09:46 +00008006 !isa<CXXRecordDecl>(Tag->getParent()))
David Blaikie66cff722012-11-14 01:52:05 +00008007 return;
8008
8009 std::pair<llvm::DenseMap<const DeclContext *, unsigned>::iterator, bool> P =
8010 UnnamedMangleContexts.insert(std::make_pair(Tag->getParent(), 0));
8011 UnnamedMangleNumbers.insert(std::make_pair(Tag, P.first->second++));
8012}
8013
8014int ASTContext::getUnnamedTagManglingNumber(const TagDecl *Tag) const {
8015 llvm::DenseMap<const TagDecl *, unsigned>::const_iterator I =
8016 UnnamedMangleNumbers.find(Tag);
8017 return I != UnnamedMangleNumbers.end() ? I->second : -1;
8018}
8019
Douglas Gregor9e8c92a2012-02-20 19:44:39 +00008020unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
8021 CXXRecordDecl *Lambda = CallOperator->getParent();
8022 return LambdaMangleContexts[Lambda->getDeclContext()]
8023 .getManglingNumber(CallOperator);
8024}
8025
8026
Ted Kremenekd211cb72011-10-06 05:00:56 +00008027void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8028 ParamIndices[D] = index;
8029}
8030
8031unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8032 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8033 assert(I != ParamIndices.end() &&
8034 "ParmIndices lacks entry set by ParmVarDecl");
8035 return I->second;
8036}
Fariborz Jahanian538bbe52013-05-28 17:37:39 +00008037
Richard Smith211c8dd2013-06-05 00:46:14 +00008038APValue *
8039ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8040 bool MayCreate) {
8041 assert(E && E->getStorageDuration() == SD_Static &&
8042 "don't need to cache the computed value for this temporary");
8043 if (MayCreate)
8044 return &MaterializedTemporaryValues[E];
8045
8046 llvm::DenseMap<const MaterializeTemporaryExpr *, APValue>::iterator I =
8047 MaterializedTemporaryValues.find(E);
8048 return I == MaterializedTemporaryValues.end() ? 0 : &I->second;
8049}
8050
Fariborz Jahanian538bbe52013-05-28 17:37:39 +00008051bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8052 const llvm::Triple &T = getTargetInfo().getTriple();
8053 if (!T.isOSDarwin())
8054 return false;
8055
8056 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8057 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8058 uint64_t Size = sizeChars.getQuantity();
8059 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8060 unsigned Align = alignChars.getQuantity();
8061 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8062 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8063}
Reid Klecknercff15122013-06-17 12:56:08 +00008064
8065namespace {
8066
8067 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8068 /// parents as defined by the \c RecursiveASTVisitor.
8069 ///
8070 /// Note that the relationship described here is purely in terms of AST
8071 /// traversal - there are other relationships (for example declaration context)
8072 /// in the AST that are better modeled by special matchers.
8073 ///
8074 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
8075 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
8076
8077 public:
8078 /// \brief Builds and returns the translation unit's parent map.
8079 ///
8080 /// The caller takes ownership of the returned \c ParentMap.
8081 static ASTContext::ParentMap *buildMap(TranslationUnitDecl &TU) {
8082 ParentMapASTVisitor Visitor(new ASTContext::ParentMap);
8083 Visitor.TraverseDecl(&TU);
8084 return Visitor.Parents;
8085 }
8086
8087 private:
8088 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8089
8090 ParentMapASTVisitor(ASTContext::ParentMap *Parents) : Parents(Parents) {
8091 }
8092
8093 bool shouldVisitTemplateInstantiations() const {
8094 return true;
8095 }
8096 bool shouldVisitImplicitCode() const {
8097 return true;
8098 }
8099 // Disables data recursion. We intercept Traverse* methods in the RAV, which
8100 // are not triggered during data recursion.
8101 bool shouldUseDataRecursionFor(clang::Stmt *S) const {
8102 return false;
8103 }
8104
8105 template <typename T>
8106 bool TraverseNode(T *Node, bool(VisitorBase:: *traverse) (T *)) {
8107 if (Node == NULL)
8108 return true;
8109 if (ParentStack.size() > 0)
8110 // FIXME: Currently we add the same parent multiple times, for example
8111 // when we visit all subexpressions of template instantiations; this is
8112 // suboptimal, bug benign: the only way to visit those is with
8113 // hasAncestor / hasParent, and those do not create new matches.
8114 // The plan is to enable DynTypedNode to be storable in a map or hash
8115 // map. The main problem there is to implement hash functions /
8116 // comparison operators for all types that DynTypedNode supports that
8117 // do not have pointer identity.
8118 (*Parents)[Node].push_back(ParentStack.back());
8119 ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node));
8120 bool Result = (this ->* traverse) (Node);
8121 ParentStack.pop_back();
8122 return Result;
8123 }
8124
8125 bool TraverseDecl(Decl *DeclNode) {
8126 return TraverseNode(DeclNode, &VisitorBase::TraverseDecl);
8127 }
8128
8129 bool TraverseStmt(Stmt *StmtNode) {
8130 return TraverseNode(StmtNode, &VisitorBase::TraverseStmt);
8131 }
8132
8133 ASTContext::ParentMap *Parents;
8134 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8135
8136 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8137 };
8138
8139} // end namespace
8140
8141ASTContext::ParentVector
8142ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
8143 assert(Node.getMemoizationData() &&
8144 "Invariant broken: only nodes that support memoization may be "
8145 "used in the parent map.");
8146 if (!AllParents) {
8147 // We always need to run over the whole translation unit, as
8148 // hasAncestor can escape any subtree.
8149 AllParents.reset(
8150 ParentMapASTVisitor::buildMap(*getTranslationUnitDecl()));
8151 }
8152 ParentMap::const_iterator I = AllParents->find(Node.getMemoizationData());
8153 if (I == AllParents->end()) {
8154 return ParentVector();
8155 }
8156 return I->second;
8157}