blob: 2ed345aec8d4193ffc58ad6ad6e681b7b23365ba [file] [log] [blame]
Chris Lattnerddc135e2006-11-10 06:34:16 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerddc135e2006-11-10 06:34:16 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "CXXABI.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000016#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/Attr.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000018#include "clang/AST/CharUnits.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000019#include "clang/AST/Comment.h"
Dmitri Gribenkoca7f80a2012-08-09 00:03:17 +000020#include "clang/AST/CommentCommandTraits.h"
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +000021#include "clang/AST/DeclCXX.h"
Steve Naroff67391b82007-10-01 19:00:59 +000022#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000023#include "clang/AST/DeclTemplate.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000024#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000025#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000026#include "clang/AST/ExternalASTSource.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000027#include "clang/AST/Mangle.h"
Reid Klecknerd8110b62013-09-10 20:14:30 +000028#include "clang/AST/MangleNumberingContext.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000029#include "clang/AST/RecordLayout.h"
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000030#include "clang/AST/RecursiveASTVisitor.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000031#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000032#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000033#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000034#include "clang/Basic/TargetInfo.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000035#include "llvm/ADT/SmallString.h"
Anders Carlssond8499822007-10-29 05:01:08 +000036#include "llvm/ADT/StringExtras.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000037#include "llvm/Support/Capacity.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000038#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000039#include "llvm/Support/raw_ostream.h"
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +000040#include <map>
Anders Carlssona4267a62009-07-18 21:19:52 +000041
Chris Lattnerddc135e2006-11-10 06:34:16 +000042using namespace clang;
43
Douglas Gregor9672f922010-07-03 00:47:00 +000044unsigned ASTContext::NumImplicitDefaultConstructors;
45unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000046unsigned ASTContext::NumImplicitCopyConstructors;
47unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000048unsigned ASTContext::NumImplicitMoveConstructors;
49unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +000050unsigned ASTContext::NumImplicitCopyAssignmentOperators;
51unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000052unsigned ASTContext::NumImplicitMoveAssignmentOperators;
53unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +000054unsigned ASTContext::NumImplicitDestructors;
55unsigned ASTContext::NumImplicitDestructorsDeclared;
56
Steve Naroff0af91202007-04-27 21:51:21 +000057enum FloatingRank {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +000058 HalfRank, FloatRank, DoubleRank, LongDoubleRank
Steve Naroff0af91202007-04-27 21:51:21 +000059};
60
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000061RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000062 if (!CommentsLoaded && ExternalSource) {
63 ExternalSource->ReadComments();
64 CommentsLoaded = true;
65 }
66
67 assert(D);
68
Dmitri Gribenkodf17d642012-06-28 16:19:39 +000069 // User can not attach documentation to implicit declarations.
70 if (D->isImplicit())
71 return NULL;
72
Dmitri Gribenkob2610882012-08-14 17:17:18 +000073 // User can not attach documentation to implicit instantiations.
74 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
75 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
76 return NULL;
77 }
78
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000079 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
80 if (VD->isStaticDataMember() &&
81 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
82 return NULL;
83 }
84
85 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
86 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
87 return NULL;
88 }
89
Dmitri Gribenko01b06512013-01-27 21:18:39 +000090 if (const ClassTemplateSpecializationDecl *CTSD =
91 dyn_cast<ClassTemplateSpecializationDecl>(D)) {
92 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
93 if (TSK == TSK_ImplicitInstantiation ||
94 TSK == TSK_Undeclared)
95 return NULL;
96 }
97
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000098 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
99 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
100 return NULL;
101 }
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000102 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
103 // When tag declaration (but not definition!) is part of the
104 // decl-specifier-seq of some other declaration, it doesn't get comment
105 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
106 return NULL;
107 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000108 // TODO: handle comments for function parameters properly.
109 if (isa<ParmVarDecl>(D))
110 return NULL;
111
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000112 // TODO: we could look up template parameter documentation in the template
113 // documentation.
114 if (isa<TemplateTypeParmDecl>(D) ||
115 isa<NonTypeTemplateParmDecl>(D) ||
116 isa<TemplateTemplateParmDecl>(D))
117 return NULL;
118
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000119 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000120
121 // If there are no comments anywhere, we won't find anything.
122 if (RawComments.empty())
123 return NULL;
124
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000125 // Find declaration location.
126 // For Objective-C declarations we generally don't expect to have multiple
127 // declarators, thus use declaration starting location as the "declaration
128 // location".
129 // For all other declarations multiple declarators are used quite frequently,
130 // so we use the location of the identifier as the "declaration location".
131 SourceLocation DeclLoc;
132 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000133 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +0000134 isa<RedeclarableTemplateDecl>(D) ||
135 isa<ClassTemplateSpecializationDecl>(D))
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000136 DeclLoc = D->getLocStart();
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000137 else {
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000138 DeclLoc = D->getLocation();
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000139 // If location of the typedef name is in a macro, it is because being
140 // declared via a macro. Try using declaration's starting location
141 // as the "declaration location".
142 if (DeclLoc.isMacroID() && isa<TypedefDecl>(D))
143 DeclLoc = D->getLocStart();
144 }
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000145
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000146 // If the declaration doesn't map directly to a location in a file, we
147 // can't find the comment.
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000148 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
149 return NULL;
150
151 // Find the comment that occurs just after this declaration.
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000152 ArrayRef<RawComment *>::iterator Comment;
153 {
154 // When searching for comments during parsing, the comment we are looking
155 // for is usually among the last two comments we parsed -- check them
156 // first.
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +0000157 RawComment CommentAtDeclLoc(
158 SourceMgr, SourceRange(DeclLoc), false,
159 LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000160 BeforeThanCompare<RawComment> Compare(SourceMgr);
161 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
162 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
163 if (!Found && RawComments.size() >= 2) {
164 MaybeBeforeDecl--;
165 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
166 }
167
168 if (Found) {
169 Comment = MaybeBeforeDecl + 1;
170 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
171 &CommentAtDeclLoc, Compare));
172 } else {
173 // Slow path.
174 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
175 &CommentAtDeclLoc, Compare);
176 }
177 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000178
179 // Decompose the location for the declaration and find the beginning of the
180 // file buffer.
181 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
182
183 // First check whether we have a trailing comment.
184 if (Comment != RawComments.end() &&
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000185 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
Fariborz Jahanianfad28542013-08-06 23:29:00 +0000186 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
Fariborz Jahanian3ab62222013-08-07 16:40:29 +0000187 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000188 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000189 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000190 // Check that Doxygen trailing comment comes after the declaration, starts
191 // on the same line and in the same file as the declaration.
192 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
193 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
194 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
195 CommentBeginDecomp.second)) {
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000196 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000197 }
198 }
199
200 // The comment just after the declaration was not a trailing comment.
201 // Let's look at the previous comment.
202 if (Comment == RawComments.begin())
203 return NULL;
204 --Comment;
205
206 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000207 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000208 return NULL;
209
210 // Decompose the end of the comment.
211 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000212 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000213
214 // If the comment and the declaration aren't in the same file, then they
215 // aren't related.
216 if (DeclLocDecomp.first != CommentEndDecomp.first)
217 return NULL;
218
219 // Get the corresponding buffer.
220 bool Invalid = false;
221 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
222 &Invalid).data();
223 if (Invalid)
224 return NULL;
225
226 // Extract text between the comment and declaration.
227 StringRef Text(Buffer + CommentEndDecomp.second,
228 DeclLocDecomp.second - CommentEndDecomp.second);
229
Dmitri Gribenko7e8729b2012-06-27 23:43:37 +0000230 // There should be no other declarations or preprocessor directives between
231 // comment and declaration.
Argyrios Kyrtzidisb534d3a2013-07-26 18:38:12 +0000232 if (Text.find_first_of(";{}#@") != StringRef::npos)
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000233 return NULL;
234
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000235 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000236}
237
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000238namespace {
239/// If we have a 'templated' declaration for a template, adjust 'D' to
240/// refer to the actual template.
Dmitri Gribenko90631802012-08-22 17:44:32 +0000241/// If we have an implicit instantiation, adjust 'D' to refer to template.
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000242const Decl *adjustDeclToTemplate(const Decl *D) {
Douglas Gregor35ceb272012-08-13 16:37:30 +0000243 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000244 // Is this function declaration part of a function template?
Douglas Gregor35ceb272012-08-13 16:37:30 +0000245 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko90631802012-08-22 17:44:32 +0000246 return FTD;
247
248 // Nothing to do if function is not an implicit instantiation.
249 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
250 return D;
251
252 // Function is an implicit instantiation of a function template?
253 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
254 return FTD;
255
256 // Function is instantiated from a member definition of a class template?
257 if (const FunctionDecl *MemberDecl =
258 FD->getInstantiatedFromMemberFunction())
259 return MemberDecl;
260
261 return D;
Douglas Gregor35ceb272012-08-13 16:37:30 +0000262 }
Dmitri Gribenko90631802012-08-22 17:44:32 +0000263 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
264 // Static data member is instantiated from a member definition of a class
265 // template?
266 if (VD->isStaticDataMember())
267 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
268 return MemberDecl;
269
270 return D;
271 }
272 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
273 // Is this class declaration part of a class template?
274 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
275 return CTD;
276
277 // Class is an implicit instantiation of a class template or partial
278 // specialization?
279 if (const ClassTemplateSpecializationDecl *CTSD =
280 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
281 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
282 return D;
283 llvm::PointerUnion<ClassTemplateDecl *,
284 ClassTemplatePartialSpecializationDecl *>
285 PU = CTSD->getSpecializedTemplateOrPartial();
286 return PU.is<ClassTemplateDecl*>() ?
287 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
288 static_cast<const Decl*>(
289 PU.get<ClassTemplatePartialSpecializationDecl *>());
290 }
291
292 // Class is instantiated from a member definition of a class template?
293 if (const MemberSpecializationInfo *Info =
294 CRD->getMemberSpecializationInfo())
295 return Info->getInstantiatedFrom();
296
297 return D;
298 }
299 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
300 // Enum is instantiated from a member definition of a class template?
301 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
302 return MemberDecl;
303
304 return D;
305 }
306 // FIXME: Adjust alias templates?
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000307 return D;
308}
309} // unnamed namespace
310
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000311const RawComment *ASTContext::getRawCommentForAnyRedecl(
312 const Decl *D,
313 const Decl **OriginalDecl) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000314 D = adjustDeclToTemplate(D);
Douglas Gregor35ceb272012-08-13 16:37:30 +0000315
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000316 // Check whether we have cached a comment for this declaration already.
317 {
318 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
319 RedeclComments.find(D);
320 if (Pos != RedeclComments.end()) {
321 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000322 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
323 if (OriginalDecl)
324 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000325 return Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000326 }
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000327 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000328 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000329
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000330 // Search for comments attached to declarations in the redeclaration chain.
331 const RawComment *RC = NULL;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000332 const Decl *OriginalDeclForRC = NULL;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000333 for (Decl::redecl_iterator I = D->redecls_begin(),
334 E = D->redecls_end();
335 I != E; ++I) {
336 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
337 RedeclComments.find(*I);
338 if (Pos != RedeclComments.end()) {
339 const RawCommentAndCacheFlags &Raw = Pos->second;
340 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
341 RC = Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000342 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000343 break;
344 }
345 } else {
346 RC = getRawCommentForDeclNoCache(*I);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000347 OriginalDeclForRC = *I;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000348 RawCommentAndCacheFlags Raw;
349 if (RC) {
350 Raw.setRaw(RC);
351 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
352 } else
353 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000354 Raw.setOriginalDecl(*I);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000355 RedeclComments[*I] = Raw;
356 if (RC)
357 break;
358 }
359 }
360
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000361 // If we found a comment, it should be a documentation comment.
362 assert(!RC || RC->isDocumentation());
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000363
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000364 if (OriginalDecl)
365 *OriginalDecl = OriginalDeclForRC;
366
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000367 // Update cache for every declaration in the redeclaration chain.
368 RawCommentAndCacheFlags Raw;
369 Raw.setRaw(RC);
370 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000371 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000372
373 for (Decl::redecl_iterator I = D->redecls_begin(),
374 E = D->redecls_end();
375 I != E; ++I) {
376 RawCommentAndCacheFlags &R = RedeclComments[*I];
377 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
378 R = Raw;
379 }
380
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000381 return RC;
382}
383
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000384static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
385 SmallVectorImpl<const NamedDecl *> &Redeclared) {
386 const DeclContext *DC = ObjCMethod->getDeclContext();
387 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
388 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
389 if (!ID)
390 return;
391 // Add redeclared method here.
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000392 for (ObjCInterfaceDecl::known_extensions_iterator
393 Ext = ID->known_extensions_begin(),
394 ExtEnd = ID->known_extensions_end();
395 Ext != ExtEnd; ++Ext) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000396 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000397 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000398 ObjCMethod->isInstanceMethod()))
399 Redeclared.push_back(RedeclaredMethod);
400 }
401 }
402}
403
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000404comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
405 const Decl *D) const {
406 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
407 ThisDeclInfo->CommentDecl = D;
408 ThisDeclInfo->IsFilled = false;
409 ThisDeclInfo->fill();
410 ThisDeclInfo->CommentDecl = FC->getDecl();
411 comments::FullComment *CFC =
412 new (*this) comments::FullComment(FC->getBlocks(),
413 ThisDeclInfo);
414 return CFC;
415
416}
417
Richard Smithb39b9d52013-05-21 05:24:00 +0000418comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
419 const RawComment *RC = getRawCommentForDeclNoCache(D);
420 return RC ? RC->parse(*this, 0, D) : 0;
421}
422
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000423comments::FullComment *ASTContext::getCommentForDecl(
424 const Decl *D,
425 const Preprocessor *PP) const {
Fariborz Jahanian096f7c12013-05-13 17:27:00 +0000426 if (D->isInvalidDecl())
427 return NULL;
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000428 D = adjustDeclToTemplate(D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000429
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000430 const Decl *Canonical = D->getCanonicalDecl();
431 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
432 ParsedComments.find(Canonical);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000433
434 if (Pos != ParsedComments.end()) {
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000435 if (Canonical != D) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000436 comments::FullComment *FC = Pos->second;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000437 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000438 return CFC;
439 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000440 return Pos->second;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000441 }
442
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000443 const Decl *OriginalDecl;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000444
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000445 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000446 if (!RC) {
447 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000448 SmallVector<const NamedDecl*, 8> Overridden;
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000449 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000450 if (OMD && OMD->isPropertyAccessor())
451 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
452 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
453 return cloneFullComment(FC, D);
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000454 if (OMD)
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000455 addRedeclaredMethods(OMD, Overridden);
456 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000457 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
458 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
459 return cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000460 }
Fariborz Jahanian6384fbb2013-05-02 15:44:16 +0000461 else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000462 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000463 // does not have one of its own.
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000464 QualType QT = TD->getUnderlyingType();
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000465 if (const TagType *TT = QT->getAs<TagType>())
466 if (const Decl *TD = TT->getDecl())
467 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000468 return cloneFullComment(FC, D);
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000469 }
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000470 else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
471 while (IC->getSuperClass()) {
472 IC = IC->getSuperClass();
473 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
474 return cloneFullComment(FC, D);
475 }
476 }
477 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
478 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
479 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
480 return cloneFullComment(FC, D);
481 }
482 else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
483 if (!(RD = RD->getDefinition()))
484 return NULL;
485 // Check non-virtual bases.
486 for (CXXRecordDecl::base_class_const_iterator I =
487 RD->bases_begin(), E = RD->bases_end(); I != E; ++I) {
Fariborz Jahanian5a2e4a22013-04-26 23:34:36 +0000488 if (I->isVirtual() || (I->getAccessSpecifier() != AS_public))
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000489 continue;
490 QualType Ty = I->getType();
491 if (Ty.isNull())
492 continue;
493 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
494 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
495 continue;
496
497 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
498 return cloneFullComment(FC, D);
499 }
500 }
501 // Check virtual bases.
502 for (CXXRecordDecl::base_class_const_iterator I =
503 RD->vbases_begin(), E = RD->vbases_end(); I != E; ++I) {
Fariborz Jahanian5a2e4a22013-04-26 23:34:36 +0000504 if (I->getAccessSpecifier() != AS_public)
505 continue;
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000506 QualType Ty = I->getType();
507 if (Ty.isNull())
508 continue;
509 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
510 if (!(VirtualBase= VirtualBase->getDefinition()))
511 continue;
512 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
513 return cloneFullComment(FC, D);
514 }
515 }
516 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000517 return NULL;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000518 }
519
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000520 // If the RawComment was attached to other redeclaration of this Decl, we
521 // should parse the comment in context of that other Decl. This is important
522 // because comments can contain references to parameter names which can be
523 // different across redeclarations.
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000524 if (D != OriginalDecl)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000525 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000526
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000527 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000528 ParsedComments[Canonical] = FC;
529 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000530}
531
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000532void
533ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
534 TemplateTemplateParmDecl *Parm) {
535 ID.AddInteger(Parm->getDepth());
536 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000537 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000538
539 TemplateParameterList *Params = Parm->getTemplateParameters();
540 ID.AddInteger(Params->size());
541 for (TemplateParameterList::const_iterator P = Params->begin(),
542 PEnd = Params->end();
543 P != PEnd; ++P) {
544 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
545 ID.AddInteger(0);
546 ID.AddBoolean(TTP->isParameterPack());
547 continue;
548 }
549
550 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
551 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000552 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000553 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000554 if (NTTP->isExpandedParameterPack()) {
555 ID.AddBoolean(true);
556 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000557 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
558 QualType T = NTTP->getExpansionType(I);
559 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
560 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000561 } else
562 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000563 continue;
564 }
565
566 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
567 ID.AddInteger(2);
568 Profile(ID, TTP);
569 }
570}
571
572TemplateTemplateParmDecl *
573ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000574 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000575 // Check if we already have a canonical template template parameter.
576 llvm::FoldingSetNodeID ID;
577 CanonicalTemplateTemplateParm::Profile(ID, TTP);
578 void *InsertPos = 0;
579 CanonicalTemplateTemplateParm *Canonical
580 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
581 if (Canonical)
582 return Canonical->getParam();
583
584 // Build a canonical template parameter list.
585 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000586 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000587 CanonParams.reserve(Params->size());
588 for (TemplateParameterList::const_iterator P = Params->begin(),
589 PEnd = Params->end();
590 P != PEnd; ++P) {
591 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
592 CanonParams.push_back(
593 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000594 SourceLocation(),
595 SourceLocation(),
596 TTP->getDepth(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000597 TTP->getIndex(), 0, false,
598 TTP->isParameterPack()));
599 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000600 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
601 QualType T = getCanonicalType(NTTP->getType());
602 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
603 NonTypeTemplateParmDecl *Param;
604 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000605 SmallVector<QualType, 2> ExpandedTypes;
606 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000607 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
608 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
609 ExpandedTInfos.push_back(
610 getTrivialTypeSourceInfo(ExpandedTypes.back()));
611 }
612
613 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000614 SourceLocation(),
615 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000616 NTTP->getDepth(),
617 NTTP->getPosition(), 0,
618 T,
619 TInfo,
620 ExpandedTypes.data(),
621 ExpandedTypes.size(),
622 ExpandedTInfos.data());
623 } else {
624 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000625 SourceLocation(),
626 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000627 NTTP->getDepth(),
628 NTTP->getPosition(), 0,
629 T,
630 NTTP->isParameterPack(),
631 TInfo);
632 }
633 CanonParams.push_back(Param);
634
635 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000636 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
637 cast<TemplateTemplateParmDecl>(*P)));
638 }
639
640 TemplateTemplateParmDecl *CanonTTP
641 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
642 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000643 TTP->getPosition(),
644 TTP->isParameterPack(),
645 0,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000646 TemplateParameterList::Create(*this, SourceLocation(),
647 SourceLocation(),
648 CanonParams.data(),
649 CanonParams.size(),
650 SourceLocation()));
651
652 // Get the new insert position for the node we care about.
653 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
654 assert(Canonical == 0 && "Shouldn't be in the map!");
655 (void)Canonical;
656
657 // Create the canonical template template parameter entry.
658 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
659 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
660 return CanonTTP;
661}
662
Charles Davis53c59df2010-08-16 03:33:14 +0000663CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000664 if (!LangOpts.CPlusPlus) return 0;
665
John McCall359b8852013-01-25 22:30:49 +0000666 switch (T.getCXXABI().getKind()) {
667 case TargetCXXABI::GenericARM:
668 case TargetCXXABI::iOS:
John McCall86353412010-08-21 22:46:04 +0000669 return CreateARMCXXABI(*this);
Tim Northover9bb857a2013-01-31 12:13:10 +0000670 case TargetCXXABI::GenericAArch64: // Same as Itanium at this level
John McCall359b8852013-01-25 22:30:49 +0000671 case TargetCXXABI::GenericItanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000672 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000673 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000674 return CreateMicrosoftCXXABI(*this);
675 }
David Blaikie8a40f702012-01-17 06:56:22 +0000676 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000677}
678
Douglas Gregore8bbc122011-09-02 00:18:52 +0000679static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000680 const LangOptions &LOpts) {
681 if (LOpts.FakeAddressSpaceMap) {
682 // The fake address space map must have a distinct entry for each
683 // language-specific address space.
684 static const unsigned FakeAddrSpaceMap[] = {
685 1, // opencl_global
686 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000687 3, // opencl_constant
688 4, // cuda_device
689 5, // cuda_constant
690 6 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000691 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000692 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000693 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000694 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000695 }
696}
697
David Tweed31d09b02013-09-13 12:04:22 +0000698static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
699 const LangOptions &LangOpts) {
700 switch (LangOpts.getAddressSpaceMapMangling()) {
David Tweed31d09b02013-09-13 12:04:22 +0000701 case LangOptions::ASMM_Target:
702 return TI.useAddressSpaceMapMangling();
703 case LangOptions::ASMM_On:
704 return true;
705 case LangOptions::ASMM_Off:
706 return false;
707 }
NAKAMURA Takumi5c81ca42013-09-13 17:12:09 +0000708 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
David Tweed31d09b02013-09-13 12:04:22 +0000709}
710
Douglas Gregor7018d5b2011-09-01 20:23:19 +0000711ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000712 const TargetInfo *t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000713 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000714 Builtin::Context &builtins,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000715 unsigned size_reserve,
716 bool DelayInitialization)
717 : FunctionProtoTypes(this_()),
718 TemplateSpecializationTypes(this_()),
719 DependentTemplateSpecializationTypes(this_()),
720 SubstTemplateTemplateParmPacks(this_()),
721 GlobalNestedNameSpecifier(0),
Nico Webere1687c52013-06-20 21:44:55 +0000722 Int128Decl(0), UInt128Decl(0), Float128StubDecl(0),
Meador Inge5d3fb222012-06-16 03:34:49 +0000723 BuiltinVaListDecl(0),
Douglas Gregord53ae832012-01-17 18:09:05 +0000724 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Fariborz Jahanianf2578572012-08-30 18:49:41 +0000725 BOOLDecl(0),
Douglas Gregorbab8a962011-09-08 01:46:34 +0000726 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000727 FILEDecl(0),
Rafael Espindola6cfa82b2011-11-13 21:51:09 +0000728 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
729 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
730 cudaConfigureCallDecl(0),
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000731 NullTypeSourceInfo(QualType()),
732 FirstLocalImport(), LastLocalImport(),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000733 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000734 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000735 Idents(idents), Selectors(sels),
736 BuiltinInfo(builtins),
737 DeclarationNames(*this),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000738 ExternalSource(0), Listener(0),
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000739 Comments(SM), CommentsLoaded(false),
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000740 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
Rafael Espindolace2168f2013-05-29 19:51:12 +0000741 LastSDM(0, 0)
Douglas Gregore8bbc122011-09-02 00:18:52 +0000742{
Mike Stump11289f42009-09-09 15:08:12 +0000743 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000744 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000745
746 if (!DelayInitialization) {
747 assert(t && "No target supplied for ASTContext initialization");
748 InitBuiltinTypes(*t);
749 }
Daniel Dunbar221fa942008-08-11 04:54:23 +0000750}
751
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000752ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000753 // Release the DenseMaps associated with DeclContext objects.
754 // FIXME: Is this the ideal solution?
755 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000756
Manuel Klimeka7328992013-06-03 13:51:33 +0000757 // Call all of the deallocation functions on all of their targets.
758 for (DeallocationMap::const_iterator I = Deallocations.begin(),
759 E = Deallocations.end(); I != E; ++I)
760 for (unsigned J = 0, N = I->second.size(); J != N; ++J)
761 (I->first)((I->second)[J]);
762
Ted Kremenek076baeb2010-06-08 23:00:58 +0000763 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000764 // because they can contain DenseMaps.
765 for (llvm::DenseMap<const ObjCContainerDecl*,
766 const ASTRecordLayout*>::iterator
767 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
768 // Increment in loop to prevent using deallocated memory.
769 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
770 R->Destroy(*this);
771
Ted Kremenek076baeb2010-06-08 23:00:58 +0000772 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
773 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
774 // Increment in loop to prevent using deallocated memory.
775 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
776 R->Destroy(*this);
777 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000778
779 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
780 AEnd = DeclAttrs.end();
781 A != AEnd; ++A)
782 A->second->~AttrVec();
Reid Klecknerd8110b62013-09-10 20:14:30 +0000783
784 for (llvm::DenseMap<const DeclContext *, MangleNumberingContext *>::iterator
785 I = MangleNumberingContexts.begin(),
786 E = MangleNumberingContexts.end();
787 I != E; ++I)
788 delete I->second;
Douglas Gregor561eceb2010-08-30 16:49:28 +0000789}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000790
Douglas Gregor1a809332010-05-23 18:26:36 +0000791void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Manuel Klimeka7328992013-06-03 13:51:33 +0000792 Deallocations[Callback].push_back(Data);
Douglas Gregor1a809332010-05-23 18:26:36 +0000793}
794
Mike Stump11289f42009-09-09 15:08:12 +0000795void
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000796ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000797 ExternalSource.reset(Source.take());
798}
799
Chris Lattner4eb445d2007-01-26 01:27:23 +0000800void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000801 llvm::errs() << "\n*** AST Context Stats:\n";
802 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000803
Douglas Gregora30d0462009-05-26 14:40:08 +0000804 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000805#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000806#define ABSTRACT_TYPE(Name, Parent)
807#include "clang/AST/TypeNodes.def"
808 0 // Extra
809 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000810
Chris Lattner4eb445d2007-01-26 01:27:23 +0000811 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
812 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000813 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000814 }
815
Douglas Gregora30d0462009-05-26 14:40:08 +0000816 unsigned Idx = 0;
817 unsigned TotalBytes = 0;
818#define TYPE(Name, Parent) \
819 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000820 llvm::errs() << " " << counts[Idx] << " " << #Name \
821 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000822 TotalBytes += counts[Idx] * sizeof(Name##Type); \
823 ++Idx;
824#define ABSTRACT_TYPE(Name, Parent)
825#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000826
Chandler Carruth3c147a72011-07-04 05:32:14 +0000827 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
828
Douglas Gregor7454c562010-07-02 20:37:36 +0000829 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000830 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
831 << NumImplicitDefaultConstructors
832 << " implicit default constructors created\n";
833 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
834 << NumImplicitCopyConstructors
835 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000836 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000837 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
838 << NumImplicitMoveConstructors
839 << " implicit move constructors created\n";
840 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
841 << NumImplicitCopyAssignmentOperators
842 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000843 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000844 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
845 << NumImplicitMoveAssignmentOperators
846 << " implicit move assignment operators created\n";
847 llvm::errs() << NumImplicitDestructorsDeclared << "/"
848 << NumImplicitDestructors
849 << " implicit destructors created\n";
850
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000851 if (ExternalSource.get()) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000852 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000853 ExternalSource->PrintStats();
854 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000855
Douglas Gregor5b11d492010-07-25 17:53:33 +0000856 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000857}
858
Douglas Gregor801c99d2011-08-12 06:49:56 +0000859TypedefDecl *ASTContext::getInt128Decl() const {
860 if (!Int128Decl) {
861 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
862 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
863 getTranslationUnitDecl(),
864 SourceLocation(),
865 SourceLocation(),
866 &Idents.get("__int128_t"),
867 TInfo);
868 }
869
870 return Int128Decl;
871}
872
873TypedefDecl *ASTContext::getUInt128Decl() const {
874 if (!UInt128Decl) {
875 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
876 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
877 getTranslationUnitDecl(),
878 SourceLocation(),
879 SourceLocation(),
880 &Idents.get("__uint128_t"),
881 TInfo);
882 }
883
884 return UInt128Decl;
885}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000886
Nico Webere1687c52013-06-20 21:44:55 +0000887TypeDecl *ASTContext::getFloat128StubType() const {
Nico Weber5b0b46f2013-06-21 01:29:36 +0000888 assert(LangOpts.CPlusPlus && "should only be called for c++");
Nico Webere1687c52013-06-20 21:44:55 +0000889 if (!Float128StubDecl) {
Nico Weber95296d42013-06-20 23:30:30 +0000890 Float128StubDecl = CXXRecordDecl::Create(const_cast<ASTContext &>(*this),
891 TTK_Struct,
892 getTranslationUnitDecl(),
893 SourceLocation(),
894 SourceLocation(),
895 &Idents.get("__float128"));
Nico Webere1687c52013-06-20 21:44:55 +0000896 }
897
898 return Float128StubDecl;
899}
900
John McCall48f2d582009-10-23 23:03:21 +0000901void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000902 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000903 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000904 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000905}
906
Douglas Gregore8bbc122011-09-02 00:18:52 +0000907void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
908 assert((!this->Target || this->Target == &Target) &&
909 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000910 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000911
Douglas Gregore8bbc122011-09-02 00:18:52 +0000912 this->Target = &Target;
913
914 ABI.reset(createCXXABI(Target));
915 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +0000916 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000917
Chris Lattner970e54e2006-11-12 00:37:36 +0000918 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000919 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000920
Chris Lattner970e54e2006-11-12 00:37:36 +0000921 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000922 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000923 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000924 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000925 InitBuiltinType(CharTy, BuiltinType::Char_S);
926 else
927 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000928 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000929 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
930 InitBuiltinType(ShortTy, BuiltinType::Short);
931 InitBuiltinType(IntTy, BuiltinType::Int);
932 InitBuiltinType(LongTy, BuiltinType::Long);
933 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000934
Chris Lattner970e54e2006-11-12 00:37:36 +0000935 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000936 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
937 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
938 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
939 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
940 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000941
Chris Lattner970e54e2006-11-12 00:37:36 +0000942 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000943 InitBuiltinType(FloatTy, BuiltinType::Float);
944 InitBuiltinType(DoubleTy, BuiltinType::Double);
945 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000946
Chris Lattnerf122cef2009-04-30 02:43:43 +0000947 // GNU extension, 128-bit integers.
948 InitBuiltinType(Int128Ty, BuiltinType::Int128);
949 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
950
Hans Wennborg0d81e012013-05-10 10:08:40 +0000951 // C++ 3.9.1p5
952 if (TargetInfo::isTypeSigned(Target.getWCharType()))
953 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
954 else // -fshort-wchar makes wchar_t be unsigned.
955 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
956 if (LangOpts.CPlusPlus && LangOpts.WChar)
957 WideCharTy = WCharTy;
958 else {
959 // C99 (or C++ using -fno-wchar).
960 WideCharTy = getFromTargetType(Target.getWCharType());
961 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000962
James Molloy36365542012-05-04 10:55:22 +0000963 WIntTy = getFromTargetType(Target.getWIntType());
964
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000965 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
966 InitBuiltinType(Char16Ty, BuiltinType::Char16);
967 else // C99
968 Char16Ty = getFromTargetType(Target.getChar16Type());
969
970 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
971 InitBuiltinType(Char32Ty, BuiltinType::Char32);
972 else // C99
973 Char32Ty = getFromTargetType(Target.getChar32Type());
974
Douglas Gregor4619e432008-12-05 23:32:09 +0000975 // Placeholder type for type-dependent expressions whose type is
976 // completely unknown. No code should ever check a type against
977 // DependentTy and users should never see it; however, it is here to
978 // help diagnose failures to properly check for type-dependent
979 // expressions.
980 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000981
John McCall36e7fe32010-10-12 00:20:44 +0000982 // Placeholder type for functions.
983 InitBuiltinType(OverloadTy, BuiltinType::Overload);
984
John McCall0009fcc2011-04-26 20:42:42 +0000985 // Placeholder type for bound members.
986 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
987
John McCall526ab472011-10-25 17:37:35 +0000988 // Placeholder type for pseudo-objects.
989 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
990
John McCall31996342011-04-07 08:22:57 +0000991 // "any" type; useful for debugger-like clients.
992 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
993
John McCall8a6b59a2011-10-17 18:09:15 +0000994 // Placeholder type for unbridged ARC casts.
995 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
996
Eli Friedman34866c72012-08-31 00:14:07 +0000997 // Placeholder type for builtin functions.
998 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
999
Chris Lattner970e54e2006-11-12 00:37:36 +00001000 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +00001001 FloatComplexTy = getComplexType(FloatTy);
1002 DoubleComplexTy = getComplexType(DoubleTy);
1003 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001004
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001005 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001006 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1007 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001008 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001009
1010 if (LangOpts.OpenCL) {
1011 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
1012 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
1013 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
1014 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
1015 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
1016 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001017
Guy Benyei61054192013-02-07 10:55:47 +00001018 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001019 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001020 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001021
1022 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001023 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1024 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001025
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001026 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001027
1028 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001029
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001030 // void * type
1031 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +00001032
1033 // nullptr type (C++0x 2.14.7)
1034 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001035
1036 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1037 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001038
1039 // Builtin type used to help define __builtin_va_list.
1040 VaListTagTy = QualType();
Chris Lattner970e54e2006-11-12 00:37:36 +00001041}
1042
David Blaikie9c902b52011-09-25 23:23:43 +00001043DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001044 return SourceMgr.getDiagnostics();
1045}
1046
Douglas Gregor561eceb2010-08-30 16:49:28 +00001047AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1048 AttrVec *&Result = DeclAttrs[D];
1049 if (!Result) {
1050 void *Mem = Allocate(sizeof(AttrVec));
1051 Result = new (Mem) AttrVec;
1052 }
1053
1054 return *Result;
1055}
1056
1057/// \brief Erase the attributes corresponding to the given declaration.
1058void ASTContext::eraseDeclAttrs(const Decl *D) {
1059 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1060 if (Pos != DeclAttrs.end()) {
1061 Pos->second->~AttrVec();
1062 DeclAttrs.erase(Pos);
1063 }
1064}
1065
Larisse Voufo39a1e502013-08-06 01:03:05 +00001066// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001067MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001068ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001069 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001070 return getTemplateOrSpecializationInfo(Var)
1071 .dyn_cast<MemberSpecializationInfo *>();
1072}
1073
1074ASTContext::TemplateOrSpecializationInfo
1075ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1076 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1077 TemplateOrInstantiation.find(Var);
1078 if (Pos == TemplateOrInstantiation.end())
1079 return TemplateOrSpecializationInfo();
Mike Stump11289f42009-09-09 15:08:12 +00001080
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001081 return Pos->second;
1082}
1083
Mike Stump11289f42009-09-09 15:08:12 +00001084void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001085ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001086 TemplateSpecializationKind TSK,
1087 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001088 assert(Inst->isStaticDataMember() && "Not a static data member");
1089 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001090 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1091 Tmpl, TSK, PointOfInstantiation));
1092}
1093
1094void
1095ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1096 TemplateOrSpecializationInfo TSI) {
1097 assert(!TemplateOrInstantiation[Inst] &&
1098 "Already noted what the variable was instantiated from");
1099 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001100}
1101
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001102FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1103 const FunctionDecl *FD){
1104 assert(FD && "Specialization is 0");
1105 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001106 = ClassScopeSpecializationPattern.find(FD);
1107 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001108 return 0;
1109
1110 return Pos->second;
1111}
1112
1113void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1114 FunctionDecl *Pattern) {
1115 assert(FD && "Specialization is 0");
1116 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001117 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001118}
1119
John McCalle61f2ba2009-11-18 02:36:19 +00001120NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +00001121ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +00001122 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +00001123 = InstantiatedFromUsingDecl.find(UUD);
1124 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001125 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001126
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001127 return Pos->second;
1128}
1129
1130void
John McCallb96ec562009-12-04 22:46:56 +00001131ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1132 assert((isa<UsingDecl>(Pattern) ||
1133 isa<UnresolvedUsingValueDecl>(Pattern) ||
1134 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1135 "pattern decl is not a using decl");
1136 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1137 InstantiatedFromUsingDecl[Inst] = Pattern;
1138}
1139
1140UsingShadowDecl *
1141ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1142 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1143 = InstantiatedFromUsingShadowDecl.find(Inst);
1144 if (Pos == InstantiatedFromUsingShadowDecl.end())
1145 return 0;
1146
1147 return Pos->second;
1148}
1149
1150void
1151ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1152 UsingShadowDecl *Pattern) {
1153 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1154 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001155}
1156
Anders Carlsson5da84842009-09-01 04:26:58 +00001157FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1158 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1159 = InstantiatedFromUnnamedFieldDecl.find(Field);
1160 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1161 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001162
Anders Carlsson5da84842009-09-01 04:26:58 +00001163 return Pos->second;
1164}
1165
1166void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1167 FieldDecl *Tmpl) {
1168 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1169 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1170 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1171 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001172
Anders Carlsson5da84842009-09-01 04:26:58 +00001173 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1174}
1175
Douglas Gregor832940b2010-03-02 23:58:15 +00001176ASTContext::overridden_cxx_method_iterator
1177ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1178 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001179 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001180 if (Pos == OverriddenMethods.end())
1181 return 0;
1182
1183 return Pos->second.begin();
1184}
1185
1186ASTContext::overridden_cxx_method_iterator
1187ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1188 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001189 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001190 if (Pos == OverriddenMethods.end())
1191 return 0;
1192
1193 return Pos->second.end();
1194}
1195
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001196unsigned
1197ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1198 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001199 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001200 if (Pos == OverriddenMethods.end())
1201 return 0;
1202
1203 return Pos->second.size();
1204}
1205
Douglas Gregor832940b2010-03-02 23:58:15 +00001206void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1207 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001208 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001209 OverriddenMethods[Method].push_back(Overridden);
1210}
1211
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001212void ASTContext::getOverriddenMethods(
1213 const NamedDecl *D,
1214 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001215 assert(D);
1216
1217 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001218 Overridden.append(overridden_methods_begin(CXXMethod),
1219 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001220 return;
1221 }
1222
1223 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1224 if (!Method)
1225 return;
1226
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001227 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1228 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001229 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001230}
1231
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001232void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1233 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1234 assert(!Import->isFromASTFile() && "Non-local import declaration");
1235 if (!FirstLocalImport) {
1236 FirstLocalImport = Import;
1237 LastLocalImport = Import;
1238 return;
1239 }
1240
1241 LastLocalImport->NextLocalImport = Import;
1242 LastLocalImport = Import;
1243}
1244
Chris Lattner53cfe802007-07-18 17:52:12 +00001245//===----------------------------------------------------------------------===//
1246// Type Sizing and Analysis
1247//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001248
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001249/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1250/// scalar floating point type.
1251const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001252 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001253 assert(BT && "Not a floating point type!");
1254 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001255 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001256 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001257 case BuiltinType::Float: return Target->getFloatFormat();
1258 case BuiltinType::Double: return Target->getDoubleFormat();
1259 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001260 }
1261}
1262
Rafael Espindola71eccb32013-08-08 19:53:46 +00001263CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001264 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001265
John McCall94268702010-10-08 18:24:19 +00001266 bool UseAlignAttrOnly = false;
1267 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1268 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001269
John McCall94268702010-10-08 18:24:19 +00001270 // __attribute__((aligned)) can increase or decrease alignment
1271 // *except* on a struct or struct member, where it only increases
1272 // alignment unless 'packed' is also specified.
1273 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001274 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001275 // ignore that possibility; Sema should diagnose it.
1276 if (isa<FieldDecl>(D)) {
1277 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1278 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1279 } else {
1280 UseAlignAttrOnly = true;
1281 }
1282 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001283 else if (isa<FieldDecl>(D))
1284 UseAlignAttrOnly =
1285 D->hasAttr<PackedAttr>() ||
1286 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001287
John McCall4e819612011-01-20 07:57:12 +00001288 // If we're using the align attribute only, just ignore everything
1289 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001290 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001291 // do nothing
1292
John McCall94268702010-10-08 18:24:19 +00001293 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001294 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001295 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001296 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001297 T = RT->getPointeeType();
1298 else
1299 T = getPointerType(RT->getPointeeType());
1300 }
1301 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +00001302 // Adjust alignments of declarations with array type by the
1303 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001304 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001305 unsigned MinWidth = Target->getLargeArrayMinWidth();
1306 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001307 if (isa<VariableArrayType>(arrayType))
1308 Align = std::max(Align, Target->getLargeArrayAlign());
1309 else if (isa<ConstantArrayType>(arrayType) &&
1310 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1311 Align = std::max(Align, Target->getLargeArrayAlign());
1312 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001313
John McCall33ddac02011-01-19 10:06:00 +00001314 // Walk through any array types while we're at it.
1315 T = getBaseElementType(arrayType);
1316 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001317 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Ulrich Weigandfa806422013-05-06 16:23:57 +00001318 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1319 if (VD->hasGlobalStorage())
1320 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1321 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001322 }
John McCall4e819612011-01-20 07:57:12 +00001323
1324 // Fields can be subject to extra alignment constraints, like if
1325 // the field is packed, the struct is packed, or the struct has a
1326 // a max-field-alignment constraint (#pragma pack). So calculate
1327 // the actual alignment of the field within the struct, and then
1328 // (as we're expected to) constrain that by the alignment of the type.
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001329 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1330 const RecordDecl *Parent = Field->getParent();
1331 // We can only produce a sensible answer if the record is valid.
1332 if (!Parent->isInvalidDecl()) {
1333 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001334
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001335 // Start with the record's overall alignment.
1336 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001337
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001338 // Use the GCD of that and the offset within the record.
1339 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1340 if (Offset > 0) {
1341 // Alignment is always a power of 2, so the GCD will be a power of 2,
1342 // which means we get to do this crazy thing instead of Euclid's.
1343 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1344 if (LowBitOfOffset < FieldAlign)
1345 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1346 }
1347
1348 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001349 }
Charles Davis3fc51072010-02-23 04:52:00 +00001350 }
Chris Lattner68061312009-01-24 21:53:27 +00001351 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001352
Ken Dyckcc56c542011-01-15 18:38:59 +00001353 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001354}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001355
John McCallf1249922012-08-21 04:10:00 +00001356// getTypeInfoDataSizeInChars - Return the size of a type, in
1357// chars. If the type is a record, its data size is returned. This is
1358// the size of the memcpy that's performed when assigning this type
1359// using a trivial copy/move assignment operator.
1360std::pair<CharUnits, CharUnits>
1361ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1362 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1363
1364 // In C++, objects can sometimes be allocated into the tail padding
1365 // of a base-class subobject. We decide whether that's possible
1366 // during class layout, so here we can just trust the layout results.
1367 if (getLangOpts().CPlusPlus) {
1368 if (const RecordType *RT = T->getAs<RecordType>()) {
1369 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1370 sizeAndAlign.first = layout.getDataSize();
1371 }
1372 }
1373
1374 return sizeAndAlign;
1375}
1376
Richard Trieu04d2d942013-05-14 21:59:17 +00001377/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1378/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1379std::pair<CharUnits, CharUnits>
1380static getConstantArrayInfoInChars(const ASTContext &Context,
1381 const ConstantArrayType *CAT) {
1382 std::pair<CharUnits, CharUnits> EltInfo =
1383 Context.getTypeInfoInChars(CAT->getElementType());
1384 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001385 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1386 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001387 "Overflow in array type char size evaluation");
1388 uint64_t Width = EltInfo.first.getQuantity() * Size;
1389 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001390 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1391 Context.getTargetInfo().getPointerWidth(0) == 64)
1392 Width = llvm::RoundUpToAlignment(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001393 return std::make_pair(CharUnits::fromQuantity(Width),
1394 CharUnits::fromQuantity(Align));
1395}
1396
John McCall87fe5d52010-05-20 01:18:31 +00001397std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001398ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001399 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1400 return getConstantArrayInfoInChars(*this, CAT);
John McCall87fe5d52010-05-20 01:18:31 +00001401 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +00001402 return std::make_pair(toCharUnitsFromBits(Info.first),
1403 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +00001404}
1405
1406std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001407ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001408 return getTypeInfoInChars(T.getTypePtr());
1409}
1410
Daniel Dunbarc6475872012-03-09 04:12:54 +00001411std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1412 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1413 if (it != MemoizedTypeInfo.end())
1414 return it->second;
1415
1416 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1417 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1418 return Info;
1419}
1420
1421/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1422/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001423///
1424/// FIXME: Pointers into different addr spaces could have different sizes and
1425/// alignment requirements: getPointerInfo should take an AddrSpace, this
1426/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +00001427std::pair<uint64_t, unsigned>
Daniel Dunbarc6475872012-03-09 04:12:54 +00001428ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +00001429 uint64_t Width=0;
1430 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001431 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001432#define TYPE(Class, Base)
1433#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001434#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001435#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001436#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1437 case Type::Class: \
1438 assert(!T->isDependentType() && "should not see dependent types here"); \
1439 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001440#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001441 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001442
Chris Lattner355332d2007-07-13 22:27:08 +00001443 case Type::FunctionNoProto:
1444 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001445 // GCC extension: alignof(function) = 32 bits
1446 Width = 0;
1447 Align = 32;
1448 break;
1449
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001450 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001451 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001452 Width = 0;
1453 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1454 break;
1455
Steve Naroff5c131802007-08-30 01:06:46 +00001456 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001457 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001458
Chris Lattner37e05872008-03-05 18:54:05 +00001459 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001460 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarc6475872012-03-09 04:12:54 +00001461 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1462 "Overflow in array type bit size evaluation");
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001463 Width = EltInfo.first*Size;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001464 Align = EltInfo.second;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001465 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1466 getTargetInfo().getPointerWidth(0) == 64)
1467 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001468 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001469 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001470 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001471 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001472 const VectorType *VT = cast<VectorType>(T);
1473 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1474 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001475 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001476 // If the alignment is not a power of 2, round up to the next power of 2.
1477 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001478 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001479 Align = llvm::NextPowerOf2(Align);
1480 Width = llvm::RoundUpToAlignment(Width, Align);
1481 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001482 // Adjust the alignment based on the target max.
1483 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1484 if (TargetVectorAlign && TargetVectorAlign < Align)
1485 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001486 break;
1487 }
Chris Lattner647fb222007-07-18 18:26:58 +00001488
Chris Lattner7570e9c2008-03-08 08:52:55 +00001489 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001490 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001491 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001492 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001493 // GCC extension: alignof(void) = 8 bits.
1494 Width = 0;
1495 Align = 8;
1496 break;
1497
Chris Lattner6a4f7452007-12-19 19:23:28 +00001498 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001499 Width = Target->getBoolWidth();
1500 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001501 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001502 case BuiltinType::Char_S:
1503 case BuiltinType::Char_U:
1504 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001505 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001506 Width = Target->getCharWidth();
1507 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001508 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001509 case BuiltinType::WChar_S:
1510 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001511 Width = Target->getWCharWidth();
1512 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001513 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001514 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001515 Width = Target->getChar16Width();
1516 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001517 break;
1518 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001519 Width = Target->getChar32Width();
1520 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001521 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001522 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001523 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001524 Width = Target->getShortWidth();
1525 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001526 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001527 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001528 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001529 Width = Target->getIntWidth();
1530 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001531 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001532 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001533 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001534 Width = Target->getLongWidth();
1535 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001536 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001537 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001538 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001539 Width = Target->getLongLongWidth();
1540 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001541 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001542 case BuiltinType::Int128:
1543 case BuiltinType::UInt128:
1544 Width = 128;
1545 Align = 128; // int128_t is 128-bit aligned on all targets.
1546 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001547 case BuiltinType::Half:
1548 Width = Target->getHalfWidth();
1549 Align = Target->getHalfAlign();
1550 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001551 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001552 Width = Target->getFloatWidth();
1553 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001554 break;
1555 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001556 Width = Target->getDoubleWidth();
1557 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001558 break;
1559 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001560 Width = Target->getLongDoubleWidth();
1561 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001562 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001563 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001564 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1565 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001566 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001567 case BuiltinType::ObjCId:
1568 case BuiltinType::ObjCClass:
1569 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001570 Width = Target->getPointerWidth(0);
1571 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001572 break;
Guy Benyei61054192013-02-07 10:55:47 +00001573 case BuiltinType::OCLSampler:
1574 // Samplers are modeled as integers.
1575 Width = Target->getIntWidth();
1576 Align = Target->getIntAlign();
1577 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001578 case BuiltinType::OCLEvent:
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001579 case BuiltinType::OCLImage1d:
1580 case BuiltinType::OCLImage1dArray:
1581 case BuiltinType::OCLImage1dBuffer:
1582 case BuiltinType::OCLImage2d:
1583 case BuiltinType::OCLImage2dArray:
1584 case BuiltinType::OCLImage3d:
1585 // Currently these types are pointers to opaque types.
1586 Width = Target->getPointerWidth(0);
1587 Align = Target->getPointerAlign(0);
1588 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001589 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001590 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001591 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001592 Width = Target->getPointerWidth(0);
1593 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001594 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001595 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001596 unsigned AS = getTargetAddressSpace(
1597 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001598 Width = Target->getPointerWidth(AS);
1599 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001600 break;
1601 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001602 case Type::LValueReference:
1603 case Type::RValueReference: {
1604 // alignof and sizeof should never enter this code path here, so we go
1605 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001606 unsigned AS = getTargetAddressSpace(
1607 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001608 Width = Target->getPointerWidth(AS);
1609 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001610 break;
1611 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001612 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001613 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001614 Width = Target->getPointerWidth(AS);
1615 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001616 break;
1617 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001618 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001619 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Reid Kleckner3a52abf2013-03-28 20:02:56 +00001620 llvm::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001621 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001622 }
Chris Lattner647fb222007-07-18 18:26:58 +00001623 case Type::Complex: {
1624 // Complex types have the same alignment as their elements, but twice the
1625 // size.
Mike Stump11289f42009-09-09 15:08:12 +00001626 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +00001627 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +00001628 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +00001629 Align = EltInfo.second;
1630 break;
1631 }
John McCall8b07ec22010-05-15 11:32:37 +00001632 case Type::ObjCObject:
1633 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner8a365022013-06-24 17:51:48 +00001634 case Type::Decayed:
1635 return getTypeInfo(cast<DecayedType>(T)->getDecayedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001636 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001637 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001638 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001639 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001640 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001641 break;
1642 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001643 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001644 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001645 const TagType *TT = cast<TagType>(T);
1646
1647 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001648 Width = 8;
1649 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001650 break;
1651 }
Mike Stump11289f42009-09-09 15:08:12 +00001652
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001653 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +00001654 return getTypeInfo(ET->getDecl()->getIntegerType());
1655
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001656 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +00001657 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001658 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001659 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +00001660 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001661 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001662
Chris Lattner63d2b362009-10-22 05:17:15 +00001663 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001664 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1665 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001666
Richard Smith30482bc2011-02-20 03:19:35 +00001667 case Type::Auto: {
1668 const AutoType *A = cast<AutoType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00001669 assert(!A->getDeducedType().isNull() &&
1670 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001671 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001672 }
1673
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001674 case Type::Paren:
1675 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1676
Douglas Gregoref462e62009-04-30 17:32:17 +00001677 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001678 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +00001679 std::pair<uint64_t, unsigned> Info
1680 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001681 // If the typedef has an aligned attribute on it, it overrides any computed
1682 // alignment we have. This violates the GCC documentation (which says that
1683 // attribute(aligned) can only round up) but matches its implementation.
1684 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1685 Align = AttrAlign;
1686 else
1687 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +00001688 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +00001689 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001690 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001691
Abramo Bagnara6150c882010-05-11 21:36:43 +00001692 case Type::Elaborated:
1693 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001694
John McCall81904512011-01-06 01:58:22 +00001695 case Type::Attributed:
1696 return getTypeInfo(
1697 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1698
Eli Friedman0dfb8892011-10-06 23:00:33 +00001699 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00001700 // Start with the base type information.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001701 std::pair<uint64_t, unsigned> Info
1702 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1703 Width = Info.first;
1704 Align = Info.second;
John McCalla8ec7eb2013-03-07 21:37:17 +00001705
1706 // If the size of the type doesn't exceed the platform's max
1707 // atomic promotion width, make the size and alignment more
1708 // favorable to atomic operations:
1709 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1710 // Round the size up to a power of 2.
1711 if (!llvm::isPowerOf2_64(Width))
1712 Width = llvm::NextPowerOf2(Width);
1713
1714 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001715 Align = static_cast<unsigned>(Width);
1716 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001717 }
1718
Douglas Gregoref462e62009-04-30 17:32:17 +00001719 }
Mike Stump11289f42009-09-09 15:08:12 +00001720
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001721 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +00001722 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001723}
1724
Ken Dyckcc56c542011-01-15 18:38:59 +00001725/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1726CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1727 return CharUnits::fromQuantity(BitSize / getCharWidth());
1728}
1729
Ken Dyckb0fcc592011-02-11 01:54:29 +00001730/// toBits - Convert a size in characters to a size in characters.
1731int64_t ASTContext::toBits(CharUnits CharSize) const {
1732 return CharSize.getQuantity() * getCharWidth();
1733}
1734
Ken Dyck8c89d592009-12-22 14:23:30 +00001735/// getTypeSizeInChars - Return the size of the specified type, in characters.
1736/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001737CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001738 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001739}
Jay Foad39c79802011-01-12 09:06:06 +00001740CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001741 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001742}
1743
Ken Dycka6046ab2010-01-26 17:25:18 +00001744/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001745/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001746CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001747 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001748}
Jay Foad39c79802011-01-12 09:06:06 +00001749CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001750 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001751}
1752
Chris Lattnera3402cd2009-01-27 18:08:34 +00001753/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1754/// type for the current target in bits. This can be different than the ABI
1755/// alignment in cases where it is beneficial for performance to overalign
1756/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001757unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +00001758 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +00001759
1760 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +00001761 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001762 T = CT->getElementType().getTypePtr();
1763 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001764 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1765 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman7ab09572009-05-25 21:27:19 +00001766 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1767
Chris Lattnera3402cd2009-01-27 18:08:34 +00001768 return ABIAlign;
1769}
1770
Ulrich Weigandfa806422013-05-06 16:23:57 +00001771/// getAlignOfGlobalVar - Return the alignment in bits that should be given
1772/// to a global variable of the specified type.
1773unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1774 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1775}
1776
1777/// getAlignOfGlobalVarInChars - Return the alignment in characters that
1778/// should be given to a global variable of the specified type.
1779CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1780 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1781}
1782
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001783/// DeepCollectObjCIvars -
1784/// This routine first collects all declared, but not synthesized, ivars in
1785/// super class and then collects all ivars, including those synthesized for
1786/// current class. This routine is used for implementation of current class
1787/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001788///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001789void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1790 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001791 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001792 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1793 DeepCollectObjCIvars(SuperClass, false, Ivars);
1794 if (!leafClass) {
1795 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1796 E = OI->ivar_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001797 Ivars.push_back(*I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001798 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001799 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001800 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001801 Iv= Iv->getNextIvar())
1802 Ivars.push_back(Iv);
1803 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001804}
1805
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001806/// CollectInheritedProtocols - Collect all protocols in current class and
1807/// those inherited by it.
1808void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001809 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001810 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001811 // We can use protocol_iterator here instead of
1812 // all_referenced_protocol_iterator since we are walking all categories.
1813 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1814 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001815 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001816 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001817 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001818 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001819 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001820 CollectInheritedProtocols(*P, Protocols);
1821 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001822 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001823
1824 // Categories of this Interface.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001825 for (ObjCInterfaceDecl::visible_categories_iterator
1826 Cat = OI->visible_categories_begin(),
1827 CatEnd = OI->visible_categories_end();
1828 Cat != CatEnd; ++Cat) {
1829 CollectInheritedProtocols(*Cat, Protocols);
1830 }
1831
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001832 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1833 while (SD) {
1834 CollectInheritedProtocols(SD, Protocols);
1835 SD = SD->getSuperClass();
1836 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001837 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001838 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001839 PE = OC->protocol_end(); P != PE; ++P) {
1840 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001841 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001842 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1843 PE = Proto->protocol_end(); P != PE; ++P)
1844 CollectInheritedProtocols(*P, Protocols);
1845 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001846 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001847 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1848 PE = OP->protocol_end(); P != PE; ++P) {
1849 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001850 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001851 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1852 PE = Proto->protocol_end(); P != PE; ++P)
1853 CollectInheritedProtocols(*P, Protocols);
1854 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001855 }
1856}
1857
Jay Foad39c79802011-01-12 09:06:06 +00001858unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001859 unsigned count = 0;
1860 // Count ivars declared in class extension.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001861 for (ObjCInterfaceDecl::known_extensions_iterator
1862 Ext = OI->known_extensions_begin(),
1863 ExtEnd = OI->known_extensions_end();
1864 Ext != ExtEnd; ++Ext) {
1865 count += Ext->ivar_size();
1866 }
1867
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001868 // Count ivar defined in this class's implementation. This
1869 // includes synthesized ivars.
1870 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001871 count += ImplDecl->ivar_size();
1872
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001873 return count;
1874}
1875
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001876bool ASTContext::isSentinelNullExpr(const Expr *E) {
1877 if (!E)
1878 return false;
1879
1880 // nullptr_t is always treated as null.
1881 if (E->getType()->isNullPtrType()) return true;
1882
1883 if (E->getType()->isAnyPointerType() &&
1884 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1885 Expr::NPC_ValueDependentIsNull))
1886 return true;
1887
1888 // Unfortunately, __null has type 'int'.
1889 if (isa<GNUNullExpr>(E)) return true;
1890
1891 return false;
1892}
1893
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001894/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1895ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1896 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1897 I = ObjCImpls.find(D);
1898 if (I != ObjCImpls.end())
1899 return cast<ObjCImplementationDecl>(I->second);
1900 return 0;
1901}
1902/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1903ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1904 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1905 I = ObjCImpls.find(D);
1906 if (I != ObjCImpls.end())
1907 return cast<ObjCCategoryImplDecl>(I->second);
1908 return 0;
1909}
1910
1911/// \brief Set the implementation of ObjCInterfaceDecl.
1912void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1913 ObjCImplementationDecl *ImplD) {
1914 assert(IFaceD && ImplD && "Passed null params");
1915 ObjCImpls[IFaceD] = ImplD;
1916}
1917/// \brief Set the implementation of ObjCCategoryDecl.
1918void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1919 ObjCCategoryImplDecl *ImplD) {
1920 assert(CatD && ImplD && "Passed null params");
1921 ObjCImpls[CatD] = ImplD;
1922}
1923
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001924const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
1925 const NamedDecl *ND) const {
1926 if (const ObjCInterfaceDecl *ID =
1927 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001928 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001929 if (const ObjCCategoryDecl *CD =
1930 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001931 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001932 if (const ObjCImplDecl *IMD =
1933 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001934 return IMD->getClassInterface();
1935
1936 return 0;
1937}
1938
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001939/// \brief Get the copy initialization expression of VarDecl,or NULL if
1940/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001941Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001942 assert(VD && "Passed null params");
1943 assert(VD->hasAttr<BlocksAttr>() &&
1944 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001945 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001946 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001947 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1948}
1949
1950/// \brief Set the copy inialization expression of a block var decl.
1951void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1952 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001953 assert(VD->hasAttr<BlocksAttr>() &&
1954 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001955 BlockVarCopyInits[VD] = Init;
1956}
1957
John McCallbcd03502009-12-07 02:54:59 +00001958TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001959 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001960 if (!DataSize)
1961 DataSize = TypeLoc::getFullDataSizeForType(T);
1962 else
1963 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001964 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001965
John McCallbcd03502009-12-07 02:54:59 +00001966 TypeSourceInfo *TInfo =
1967 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1968 new (TInfo) TypeSourceInfo(T);
1969 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001970}
1971
John McCallbcd03502009-12-07 02:54:59 +00001972TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001973 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001974 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001975 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001976 return DI;
1977}
1978
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001979const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001980ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001981 return getObjCLayout(D, 0);
1982}
1983
1984const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001985ASTContext::getASTObjCImplementationLayout(
1986 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001987 return getObjCLayout(D->getClassInterface(), D);
1988}
1989
Chris Lattner983a8bb2007-07-13 22:13:22 +00001990//===----------------------------------------------------------------------===//
1991// Type creation/memoization methods
1992//===----------------------------------------------------------------------===//
1993
Jay Foad39c79802011-01-12 09:06:06 +00001994QualType
John McCall33ddac02011-01-19 10:06:00 +00001995ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1996 unsigned fastQuals = quals.getFastQualifiers();
1997 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001998
1999 // Check if we've already instantiated this type.
2000 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002001 ExtQuals::Profile(ID, baseType, quals);
2002 void *insertPos = 0;
2003 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2004 assert(eq->getQualifiers() == quals);
2005 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002006 }
2007
John McCall33ddac02011-01-19 10:06:00 +00002008 // If the base type is not canonical, make the appropriate canonical type.
2009 QualType canon;
2010 if (!baseType->isCanonicalUnqualified()) {
2011 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002012 canonSplit.Quals.addConsistentQualifiers(quals);
2013 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002014
2015 // Re-find the insert position.
2016 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2017 }
2018
2019 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2020 ExtQualNodes.InsertNode(eq, insertPos);
2021 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002022}
2023
Jay Foad39c79802011-01-12 09:06:06 +00002024QualType
2025ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002026 QualType CanT = getCanonicalType(T);
2027 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002028 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002029
John McCall8ccfcb52009-09-24 19:53:00 +00002030 // If we are composing extended qualifiers together, merge together
2031 // into one ExtQuals node.
2032 QualifierCollector Quals;
2033 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002034
John McCall8ccfcb52009-09-24 19:53:00 +00002035 // If this type already has an address space specified, it cannot get
2036 // another one.
2037 assert(!Quals.hasAddressSpace() &&
2038 "Type cannot be in multiple addr spaces!");
2039 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002040
John McCall8ccfcb52009-09-24 19:53:00 +00002041 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002042}
2043
Chris Lattnerd60183d2009-02-18 22:53:11 +00002044QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002045 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002046 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002047 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002048 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002049
John McCall53fa7142010-12-24 02:08:15 +00002050 if (const PointerType *ptr = T->getAs<PointerType>()) {
2051 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002052 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002053 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2054 return getPointerType(ResultType);
2055 }
2056 }
Mike Stump11289f42009-09-09 15:08:12 +00002057
John McCall8ccfcb52009-09-24 19:53:00 +00002058 // If we are composing extended qualifiers together, merge together
2059 // into one ExtQuals node.
2060 QualifierCollector Quals;
2061 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002062
John McCall8ccfcb52009-09-24 19:53:00 +00002063 // If this type already has an ObjCGC specified, it cannot get
2064 // another one.
2065 assert(!Quals.hasObjCGCAttr() &&
2066 "Type cannot have multiple ObjCGCs!");
2067 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002068
John McCall8ccfcb52009-09-24 19:53:00 +00002069 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002070}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002071
John McCall4f5019e2010-12-19 02:44:49 +00002072const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2073 FunctionType::ExtInfo Info) {
2074 if (T->getExtInfo() == Info)
2075 return T;
2076
2077 QualType Result;
2078 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
2079 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
2080 } else {
2081 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2082 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2083 EPI.ExtInfo = Info;
Reid Kleckner896b32f2013-06-10 20:51:09 +00002084 Result = getFunctionType(FPT->getResultType(), FPT->getArgTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002085 }
2086
2087 return cast<FunctionType>(Result.getTypePtr());
2088}
2089
Richard Smith2a7d4812013-05-04 07:00:32 +00002090void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2091 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002092 FD = FD->getMostRecentDecl();
2093 while (true) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002094 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2095 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2096 FD->setType(getFunctionType(ResultType, FPT->getArgTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002097 if (FunctionDecl *Next = FD->getPreviousDecl())
2098 FD = Next;
2099 else
2100 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002101 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002102 if (ASTMutationListener *L = getASTMutationListener())
2103 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002104}
2105
Chris Lattnerc6395932007-06-22 20:56:16 +00002106/// getComplexType - Return the uniqued reference to the type for a complex
2107/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002108QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002109 // Unique pointers, to guarantee there is only one pointer of a particular
2110 // structure.
2111 llvm::FoldingSetNodeID ID;
2112 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002113
Chris Lattnerc6395932007-06-22 20:56:16 +00002114 void *InsertPos = 0;
2115 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2116 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002117
Chris Lattnerc6395932007-06-22 20:56:16 +00002118 // If the pointee type isn't canonical, this won't be a canonical type either,
2119 // so fill in the canonical type field.
2120 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002121 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002122 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002123
Chris Lattnerc6395932007-06-22 20:56:16 +00002124 // Get the new insert position for the node we care about.
2125 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002126 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002127 }
John McCall90d1c2d2009-09-24 23:30:46 +00002128 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002129 Types.push_back(New);
2130 ComplexTypes.InsertNode(New, InsertPos);
2131 return QualType(New, 0);
2132}
2133
Chris Lattner970e54e2006-11-12 00:37:36 +00002134/// getPointerType - Return the uniqued reference to the type for a pointer to
2135/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002136QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002137 // Unique pointers, to guarantee there is only one pointer of a particular
2138 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002139 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002140 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002141
Chris Lattner67521df2007-01-27 01:29:36 +00002142 void *InsertPos = 0;
2143 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002144 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002145
Chris Lattner7ccecb92006-11-12 08:50:50 +00002146 // If the pointee type isn't canonical, this won't be a canonical type either,
2147 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002148 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002149 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002150 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002151
Bob Wilsonc8541f22013-03-15 17:12:43 +00002152 // Get the new insert position for the node we care about.
2153 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2154 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2155 }
John McCall90d1c2d2009-09-24 23:30:46 +00002156 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002157 Types.push_back(New);
2158 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002159 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002160}
2161
Reid Kleckner8a365022013-06-24 17:51:48 +00002162QualType ASTContext::getDecayedType(QualType T) const {
2163 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2164
2165 llvm::FoldingSetNodeID ID;
2166 DecayedType::Profile(ID, T);
2167 void *InsertPos = 0;
2168 if (DecayedType *DT = DecayedTypes.FindNodeOrInsertPos(ID, InsertPos))
2169 return QualType(DT, 0);
2170
2171 QualType Decayed;
2172
2173 // C99 6.7.5.3p7:
2174 // A declaration of a parameter as "array of type" shall be
2175 // adjusted to "qualified pointer to type", where the type
2176 // qualifiers (if any) are those specified within the [ and ] of
2177 // the array type derivation.
2178 if (T->isArrayType())
2179 Decayed = getArrayDecayedType(T);
2180
2181 // C99 6.7.5.3p8:
2182 // A declaration of a parameter as "function returning type"
2183 // shall be adjusted to "pointer to function returning type", as
2184 // in 6.3.2.1.
2185 if (T->isFunctionType())
2186 Decayed = getPointerType(T);
2187
2188 QualType Canonical = getCanonicalType(Decayed);
2189
2190 // Get the new insert position for the node we care about.
2191 DecayedType *NewIP = DecayedTypes.FindNodeOrInsertPos(ID, InsertPos);
2192 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2193
2194 DecayedType *New =
2195 new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2196 Types.push_back(New);
2197 DecayedTypes.InsertNode(New, InsertPos);
2198 return QualType(New, 0);
2199}
2200
Mike Stump11289f42009-09-09 15:08:12 +00002201/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002202/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002203QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002204 assert(T->isFunctionType() && "block of function types only");
2205 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002206 // structure.
2207 llvm::FoldingSetNodeID ID;
2208 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002209
Steve Naroffec33ed92008-08-27 16:04:49 +00002210 void *InsertPos = 0;
2211 if (BlockPointerType *PT =
2212 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2213 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002214
2215 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002216 // type either so fill in the canonical type field.
2217 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002218 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002219 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002220
Steve Naroffec33ed92008-08-27 16:04:49 +00002221 // Get the new insert position for the node we care about.
2222 BlockPointerType *NewIP =
2223 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002224 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002225 }
John McCall90d1c2d2009-09-24 23:30:46 +00002226 BlockPointerType *New
2227 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002228 Types.push_back(New);
2229 BlockPointerTypes.InsertNode(New, InsertPos);
2230 return QualType(New, 0);
2231}
2232
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002233/// getLValueReferenceType - Return the uniqued reference to the type for an
2234/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002235QualType
2236ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002237 assert(getCanonicalType(T) != OverloadTy &&
2238 "Unresolved overloaded function type");
2239
Bill Wendling3708c182007-05-27 10:15:43 +00002240 // Unique pointers, to guarantee there is only one pointer of a particular
2241 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002242 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002243 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002244
2245 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002246 if (LValueReferenceType *RT =
2247 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002248 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002249
John McCallfc93cf92009-10-22 22:37:11 +00002250 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2251
Bill Wendling3708c182007-05-27 10:15:43 +00002252 // If the referencee type isn't canonical, this won't be a canonical type
2253 // either, so fill in the canonical type field.
2254 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002255 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2256 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2257 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002258
Bill Wendling3708c182007-05-27 10:15:43 +00002259 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002260 LValueReferenceType *NewIP =
2261 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002262 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002263 }
2264
John McCall90d1c2d2009-09-24 23:30:46 +00002265 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002266 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2267 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002268 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002269 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002270
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002271 return QualType(New, 0);
2272}
2273
2274/// getRValueReferenceType - Return the uniqued reference to the type for an
2275/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002276QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002277 // Unique pointers, to guarantee there is only one pointer of a particular
2278 // structure.
2279 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002280 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002281
2282 void *InsertPos = 0;
2283 if (RValueReferenceType *RT =
2284 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2285 return QualType(RT, 0);
2286
John McCallfc93cf92009-10-22 22:37:11 +00002287 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2288
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002289 // If the referencee type isn't canonical, this won't be a canonical type
2290 // either, so fill in the canonical type field.
2291 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002292 if (InnerRef || !T.isCanonical()) {
2293 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2294 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002295
2296 // Get the new insert position for the node we care about.
2297 RValueReferenceType *NewIP =
2298 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002299 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002300 }
2301
John McCall90d1c2d2009-09-24 23:30:46 +00002302 RValueReferenceType *New
2303 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002304 Types.push_back(New);
2305 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002306 return QualType(New, 0);
2307}
2308
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002309/// getMemberPointerType - Return the uniqued reference to the type for a
2310/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002311QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002312 // Unique pointers, to guarantee there is only one pointer of a particular
2313 // structure.
2314 llvm::FoldingSetNodeID ID;
2315 MemberPointerType::Profile(ID, T, Cls);
2316
2317 void *InsertPos = 0;
2318 if (MemberPointerType *PT =
2319 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2320 return QualType(PT, 0);
2321
2322 // If the pointee or class type isn't canonical, this won't be a canonical
2323 // type either, so fill in the canonical type field.
2324 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002325 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002326 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2327
2328 // Get the new insert position for the node we care about.
2329 MemberPointerType *NewIP =
2330 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002331 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002332 }
John McCall90d1c2d2009-09-24 23:30:46 +00002333 MemberPointerType *New
2334 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002335 Types.push_back(New);
2336 MemberPointerTypes.InsertNode(New, InsertPos);
2337 return QualType(New, 0);
2338}
2339
Mike Stump11289f42009-09-09 15:08:12 +00002340/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002341/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002342QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002343 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002344 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002345 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002346 assert((EltTy->isDependentType() ||
2347 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002348 "Constant array of VLAs is illegal!");
2349
Chris Lattnere2df3f92009-05-13 04:12:56 +00002350 // Convert the array size into a canonical width matching the pointer size for
2351 // the target.
2352 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002353 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002354 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002355
Chris Lattner23b7eb62007-06-15 23:05:46 +00002356 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002357 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002358
Chris Lattner36f8e652007-01-27 08:31:04 +00002359 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002360 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002361 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002362 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002363
John McCall33ddac02011-01-19 10:06:00 +00002364 // If the element type isn't canonical or has qualifiers, this won't
2365 // be a canonical type either, so fill in the canonical type field.
2366 QualType Canon;
2367 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2368 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002369 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002370 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002371 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002372
Chris Lattner36f8e652007-01-27 08:31:04 +00002373 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002374 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002375 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002376 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002377 }
Mike Stump11289f42009-09-09 15:08:12 +00002378
John McCall90d1c2d2009-09-24 23:30:46 +00002379 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002380 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002381 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002382 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002383 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002384}
2385
John McCall06549462011-01-18 08:40:38 +00002386/// getVariableArrayDecayedType - Turns the given type, which may be
2387/// variably-modified, into the corresponding type with all the known
2388/// sizes replaced with [*].
2389QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2390 // Vastly most common case.
2391 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002392
John McCall06549462011-01-18 08:40:38 +00002393 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002394
John McCall06549462011-01-18 08:40:38 +00002395 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002396 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002397 switch (ty->getTypeClass()) {
2398#define TYPE(Class, Base)
2399#define ABSTRACT_TYPE(Class, Base)
2400#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2401#include "clang/AST/TypeNodes.def"
2402 llvm_unreachable("didn't desugar past all non-canonical types?");
2403
2404 // These types should never be variably-modified.
2405 case Type::Builtin:
2406 case Type::Complex:
2407 case Type::Vector:
2408 case Type::ExtVector:
2409 case Type::DependentSizedExtVector:
2410 case Type::ObjCObject:
2411 case Type::ObjCInterface:
2412 case Type::ObjCObjectPointer:
2413 case Type::Record:
2414 case Type::Enum:
2415 case Type::UnresolvedUsing:
2416 case Type::TypeOfExpr:
2417 case Type::TypeOf:
2418 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002419 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002420 case Type::DependentName:
2421 case Type::InjectedClassName:
2422 case Type::TemplateSpecialization:
2423 case Type::DependentTemplateSpecialization:
2424 case Type::TemplateTypeParm:
2425 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002426 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002427 case Type::PackExpansion:
2428 llvm_unreachable("type should never be variably-modified");
2429
2430 // These types can be variably-modified but should never need to
2431 // further decay.
2432 case Type::FunctionNoProto:
2433 case Type::FunctionProto:
2434 case Type::BlockPointer:
2435 case Type::MemberPointer:
2436 return type;
2437
2438 // These types can be variably-modified. All these modifications
2439 // preserve structure except as noted by comments.
2440 // TODO: if we ever care about optimizing VLAs, there are no-op
2441 // optimizations available here.
2442 case Type::Pointer:
2443 result = getPointerType(getVariableArrayDecayedType(
2444 cast<PointerType>(ty)->getPointeeType()));
2445 break;
2446
2447 case Type::LValueReference: {
2448 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2449 result = getLValueReferenceType(
2450 getVariableArrayDecayedType(lv->getPointeeType()),
2451 lv->isSpelledAsLValue());
2452 break;
2453 }
2454
2455 case Type::RValueReference: {
2456 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2457 result = getRValueReferenceType(
2458 getVariableArrayDecayedType(lv->getPointeeType()));
2459 break;
2460 }
2461
Eli Friedman0dfb8892011-10-06 23:00:33 +00002462 case Type::Atomic: {
2463 const AtomicType *at = cast<AtomicType>(ty);
2464 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2465 break;
2466 }
2467
John McCall06549462011-01-18 08:40:38 +00002468 case Type::ConstantArray: {
2469 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2470 result = getConstantArrayType(
2471 getVariableArrayDecayedType(cat->getElementType()),
2472 cat->getSize(),
2473 cat->getSizeModifier(),
2474 cat->getIndexTypeCVRQualifiers());
2475 break;
2476 }
2477
2478 case Type::DependentSizedArray: {
2479 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2480 result = getDependentSizedArrayType(
2481 getVariableArrayDecayedType(dat->getElementType()),
2482 dat->getSizeExpr(),
2483 dat->getSizeModifier(),
2484 dat->getIndexTypeCVRQualifiers(),
2485 dat->getBracketsRange());
2486 break;
2487 }
2488
2489 // Turn incomplete types into [*] types.
2490 case Type::IncompleteArray: {
2491 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2492 result = getVariableArrayType(
2493 getVariableArrayDecayedType(iat->getElementType()),
2494 /*size*/ 0,
2495 ArrayType::Normal,
2496 iat->getIndexTypeCVRQualifiers(),
2497 SourceRange());
2498 break;
2499 }
2500
2501 // Turn VLA types into [*] types.
2502 case Type::VariableArray: {
2503 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2504 result = getVariableArrayType(
2505 getVariableArrayDecayedType(vat->getElementType()),
2506 /*size*/ 0,
2507 ArrayType::Star,
2508 vat->getIndexTypeCVRQualifiers(),
2509 vat->getBracketsRange());
2510 break;
2511 }
2512 }
2513
2514 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002515 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002516}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002517
Steve Naroffcadebd02007-08-30 18:14:25 +00002518/// getVariableArrayType - Returns a non-unique reference to the type for a
2519/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002520QualType ASTContext::getVariableArrayType(QualType EltTy,
2521 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002522 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002523 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002524 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002525 // Since we don't unique expressions, it isn't possible to unique VLA's
2526 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002527 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002528
John McCall33ddac02011-01-19 10:06:00 +00002529 // Be sure to pull qualifiers off the element type.
2530 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2531 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002532 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002533 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002534 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002535 }
2536
John McCall90d1c2d2009-09-24 23:30:46 +00002537 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002538 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002539
2540 VariableArrayTypes.push_back(New);
2541 Types.push_back(New);
2542 return QualType(New, 0);
2543}
2544
Douglas Gregor4619e432008-12-05 23:32:09 +00002545/// getDependentSizedArrayType - Returns a non-unique reference to
2546/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002547/// type.
John McCall33ddac02011-01-19 10:06:00 +00002548QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2549 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002550 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002551 unsigned elementTypeQuals,
2552 SourceRange brackets) const {
2553 assert((!numElements || numElements->isTypeDependent() ||
2554 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002555 "Size must be type- or value-dependent!");
2556
John McCall33ddac02011-01-19 10:06:00 +00002557 // Dependently-sized array types that do not have a specified number
2558 // of elements will have their sizes deduced from a dependent
2559 // initializer. We do no canonicalization here at all, which is okay
2560 // because they can't be used in most locations.
2561 if (!numElements) {
2562 DependentSizedArrayType *newType
2563 = new (*this, TypeAlignment)
2564 DependentSizedArrayType(*this, elementType, QualType(),
2565 numElements, ASM, elementTypeQuals,
2566 brackets);
2567 Types.push_back(newType);
2568 return QualType(newType, 0);
2569 }
2570
2571 // Otherwise, we actually build a new type every time, but we
2572 // also build a canonical type.
2573
2574 SplitQualType canonElementType = getCanonicalType(elementType).split();
2575
2576 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002577 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002578 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002579 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002580 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002581
John McCall33ddac02011-01-19 10:06:00 +00002582 // Look for an existing type with these properties.
2583 DependentSizedArrayType *canonTy =
2584 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002585
John McCall33ddac02011-01-19 10:06:00 +00002586 // If we don't have one, build one.
2587 if (!canonTy) {
2588 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002589 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002590 QualType(), numElements, ASM, elementTypeQuals,
2591 brackets);
2592 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2593 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002594 }
2595
John McCall33ddac02011-01-19 10:06:00 +00002596 // Apply qualifiers from the element type to the array.
2597 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002598 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002599
John McCall33ddac02011-01-19 10:06:00 +00002600 // If we didn't need extra canonicalization for the element type,
2601 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00002602 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00002603 return canon;
2604
2605 // Otherwise, we need to build a type which follows the spelling
2606 // of the element type.
2607 DependentSizedArrayType *sugaredType
2608 = new (*this, TypeAlignment)
2609 DependentSizedArrayType(*this, elementType, canon, numElements,
2610 ASM, elementTypeQuals, brackets);
2611 Types.push_back(sugaredType);
2612 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002613}
2614
John McCall33ddac02011-01-19 10:06:00 +00002615QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002616 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002617 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002618 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002619 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002620
John McCall33ddac02011-01-19 10:06:00 +00002621 void *insertPos = 0;
2622 if (IncompleteArrayType *iat =
2623 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2624 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002625
2626 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002627 // either, so fill in the canonical type field. We also have to pull
2628 // qualifiers off the element type.
2629 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002630
John McCall33ddac02011-01-19 10:06:00 +00002631 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2632 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002633 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002634 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002635 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002636
2637 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002638 IncompleteArrayType *existing =
2639 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2640 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002641 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002642
John McCall33ddac02011-01-19 10:06:00 +00002643 IncompleteArrayType *newType = new (*this, TypeAlignment)
2644 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002645
John McCall33ddac02011-01-19 10:06:00 +00002646 IncompleteArrayTypes.InsertNode(newType, insertPos);
2647 Types.push_back(newType);
2648 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002649}
2650
Steve Naroff91fcddb2007-07-18 18:00:27 +00002651/// getVectorType - Return the unique reference to a vector type of
2652/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002653QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002654 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002655 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002656
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002657 // Check if we've already instantiated a vector of this type.
2658 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002659 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002660
Steve Naroff4ae0ac62007-07-06 23:09:18 +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;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002668 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002669 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002670
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002671 // Get the new insert position for the node we care about.
2672 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002673 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002674 }
John McCall90d1c2d2009-09-24 23:30:46 +00002675 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002676 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002677 VectorTypes.InsertNode(New, InsertPos);
2678 Types.push_back(New);
2679 return QualType(New, 0);
2680}
2681
Nate Begemance4d7fc2008-04-18 23:10:10 +00002682/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002683/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002684QualType
2685ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002686 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002687
Steve Naroff91fcddb2007-07-18 18:00:27 +00002688 // Check if we've already instantiated a vector of this type.
2689 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002690 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002691 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002692 void *InsertPos = 0;
2693 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2694 return QualType(VTP, 0);
2695
2696 // If the element type isn't canonical, this won't be a canonical type either,
2697 // so fill in the canonical type field.
2698 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002699 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002700 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002701
Steve Naroff91fcddb2007-07-18 18:00:27 +00002702 // Get the new insert position for the node we care about.
2703 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002704 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002705 }
John McCall90d1c2d2009-09-24 23:30:46 +00002706 ExtVectorType *New = new (*this, TypeAlignment)
2707 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002708 VectorTypes.InsertNode(New, InsertPos);
2709 Types.push_back(New);
2710 return QualType(New, 0);
2711}
2712
Jay Foad39c79802011-01-12 09:06:06 +00002713QualType
2714ASTContext::getDependentSizedExtVectorType(QualType vecType,
2715 Expr *SizeExpr,
2716 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002717 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002718 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002719 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002720
Douglas Gregor352169a2009-07-31 03:54:25 +00002721 void *InsertPos = 0;
2722 DependentSizedExtVectorType *Canon
2723 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2724 DependentSizedExtVectorType *New;
2725 if (Canon) {
2726 // We already have a canonical version of this array type; use it as
2727 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002728 New = new (*this, TypeAlignment)
2729 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2730 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002731 } else {
2732 QualType CanonVecTy = getCanonicalType(vecType);
2733 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002734 New = new (*this, TypeAlignment)
2735 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2736 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002737
2738 DependentSizedExtVectorType *CanonCheck
2739 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2740 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2741 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002742 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2743 } else {
2744 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2745 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002746 New = new (*this, TypeAlignment)
2747 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002748 }
2749 }
Mike Stump11289f42009-09-09 15:08:12 +00002750
Douglas Gregor758a8692009-06-17 21:51:59 +00002751 Types.push_back(New);
2752 return QualType(New, 0);
2753}
2754
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002755/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002756///
Jay Foad39c79802011-01-12 09:06:06 +00002757QualType
2758ASTContext::getFunctionNoProtoType(QualType ResultTy,
2759 const FunctionType::ExtInfo &Info) const {
Reid Kleckner78af0702013-08-27 23:08:25 +00002760 const CallingConv CallConv = Info.getCC();
2761
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002762 // Unique functions, to guarantee there is only one function of a particular
2763 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002764 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002765 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002766
Chris Lattner47955de2007-01-27 08:37:20 +00002767 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002768 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002769 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002770 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002771
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002772 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002773 if (!ResultTy.isCanonical()) {
2774 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00002775
Chris Lattner47955de2007-01-27 08:37:20 +00002776 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002777 FunctionNoProtoType *NewIP =
2778 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002779 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002780 }
Mike Stump11289f42009-09-09 15:08:12 +00002781
Roman Divacky65b88cd2011-03-01 17:40:53 +00002782 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002783 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002784 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002785 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002786 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002787 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002788}
2789
Douglas Gregorcd780372013-01-17 23:36:45 +00002790/// \brief Determine whether \p T is canonical as the result type of a function.
2791static bool isCanonicalResultType(QualType T) {
2792 return T.isCanonical() &&
2793 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2794 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2795}
2796
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002797/// getFunctionType - Return a normal function type with a typed argument
2798/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00002799QualType
Jordan Rose5c382722013-03-08 21:51:21 +00002800ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad39c79802011-01-12 09:06:06 +00002801 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rose5c382722013-03-08 21:51:21 +00002802 size_t NumArgs = ArgArray.size();
2803
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002804 // Unique functions, to guarantee there is only one function of a particular
2805 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002806 llvm::FoldingSetNodeID ID;
Jordan Rose5c382722013-03-08 21:51:21 +00002807 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
2808 *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002809
2810 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002811 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002812 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002813 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002814
2815 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002816 bool isCanonical =
Douglas Gregorcd780372013-01-17 23:36:45 +00002817 EPI.ExceptionSpecType == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smith5e580292012-02-10 09:58:53 +00002818 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002819 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002820 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002821 isCanonical = false;
2822
2823 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002824 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002825 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002826 if (!isCanonical) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002827 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002828 CanonicalArgs.reserve(NumArgs);
2829 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002830 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002831
John McCalldb40c7f2010-12-14 08:05:40 +00002832 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002833 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002834 CanonicalEPI.ExceptionSpecType = EST_None;
2835 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002836
Douglas Gregorcd780372013-01-17 23:36:45 +00002837 // Result types do not have ARC lifetime qualifiers.
2838 QualType CanResultTy = getCanonicalType(ResultTy);
2839 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2840 Qualifiers Qs = CanResultTy.getQualifiers();
2841 Qs.removeObjCLifetime();
2842 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2843 }
2844
Jordan Rose5c382722013-03-08 21:51:21 +00002845 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002846
Chris Lattnerfd4de792007-01-27 01:15:32 +00002847 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002848 FunctionProtoType *NewIP =
2849 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002850 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002851 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002852
John McCall31168b02011-06-15 23:02:42 +00002853 // FunctionProtoType objects are allocated with extra bytes after
2854 // them for three variable size arrays at the end:
2855 // - parameter types
2856 // - exception types
2857 // - consumed-arguments flags
2858 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00002859 // expression, or information used to resolve the exception
2860 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00002861 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002862 NumArgs * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002863 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002864 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002865 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002866 Size += sizeof(Expr*);
Richard Smithf623c962012-04-17 00:58:00 +00002867 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00002868 Size += 2 * sizeof(FunctionDecl*);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002869 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2870 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002871 }
John McCall31168b02011-06-15 23:02:42 +00002872 if (EPI.ConsumedArguments)
2873 Size += NumArgs * sizeof(bool);
2874
John McCalldb40c7f2010-12-14 08:05:40 +00002875 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002876 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00002877 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002878 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002879 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002880 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002881}
Chris Lattneref51c202006-11-10 07:17:23 +00002882
John McCalle78aac42010-03-10 03:28:59 +00002883#ifndef NDEBUG
2884static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2885 if (!isa<CXXRecordDecl>(D)) return false;
2886 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2887 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2888 return true;
2889 if (RD->getDescribedClassTemplate() &&
2890 !isa<ClassTemplateSpecializationDecl>(RD))
2891 return true;
2892 return false;
2893}
2894#endif
2895
2896/// getInjectedClassNameType - Return the unique reference to the
2897/// injected class name type for the specified templated declaration.
2898QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002899 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002900 assert(NeedsInjectedClassNameType(Decl));
2901 if (Decl->TypeForDecl) {
2902 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00002903 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00002904 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2905 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2906 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2907 } else {
John McCall424cec92011-01-19 06:33:43 +00002908 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002909 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002910 Decl->TypeForDecl = newType;
2911 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002912 }
2913 return QualType(Decl->TypeForDecl, 0);
2914}
2915
Douglas Gregor83a586e2008-04-13 21:07:44 +00002916/// getTypeDeclType - Return the unique reference to the type for the
2917/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002918QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002919 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002920 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002921
Richard Smithdda56e42011-04-15 14:24:37 +00002922 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002923 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002924
John McCall96f0b5f2010-03-10 06:48:02 +00002925 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2926 "Template type parameter types are always available.");
2927
John McCall81e38502010-02-16 03:57:14 +00002928 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00002929 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00002930 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002931 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002932 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00002933 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002934 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002935 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002936 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002937 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2938 Decl->TypeForDecl = newType;
2939 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002940 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002941 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002942
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002943 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002944}
2945
Chris Lattner32d920b2007-01-26 02:01:53 +00002946/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002947/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002948QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002949ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2950 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002951 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002952
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002953 if (Canonical.isNull())
2954 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002955 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002956 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002957 Decl->TypeForDecl = newType;
2958 Types.push_back(newType);
2959 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002960}
2961
Jay Foad39c79802011-01-12 09:06:06 +00002962QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002963 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2964
Douglas Gregorec9fd132012-01-14 16:38:05 +00002965 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002966 if (PrevDecl->TypeForDecl)
2967 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2968
John McCall424cec92011-01-19 06:33:43 +00002969 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2970 Decl->TypeForDecl = newType;
2971 Types.push_back(newType);
2972 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002973}
2974
Jay Foad39c79802011-01-12 09:06:06 +00002975QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002976 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2977
Douglas Gregorec9fd132012-01-14 16:38:05 +00002978 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002979 if (PrevDecl->TypeForDecl)
2980 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2981
John McCall424cec92011-01-19 06:33:43 +00002982 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2983 Decl->TypeForDecl = newType;
2984 Types.push_back(newType);
2985 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002986}
2987
John McCall81904512011-01-06 01:58:22 +00002988QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2989 QualType modifiedType,
2990 QualType equivalentType) {
2991 llvm::FoldingSetNodeID id;
2992 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2993
2994 void *insertPos = 0;
2995 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2996 if (type) return QualType(type, 0);
2997
2998 QualType canon = getCanonicalType(equivalentType);
2999 type = new (*this, TypeAlignment)
3000 AttributedType(canon, attrKind, modifiedType, equivalentType);
3001
3002 Types.push_back(type);
3003 AttributedTypes.InsertNode(type, insertPos);
3004
3005 return QualType(type, 0);
3006}
3007
3008
John McCallcebee162009-10-18 09:09:24 +00003009/// \brief Retrieve a substitution-result type.
3010QualType
3011ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003012 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003013 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003014 && "replacement types must always be canonical");
3015
3016 llvm::FoldingSetNodeID ID;
3017 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
3018 void *InsertPos = 0;
3019 SubstTemplateTypeParmType *SubstParm
3020 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3021
3022 if (!SubstParm) {
3023 SubstParm = new (*this, TypeAlignment)
3024 SubstTemplateTypeParmType(Parm, Replacement);
3025 Types.push_back(SubstParm);
3026 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3027 }
3028
3029 return QualType(SubstParm, 0);
3030}
3031
Douglas Gregorada4b792011-01-14 02:55:32 +00003032/// \brief Retrieve a
3033QualType ASTContext::getSubstTemplateTypeParmPackType(
3034 const TemplateTypeParmType *Parm,
3035 const TemplateArgument &ArgPack) {
3036#ifndef NDEBUG
3037 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
3038 PEnd = ArgPack.pack_end();
3039 P != PEnd; ++P) {
3040 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3041 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
3042 }
3043#endif
3044
3045 llvm::FoldingSetNodeID ID;
3046 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
3047 void *InsertPos = 0;
3048 if (SubstTemplateTypeParmPackType *SubstParm
3049 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3050 return QualType(SubstParm, 0);
3051
3052 QualType Canon;
3053 if (!Parm->isCanonicalUnqualified()) {
3054 Canon = getCanonicalType(QualType(Parm, 0));
3055 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3056 ArgPack);
3057 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3058 }
3059
3060 SubstTemplateTypeParmPackType *SubstParm
3061 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3062 ArgPack);
3063 Types.push_back(SubstParm);
3064 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3065 return QualType(SubstParm, 0);
3066}
3067
Douglas Gregoreff93e02009-02-05 23:33:38 +00003068/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003069/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003070/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003071QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003072 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003073 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003074 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003075 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003076 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003077 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003078 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3079
3080 if (TypeParm)
3081 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003082
Chandler Carruth08836322011-05-01 00:51:33 +00003083 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003084 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003085 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003086
3087 TemplateTypeParmType *TypeCheck
3088 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3089 assert(!TypeCheck && "Template type parameter canonical type broken");
3090 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003091 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003092 TypeParm = new (*this, TypeAlignment)
3093 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003094
3095 Types.push_back(TypeParm);
3096 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3097
3098 return QualType(TypeParm, 0);
3099}
3100
John McCalle78aac42010-03-10 03:28:59 +00003101TypeSourceInfo *
3102ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3103 SourceLocation NameLoc,
3104 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003105 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003106 assert(!Name.getAsDependentTemplateName() &&
3107 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003108 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003109
3110 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003111 TemplateSpecializationTypeLoc TL =
3112 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003113 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003114 TL.setTemplateNameLoc(NameLoc);
3115 TL.setLAngleLoc(Args.getLAngleLoc());
3116 TL.setRAngleLoc(Args.getRAngleLoc());
3117 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3118 TL.setArgLocInfo(i, Args[i].getLocInfo());
3119 return DI;
3120}
3121
Mike Stump11289f42009-09-09 15:08:12 +00003122QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003123ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003124 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003125 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003126 assert(!Template.getAsDependentTemplateName() &&
3127 "No dependent template names here!");
3128
John McCall6b51f282009-11-23 01:53:49 +00003129 unsigned NumArgs = Args.size();
3130
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003131 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00003132 ArgVec.reserve(NumArgs);
3133 for (unsigned i = 0; i != NumArgs; ++i)
3134 ArgVec.push_back(Args[i].getArgument());
3135
John McCall2408e322010-04-27 00:57:59 +00003136 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003137 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003138}
3139
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003140#ifndef NDEBUG
3141static bool hasAnyPackExpansions(const TemplateArgument *Args,
3142 unsigned NumArgs) {
3143 for (unsigned I = 0; I != NumArgs; ++I)
3144 if (Args[I].isPackExpansion())
3145 return true;
3146
3147 return true;
3148}
3149#endif
3150
John McCall0ad16662009-10-29 08:12:44 +00003151QualType
3152ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00003153 const TemplateArgument *Args,
3154 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003155 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003156 assert(!Template.getAsDependentTemplateName() &&
3157 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003158 // Look through qualified template names.
3159 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3160 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003161
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003162 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003163 Template.getAsTemplateDecl() &&
3164 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003165 QualType CanonType;
3166 if (!Underlying.isNull())
3167 CanonType = getCanonicalType(Underlying);
3168 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003169 // We can get here with an alias template when the specialization contains
3170 // a pack expansion that does not match up with a parameter pack.
3171 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3172 "Caller must compute aliased type");
3173 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003174 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3175 NumArgs);
3176 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003177
Douglas Gregora8e02e72009-07-28 23:00:59 +00003178 // Allocate the (non-canonical) template specialization type, but don't
3179 // try to unique it: these types typically have location information that
3180 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003181 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3182 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003183 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003184 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003185 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003186 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3187 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003188
Douglas Gregor8bf42052009-02-09 18:46:07 +00003189 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003190 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003191}
3192
Mike Stump11289f42009-09-09 15:08:12 +00003193QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003194ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3195 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00003196 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003197 assert(!Template.getAsDependentTemplateName() &&
3198 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003199
Douglas Gregore29139c2011-03-03 17:04:51 +00003200 // Look through qualified template names.
3201 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3202 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003203
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003204 // Build the canonical template specialization type.
3205 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003206 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003207 CanonArgs.reserve(NumArgs);
3208 for (unsigned I = 0; I != NumArgs; ++I)
3209 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3210
3211 // Determine whether this canonical template specialization type already
3212 // exists.
3213 llvm::FoldingSetNodeID ID;
3214 TemplateSpecializationType::Profile(ID, CanonTemplate,
3215 CanonArgs.data(), NumArgs, *this);
3216
3217 void *InsertPos = 0;
3218 TemplateSpecializationType *Spec
3219 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3220
3221 if (!Spec) {
3222 // Allocate a new canonical template specialization type.
3223 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3224 sizeof(TemplateArgument) * NumArgs),
3225 TypeAlignment);
3226 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3227 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003228 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003229 Types.push_back(Spec);
3230 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3231 }
3232
3233 assert(Spec->isDependentType() &&
3234 "Non-dependent template-id type must have a canonical type");
3235 return QualType(Spec, 0);
3236}
3237
3238QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003239ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3240 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003241 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003242 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003243 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003244
3245 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003246 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003247 if (T)
3248 return QualType(T, 0);
3249
Douglas Gregorc42075a2010-02-04 18:10:26 +00003250 QualType Canon = NamedType;
3251 if (!Canon.isCanonical()) {
3252 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003253 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3254 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003255 (void)CheckT;
3256 }
3257
Abramo Bagnara6150c882010-05-11 21:36:43 +00003258 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003259 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003260 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003261 return QualType(T, 0);
3262}
3263
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003264QualType
Jay Foad39c79802011-01-12 09:06:06 +00003265ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003266 llvm::FoldingSetNodeID ID;
3267 ParenType::Profile(ID, InnerType);
3268
3269 void *InsertPos = 0;
3270 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3271 if (T)
3272 return QualType(T, 0);
3273
3274 QualType Canon = InnerType;
3275 if (!Canon.isCanonical()) {
3276 Canon = getCanonicalType(InnerType);
3277 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3278 assert(!CheckT && "Paren canonical type broken");
3279 (void)CheckT;
3280 }
3281
3282 T = new (*this) ParenType(InnerType, Canon);
3283 Types.push_back(T);
3284 ParenTypes.InsertNode(T, InsertPos);
3285 return QualType(T, 0);
3286}
3287
Douglas Gregor02085352010-03-31 20:19:30 +00003288QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3289 NestedNameSpecifier *NNS,
3290 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003291 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003292 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
3293
3294 if (Canon.isNull()) {
3295 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00003296 ElaboratedTypeKeyword CanonKeyword = Keyword;
3297 if (Keyword == ETK_None)
3298 CanonKeyword = ETK_Typename;
3299
3300 if (CanonNNS != NNS || CanonKeyword != Keyword)
3301 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003302 }
3303
3304 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003305 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003306
3307 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003308 DependentNameType *T
3309 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003310 if (T)
3311 return QualType(T, 0);
3312
Douglas Gregor02085352010-03-31 20:19:30 +00003313 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003314 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003315 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003316 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003317}
3318
Mike Stump11289f42009-09-09 15:08:12 +00003319QualType
John McCallc392f372010-06-11 00:33:02 +00003320ASTContext::getDependentTemplateSpecializationType(
3321 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003322 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003323 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003324 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003325 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003326 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003327 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3328 ArgCopy.push_back(Args[I].getArgument());
3329 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3330 ArgCopy.size(),
3331 ArgCopy.data());
3332}
3333
3334QualType
3335ASTContext::getDependentTemplateSpecializationType(
3336 ElaboratedTypeKeyword Keyword,
3337 NestedNameSpecifier *NNS,
3338 const IdentifierInfo *Name,
3339 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00003340 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003341 assert((!NNS || NNS->isDependent()) &&
3342 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003343
Douglas Gregorc42075a2010-02-04 18:10:26 +00003344 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003345 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3346 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003347
3348 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00003349 DependentTemplateSpecializationType *T
3350 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003351 if (T)
3352 return QualType(T, 0);
3353
John McCallc392f372010-06-11 00:33:02 +00003354 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003355
John McCallc392f372010-06-11 00:33:02 +00003356 ElaboratedTypeKeyword CanonKeyword = Keyword;
3357 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3358
3359 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003360 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003361 for (unsigned I = 0; I != NumArgs; ++I) {
3362 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3363 if (!CanonArgs[I].structurallyEquals(Args[I]))
3364 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003365 }
3366
John McCallc392f372010-06-11 00:33:02 +00003367 QualType Canon;
3368 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3369 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3370 Name, NumArgs,
3371 CanonArgs.data());
3372
3373 // Find the insert position again.
3374 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3375 }
3376
3377 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3378 sizeof(TemplateArgument) * NumArgs),
3379 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003380 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00003381 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003382 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003383 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003384 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003385}
3386
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003387QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00003388 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003389 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003390 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003391
3392 assert(Pattern->containsUnexpandedParameterPack() &&
3393 "Pack expansions must expand one or more parameter packs");
3394 void *InsertPos = 0;
3395 PackExpansionType *T
3396 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3397 if (T)
3398 return QualType(T, 0);
3399
3400 QualType Canon;
3401 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003402 Canon = getCanonicalType(Pattern);
3403 // The canonical type might not contain an unexpanded parameter pack, if it
3404 // contains an alias template specialization which ignores one of its
3405 // parameters.
3406 if (Canon->containsUnexpandedParameterPack()) {
3407 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003408
Richard Smith68eea502012-07-16 00:20:35 +00003409 // Find the insert position again, in case we inserted an element into
3410 // PackExpansionTypes and invalidated our insert position.
3411 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3412 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003413 }
3414
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003415 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003416 Types.push_back(T);
3417 PackExpansionTypes.InsertNode(T, InsertPos);
3418 return QualType(T, 0);
3419}
3420
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003421/// CmpProtocolNames - Comparison predicate for sorting protocols
3422/// alphabetically.
3423static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3424 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00003425 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003426}
3427
John McCall8b07ec22010-05-15 11:32:37 +00003428static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00003429 unsigned NumProtocols) {
3430 if (NumProtocols == 0) return true;
3431
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003432 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3433 return false;
3434
John McCallfc93cf92009-10-22 22:37:11 +00003435 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003436 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3437 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003438 return false;
3439 return true;
3440}
3441
3442static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003443 unsigned &NumProtocols) {
3444 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00003445
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003446 // Sort protocols, keyed by name.
3447 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3448
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003449 // Canonicalize.
3450 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3451 Protocols[I] = Protocols[I]->getCanonicalDecl();
3452
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003453 // Remove duplicates.
3454 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3455 NumProtocols = ProtocolsEnd-Protocols;
3456}
3457
John McCall8b07ec22010-05-15 11:32:37 +00003458QualType ASTContext::getObjCObjectType(QualType BaseType,
3459 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003460 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00003461 // If the base type is an interface and there aren't any protocols
3462 // to add, then the interface type will do just fine.
3463 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3464 return BaseType;
3465
3466 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003467 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00003468 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00003469 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00003470 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3471 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003472
John McCall8b07ec22010-05-15 11:32:37 +00003473 // Build the canonical type, which has the canonical base type and
3474 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00003475 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00003476 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3477 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3478 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003479 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003480 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003481 unsigned UniqueCount = NumProtocols;
3482
John McCallfc93cf92009-10-22 22:37:11 +00003483 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00003484 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3485 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00003486 } else {
John McCall8b07ec22010-05-15 11:32:37 +00003487 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3488 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003489 }
3490
3491 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003492 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3493 }
3494
3495 unsigned Size = sizeof(ObjCObjectTypeImpl);
3496 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3497 void *Mem = Allocate(Size, TypeAlignment);
3498 ObjCObjectTypeImpl *T =
3499 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3500
3501 Types.push_back(T);
3502 ObjCObjectTypes.InsertNode(T, InsertPos);
3503 return QualType(T, 0);
3504}
3505
3506/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3507/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003508QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003509 llvm::FoldingSetNodeID ID;
3510 ObjCObjectPointerType::Profile(ID, ObjectT);
3511
3512 void *InsertPos = 0;
3513 if (ObjCObjectPointerType *QT =
3514 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3515 return QualType(QT, 0);
3516
3517 // Find the canonical object type.
3518 QualType Canonical;
3519 if (!ObjectT.isCanonical()) {
3520 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3521
3522 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003523 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3524 }
3525
Douglas Gregorf85bee62010-02-08 22:59:26 +00003526 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003527 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3528 ObjCObjectPointerType *QType =
3529 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003530
Steve Narofffb4330f2009-06-17 22:40:22 +00003531 Types.push_back(QType);
3532 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003533 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003534}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003535
Douglas Gregor1c283312010-08-11 12:19:30 +00003536/// getObjCInterfaceType - Return the unique reference to the type for the
3537/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003538QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3539 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003540 if (Decl->TypeForDecl)
3541 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003542
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003543 if (PrevDecl) {
3544 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3545 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3546 return QualType(PrevDecl->TypeForDecl, 0);
3547 }
3548
Douglas Gregor7671e532011-12-16 16:34:57 +00003549 // Prefer the definition, if there is one.
3550 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3551 Decl = Def;
3552
Douglas Gregor1c283312010-08-11 12:19:30 +00003553 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3554 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3555 Decl->TypeForDecl = T;
3556 Types.push_back(T);
3557 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003558}
3559
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003560/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3561/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003562/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003563/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003564/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003565QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003566 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003567 if (tofExpr->isTypeDependent()) {
3568 llvm::FoldingSetNodeID ID;
3569 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003570
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003571 void *InsertPos = 0;
3572 DependentTypeOfExprType *Canon
3573 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3574 if (Canon) {
3575 // We already have a "canonical" version of an identical, dependent
3576 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003577 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003578 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003579 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003580 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003581 Canon
3582 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003583 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3584 toe = Canon;
3585 }
3586 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003587 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003588 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003589 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003590 Types.push_back(toe);
3591 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003592}
3593
Steve Naroffa773cd52007-08-01 18:02:17 +00003594/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3595/// TypeOfType AST's. The only motivation to unique these nodes would be
3596/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003597/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003598/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003599QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003600 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003601 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003602 Types.push_back(tot);
3603 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003604}
3605
Anders Carlssonad6bd352009-06-24 21:24:56 +00003606
Anders Carlsson81df7b82009-06-24 19:06:50 +00003607/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3608/// DecltypeType AST's. The only motivation to unique these nodes would be
3609/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003610/// an issue. This doesn't effect the type checker, since it operates
David Blaikie876657b2011-11-06 22:28:03 +00003611/// on canonical types (which are always unique).
Douglas Gregor81495f32012-02-12 18:42:33 +00003612QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003613 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003614
3615 // C++0x [temp.type]p2:
3616 // If an expression e involves a template parameter, decltype(e) denotes a
3617 // unique dependent type. Two such decltype-specifiers refer to the same
3618 // type only if their expressions are equivalent (14.5.6.1).
3619 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003620 llvm::FoldingSetNodeID ID;
3621 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003622
Douglas Gregora21f6c32009-07-30 23:36:40 +00003623 void *InsertPos = 0;
3624 DependentDecltypeType *Canon
3625 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3626 if (Canon) {
3627 // We already have a "canonical" version of an equivalent, dependent
3628 // decltype type. Use that as our canonical type.
Richard Smithef8bf432012-08-13 20:08:14 +00003629 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
Douglas Gregora21f6c32009-07-30 23:36:40 +00003630 QualType((DecltypeType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003631 } else {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003632 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003633 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003634 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3635 dt = Canon;
3636 }
3637 } else {
Douglas Gregor81495f32012-02-12 18:42:33 +00003638 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3639 getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003640 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003641 Types.push_back(dt);
3642 return QualType(dt, 0);
3643}
3644
Alexis Hunte852b102011-05-24 22:41:36 +00003645/// getUnaryTransformationType - We don't unique these, since the memory
3646/// savings are minimal and these are rare.
3647QualType ASTContext::getUnaryTransformType(QualType BaseType,
3648 QualType UnderlyingType,
3649 UnaryTransformType::UTTKind Kind)
3650 const {
3651 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003652 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3653 Kind,
3654 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003655 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003656 Types.push_back(Ty);
3657 return QualType(Ty, 0);
3658}
3659
Richard Smith2a7d4812013-05-04 07:00:32 +00003660/// getAutoType - Return the uniqued reference to the 'auto' type which has been
3661/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3662/// canonical deduced-but-dependent 'auto' type.
3663QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003664 bool IsDependent) const {
3665 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00003666 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003667
Richard Smith2a7d4812013-05-04 07:00:32 +00003668 // Look in the folding set for an existing type.
Richard Smithb2bc2e62011-02-21 20:05:19 +00003669 void *InsertPos = 0;
Richard Smith2a7d4812013-05-04 07:00:32 +00003670 llvm::FoldingSetNodeID ID;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003671 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00003672 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3673 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003674
Richard Smith74aeef52013-04-26 16:15:35 +00003675 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smith27d807c2013-04-30 13:56:41 +00003676 IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003677 IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003678 Types.push_back(AT);
3679 if (InsertPos)
3680 AutoTypes.InsertNode(AT, InsertPos);
3681 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003682}
3683
Eli Friedman0dfb8892011-10-06 23:00:33 +00003684/// getAtomicType - Return the uniqued reference to the atomic type for
3685/// the given value type.
3686QualType ASTContext::getAtomicType(QualType T) const {
3687 // Unique pointers, to guarantee there is only one pointer of a particular
3688 // structure.
3689 llvm::FoldingSetNodeID ID;
3690 AtomicType::Profile(ID, T);
3691
3692 void *InsertPos = 0;
3693 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3694 return QualType(AT, 0);
3695
3696 // If the atomic value type isn't canonical, this won't be a canonical type
3697 // either, so fill in the canonical type field.
3698 QualType Canonical;
3699 if (!T.isCanonical()) {
3700 Canonical = getAtomicType(getCanonicalType(T));
3701
3702 // Get the new insert position for the node we care about.
3703 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3704 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3705 }
3706 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3707 Types.push_back(New);
3708 AtomicTypes.InsertNode(New, InsertPos);
3709 return QualType(New, 0);
3710}
3711
Richard Smith02e85f32011-04-14 22:09:26 +00003712/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3713QualType ASTContext::getAutoDeductType() const {
3714 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00003715 AutoDeductTy = QualType(
3716 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003717 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00003718 0);
Richard Smith02e85f32011-04-14 22:09:26 +00003719 return AutoDeductTy;
3720}
3721
3722/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3723QualType ASTContext::getAutoRRefDeductType() const {
3724 if (AutoRRefDeductTy.isNull())
3725 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3726 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3727 return AutoRRefDeductTy;
3728}
3729
Chris Lattnerfb072462007-01-23 05:45:31 +00003730/// getTagDeclType - Return the unique reference to the type for the
3731/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003732QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003733 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003734 // FIXME: What is the design on getTagDeclType when it requires casting
3735 // away const? mutable?
3736 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003737}
3738
Mike Stump11289f42009-09-09 15:08:12 +00003739/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3740/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3741/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003742CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003743 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003744}
Chris Lattnerfb072462007-01-23 05:45:31 +00003745
Hans Wennborg27541db2011-10-27 08:29:09 +00003746/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3747CanQualType ASTContext::getIntMaxType() const {
3748 return getFromTargetType(Target->getIntMaxType());
3749}
3750
3751/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3752CanQualType ASTContext::getUIntMaxType() const {
3753 return getFromTargetType(Target->getUIntMaxType());
3754}
3755
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003756/// getSignedWCharType - Return the type of "signed wchar_t".
3757/// Used when in C++, as a GCC extension.
3758QualType ASTContext::getSignedWCharType() const {
3759 // FIXME: derive from "Target" ?
3760 return WCharTy;
3761}
3762
3763/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3764/// Used when in C++, as a GCC extension.
3765QualType ASTContext::getUnsignedWCharType() const {
3766 // FIXME: derive from "Target" ?
3767 return UnsignedIntTy;
3768}
3769
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00003770QualType ASTContext::getIntPtrType() const {
3771 return getFromTargetType(Target->getIntPtrType());
3772}
3773
3774QualType ASTContext::getUIntPtrType() const {
3775 return getCorrespondingUnsignedType(getIntPtrType());
3776}
3777
Hans Wennborg27541db2011-10-27 08:29:09 +00003778/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003779/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3780QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003781 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003782}
3783
Eli Friedman4e91899e2012-11-27 02:58:24 +00003784/// \brief Return the unique type for "pid_t" defined in
3785/// <sys/types.h>. We need this to compute the correct type for vfork().
3786QualType ASTContext::getProcessIDType() const {
3787 return getFromTargetType(Target->getProcessIDType());
3788}
3789
Chris Lattnera21ad802008-04-02 05:18:44 +00003790//===----------------------------------------------------------------------===//
3791// Type Operators
3792//===----------------------------------------------------------------------===//
3793
Jay Foad39c79802011-01-12 09:06:06 +00003794CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003795 // Push qualifiers into arrays, and then discard any remaining
3796 // qualifiers.
3797 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003798 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003799 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003800 QualType Result;
3801 if (isa<ArrayType>(Ty)) {
3802 Result = getArrayDecayedType(QualType(Ty,0));
3803 } else if (isa<FunctionType>(Ty)) {
3804 Result = getPointerType(QualType(Ty, 0));
3805 } else {
3806 Result = QualType(Ty, 0);
3807 }
3808
3809 return CanQualType::CreateUnsafe(Result);
3810}
3811
John McCall6c9dd522011-01-18 07:41:22 +00003812QualType ASTContext::getUnqualifiedArrayType(QualType type,
3813 Qualifiers &quals) {
3814 SplitQualType splitType = type.getSplitUnqualifiedType();
3815
3816 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3817 // the unqualified desugared type and then drops it on the floor.
3818 // We then have to strip that sugar back off with
3819 // getUnqualifiedDesugaredType(), which is silly.
3820 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003821 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003822
3823 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003824 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003825 quals = splitType.Quals;
3826 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003827 }
3828
John McCall6c9dd522011-01-18 07:41:22 +00003829 // Otherwise, recurse on the array's element type.
3830 QualType elementType = AT->getElementType();
3831 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3832
3833 // If that didn't change the element type, AT has no qualifiers, so we
3834 // can just use the results in splitType.
3835 if (elementType == unqualElementType) {
3836 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00003837 quals = splitType.Quals;
3838 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00003839 }
3840
3841 // Otherwise, add in the qualifiers from the outermost type, then
3842 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00003843 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003844
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003845 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003846 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003847 CAT->getSizeModifier(), 0);
3848 }
3849
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003850 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003851 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003852 }
3853
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003854 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003855 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003856 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003857 VAT->getSizeModifier(),
3858 VAT->getIndexTypeCVRQualifiers(),
3859 VAT->getBracketsRange());
3860 }
3861
3862 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003863 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003864 DSAT->getSizeModifier(), 0,
3865 SourceRange());
3866}
3867
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003868/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3869/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3870/// they point to and return true. If T1 and T2 aren't pointer types
3871/// or pointer-to-member types, or if they are not similar at this
3872/// level, returns false and leaves T1 and T2 unchanged. Top-level
3873/// qualifiers on T1 and T2 are ignored. This function will typically
3874/// be called in a loop that successively "unwraps" pointer and
3875/// pointer-to-member types to compare them at each level.
3876bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3877 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3878 *T2PtrType = T2->getAs<PointerType>();
3879 if (T1PtrType && T2PtrType) {
3880 T1 = T1PtrType->getPointeeType();
3881 T2 = T2PtrType->getPointeeType();
3882 return true;
3883 }
3884
3885 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3886 *T2MPType = T2->getAs<MemberPointerType>();
3887 if (T1MPType && T2MPType &&
3888 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3889 QualType(T2MPType->getClass(), 0))) {
3890 T1 = T1MPType->getPointeeType();
3891 T2 = T2MPType->getPointeeType();
3892 return true;
3893 }
3894
David Blaikiebbafb8a2012-03-11 07:00:24 +00003895 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003896 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3897 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3898 if (T1OPType && T2OPType) {
3899 T1 = T1OPType->getPointeeType();
3900 T2 = T2OPType->getPointeeType();
3901 return true;
3902 }
3903 }
3904
3905 // FIXME: Block pointers, too?
3906
3907 return false;
3908}
3909
Jay Foad39c79802011-01-12 09:06:06 +00003910DeclarationNameInfo
3911ASTContext::getNameForTemplate(TemplateName Name,
3912 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003913 switch (Name.getKind()) {
3914 case TemplateName::QualifiedTemplate:
3915 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003916 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00003917 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3918 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003919
John McCalld9dfe3a2011-06-30 08:33:18 +00003920 case TemplateName::OverloadedTemplate: {
3921 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3922 // DNInfo work in progress: CHECKME: what about DNLoc?
3923 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3924 }
3925
3926 case TemplateName::DependentTemplate: {
3927 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003928 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00003929 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003930 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3931 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00003932 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003933 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3934 // DNInfo work in progress: FIXME: source locations?
3935 DeclarationNameLoc DNLoc;
3936 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3937 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3938 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00003939 }
3940 }
3941
John McCalld9dfe3a2011-06-30 08:33:18 +00003942 case TemplateName::SubstTemplateTemplateParm: {
3943 SubstTemplateTemplateParmStorage *subst
3944 = Name.getAsSubstTemplateTemplateParm();
3945 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3946 NameLoc);
3947 }
3948
3949 case TemplateName::SubstTemplateTemplateParmPack: {
3950 SubstTemplateTemplateParmPackStorage *subst
3951 = Name.getAsSubstTemplateTemplateParmPack();
3952 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3953 NameLoc);
3954 }
3955 }
3956
3957 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00003958}
3959
Jay Foad39c79802011-01-12 09:06:06 +00003960TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003961 switch (Name.getKind()) {
3962 case TemplateName::QualifiedTemplate:
3963 case TemplateName::Template: {
3964 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003965 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00003966 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003967 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3968
3969 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00003970 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003971 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00003972
John McCalld9dfe3a2011-06-30 08:33:18 +00003973 case TemplateName::OverloadedTemplate:
3974 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00003975
John McCalld9dfe3a2011-06-30 08:33:18 +00003976 case TemplateName::DependentTemplate: {
3977 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3978 assert(DTN && "Non-dependent template names must refer to template decls.");
3979 return DTN->CanonicalTemplateName;
3980 }
3981
3982 case TemplateName::SubstTemplateTemplateParm: {
3983 SubstTemplateTemplateParmStorage *subst
3984 = Name.getAsSubstTemplateTemplateParm();
3985 return getCanonicalTemplateName(subst->getReplacement());
3986 }
3987
3988 case TemplateName::SubstTemplateTemplateParmPack: {
3989 SubstTemplateTemplateParmPackStorage *subst
3990 = Name.getAsSubstTemplateTemplateParmPack();
3991 TemplateTemplateParmDecl *canonParameter
3992 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3993 TemplateArgument canonArgPack
3994 = getCanonicalTemplateArgument(subst->getArgumentPack());
3995 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3996 }
3997 }
3998
3999 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00004000}
4001
Douglas Gregoradee3e32009-11-11 23:06:43 +00004002bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4003 X = getCanonicalTemplateName(X);
4004 Y = getCanonicalTemplateName(Y);
4005 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4006}
4007
Mike Stump11289f42009-09-09 15:08:12 +00004008TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00004009ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00004010 switch (Arg.getKind()) {
4011 case TemplateArgument::Null:
4012 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004013
Douglas Gregora8e02e72009-07-28 23:00:59 +00004014 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00004015 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004016
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004017 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00004018 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
4019 return TemplateArgument(D, Arg.isDeclForReferenceParam());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004020 }
Mike Stump11289f42009-09-09 15:08:12 +00004021
Eli Friedmanb826a002012-09-26 02:36:12 +00004022 case TemplateArgument::NullPtr:
4023 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4024 /*isNullPtr*/true);
4025
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004026 case TemplateArgument::Template:
4027 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004028
4029 case TemplateArgument::TemplateExpansion:
4030 return TemplateArgument(getCanonicalTemplateName(
4031 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00004032 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004033
Douglas Gregora8e02e72009-07-28 23:00:59 +00004034 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004035 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00004036
Douglas Gregora8e02e72009-07-28 23:00:59 +00004037 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00004038 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00004039
Douglas Gregora8e02e72009-07-28 23:00:59 +00004040 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00004041 if (Arg.pack_size() == 0)
4042 return Arg;
4043
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004044 TemplateArgument *CanonArgs
4045 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00004046 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004047 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00004048 AEnd = Arg.pack_end();
4049 A != AEnd; (void)++A, ++Idx)
4050 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00004051
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004052 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00004053 }
4054 }
4055
4056 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00004057 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00004058}
4059
Douglas Gregor333489b2009-03-27 23:10:48 +00004060NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00004061ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00004062 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00004063 return 0;
4064
4065 switch (NNS->getKind()) {
4066 case NestedNameSpecifier::Identifier:
4067 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00004068 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00004069 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4070 NNS->getAsIdentifier());
4071
4072 case NestedNameSpecifier::Namespace:
4073 // A namespace is canonical; build a nested-name-specifier with
4074 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004075 return NestedNameSpecifier::Create(*this, 0,
4076 NNS->getAsNamespace()->getOriginalNamespace());
4077
4078 case NestedNameSpecifier::NamespaceAlias:
4079 // A namespace is canonical; build a nested-name-specifier with
4080 // this namespace and no prefix.
4081 return NestedNameSpecifier::Create(*this, 0,
4082 NNS->getAsNamespaceAlias()->getNamespace()
4083 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00004084
4085 case NestedNameSpecifier::TypeSpec:
4086 case NestedNameSpecifier::TypeSpecWithTemplate: {
4087 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004088
4089 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4090 // break it apart into its prefix and identifier, then reconsititute those
4091 // as the canonical nested-name-specifier. This is required to canonicalize
4092 // a dependent nested-name-specifier involving typedefs of dependent-name
4093 // types, e.g.,
4094 // typedef typename T::type T1;
4095 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00004096 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4097 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00004098 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004099
Eli Friedman5358a0a2012-03-03 04:09:56 +00004100 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4101 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4102 // first place?
John McCall33ddac02011-01-19 10:06:00 +00004103 return NestedNameSpecifier::Create(*this, 0, false,
4104 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00004105 }
4106
4107 case NestedNameSpecifier::Global:
4108 // The global specifier is canonical and unique.
4109 return NNS;
4110 }
4111
David Blaikie8a40f702012-01-17 06:56:22 +00004112 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00004113}
4114
Chris Lattner7adf0762008-08-04 07:31:14 +00004115
Jay Foad39c79802011-01-12 09:06:06 +00004116const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004117 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004118 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00004119 // Handle the common positive case fast.
4120 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4121 return AT;
4122 }
Mike Stump11289f42009-09-09 15:08:12 +00004123
John McCall8ccfcb52009-09-24 19:53:00 +00004124 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00004125 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00004126 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004127
John McCall8ccfcb52009-09-24 19:53:00 +00004128 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00004129 // implements C99 6.7.3p8: "If the specification of an array type includes
4130 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00004131
Chris Lattner7adf0762008-08-04 07:31:14 +00004132 // If we get here, we either have type qualifiers on the type, or we have
4133 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00004134 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00004135
John McCall33ddac02011-01-19 10:06:00 +00004136 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004137 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00004138
Chris Lattner7adf0762008-08-04 07:31:14 +00004139 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00004140 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall33ddac02011-01-19 10:06:00 +00004141 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00004142 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00004143
Chris Lattner7adf0762008-08-04 07:31:14 +00004144 // Otherwise, we have an array and we have qualifiers on it. Push the
4145 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00004146 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00004147
Chris Lattner7adf0762008-08-04 07:31:14 +00004148 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4149 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4150 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004151 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00004152 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4153 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4154 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004155 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00004156
Mike Stump11289f42009-09-09 15:08:12 +00004157 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00004158 = dyn_cast<DependentSizedArrayType>(ATy))
4159 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00004160 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004161 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00004162 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004163 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004164 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00004165
Chris Lattner7adf0762008-08-04 07:31:14 +00004166 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00004167 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004168 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00004169 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004170 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004171 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00004172}
4173
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004174QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00004175 if (T->isArrayType() || T->isFunctionType())
4176 return getDecayedType(T);
4177 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00004178}
4179
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004180QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004181 T = getVariableArrayDecayedType(T);
4182 T = getAdjustedParameterType(T);
4183 return T.getUnqualifiedType();
4184}
4185
Chris Lattnera21ad802008-04-02 05:18:44 +00004186/// getArrayDecayedType - Return the properly qualified result of decaying the
4187/// specified array type to a pointer. This operation is non-trivial when
4188/// handling typedefs etc. The canonical type of "T" must be an array type,
4189/// this returns a pointer to a properly qualified element of the array.
4190///
4191/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004192QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004193 // Get the element type with 'getAsArrayType' so that we don't lose any
4194 // typedefs in the element type of the array. This also handles propagation
4195 // of type qualifiers from the array type into the element type if present
4196 // (C99 6.7.3p8).
4197 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4198 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004199
Chris Lattner7adf0762008-08-04 07:31:14 +00004200 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004201
4202 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00004203 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00004204}
4205
John McCall33ddac02011-01-19 10:06:00 +00004206QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4207 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00004208}
4209
John McCall33ddac02011-01-19 10:06:00 +00004210QualType ASTContext::getBaseElementType(QualType type) const {
4211 Qualifiers qs;
4212 while (true) {
4213 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004214 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00004215 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00004216
John McCall33ddac02011-01-19 10:06:00 +00004217 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00004218 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00004219 }
Mike Stump11289f42009-09-09 15:08:12 +00004220
John McCall33ddac02011-01-19 10:06:00 +00004221 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00004222}
4223
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004224/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00004225uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004226ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4227 uint64_t ElementCount = 1;
4228 do {
4229 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00004230 CA = dyn_cast_or_null<ConstantArrayType>(
4231 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004232 } while (CA);
4233 return ElementCount;
4234}
4235
Steve Naroff0af91202007-04-27 21:51:21 +00004236/// getFloatingRank - Return a relative rank for floating point types.
4237/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00004238static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00004239 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00004240 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00004241
John McCall9dd450b2009-09-21 23:43:11 +00004242 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4243 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004244 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004245 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00004246 case BuiltinType::Float: return FloatRank;
4247 case BuiltinType::Double: return DoubleRank;
4248 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00004249 }
4250}
4251
Mike Stump11289f42009-09-09 15:08:12 +00004252/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4253/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00004254/// 'typeDomain' is a real floating point or complex type.
4255/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004256QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4257 QualType Domain) const {
4258 FloatingRank EltRank = getFloatingRank(Size);
4259 if (Domain->isComplexType()) {
4260 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004261 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00004262 case FloatRank: return FloatComplexTy;
4263 case DoubleRank: return DoubleComplexTy;
4264 case LongDoubleRank: return LongDoubleComplexTy;
4265 }
Steve Naroff0af91202007-04-27 21:51:21 +00004266 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004267
4268 assert(Domain->isRealFloatingType() && "Unknown domain!");
4269 switch (EltRank) {
Joey Goulydd7f4562013-01-23 11:56:20 +00004270 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004271 case FloatRank: return FloatTy;
4272 case DoubleRank: return DoubleTy;
4273 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00004274 }
David Blaikief47fa302012-01-17 02:30:50 +00004275 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00004276}
4277
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004278/// getFloatingTypeOrder - Compare the rank of the two specified floating
4279/// point types, ignoring the domain of the type (i.e. 'double' ==
4280/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004281/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004282int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00004283 FloatingRank LHSR = getFloatingRank(LHS);
4284 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004285
Chris Lattnerb90739d2008-04-06 23:38:49 +00004286 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004287 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00004288 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004289 return 1;
4290 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00004291}
4292
Chris Lattner76a00cf2008-04-06 22:59:24 +00004293/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4294/// routine will assert if passed a built-in type that isn't an integer or enum,
4295/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00004296unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00004297 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004298
Chris Lattner76a00cf2008-04-06 22:59:24 +00004299 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004300 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004301 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004302 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004303 case BuiltinType::Char_S:
4304 case BuiltinType::Char_U:
4305 case BuiltinType::SChar:
4306 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004307 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004308 case BuiltinType::Short:
4309 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004310 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004311 case BuiltinType::Int:
4312 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004313 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004314 case BuiltinType::Long:
4315 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004316 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004317 case BuiltinType::LongLong:
4318 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004319 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00004320 case BuiltinType::Int128:
4321 case BuiltinType::UInt128:
4322 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00004323 }
4324}
4325
Eli Friedman629ffb92009-08-20 04:21:42 +00004326/// \brief Whether this is a promotable bitfield reference according
4327/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4328///
4329/// \returns the type this bit-field will promote to, or NULL if no
4330/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004331QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004332 if (E->isTypeDependent() || E->isValueDependent())
4333 return QualType();
4334
John McCalld25db7e2013-05-06 21:39:12 +00004335 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00004336 if (!Field)
4337 return QualType();
4338
4339 QualType FT = Field->getType();
4340
Richard Smithcaf33902011-10-10 18:28:20 +00004341 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004342 uint64_t IntSize = getTypeSize(IntTy);
4343 // GCC extension compatibility: if the bit-field size is less than or equal
4344 // to the size of int, it gets promoted no matter what its type is.
4345 // For instance, unsigned long bf : 4 gets promoted to signed int.
4346 if (BitWidth < IntSize)
4347 return IntTy;
4348
4349 if (BitWidth == IntSize)
4350 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4351
4352 // Types bigger than int are not subject to promotions, and therefore act
4353 // like the base type.
4354 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4355 // is ridiculous.
4356 return QualType();
4357}
4358
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004359/// getPromotedIntegerType - Returns the type that Promotable will
4360/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4361/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004362QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004363 assert(!Promotable.isNull());
4364 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004365 if (const EnumType *ET = Promotable->getAs<EnumType>())
4366 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004367
4368 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4369 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4370 // (3.9.1) can be converted to a prvalue of the first of the following
4371 // types that can represent all the values of its underlying type:
4372 // int, unsigned int, long int, unsigned long int, long long int, or
4373 // unsigned long long int [...]
4374 // FIXME: Is there some better way to compute this?
4375 if (BT->getKind() == BuiltinType::WChar_S ||
4376 BT->getKind() == BuiltinType::WChar_U ||
4377 BT->getKind() == BuiltinType::Char16 ||
4378 BT->getKind() == BuiltinType::Char32) {
4379 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4380 uint64_t FromSize = getTypeSize(BT);
4381 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4382 LongLongTy, UnsignedLongLongTy };
4383 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4384 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4385 if (FromSize < ToSize ||
4386 (FromSize == ToSize &&
4387 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4388 return PromoteTypes[Idx];
4389 }
4390 llvm_unreachable("char type should fit into long long");
4391 }
4392 }
4393
4394 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004395 if (Promotable->isSignedIntegerType())
4396 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00004397 uint64_t PromotableSize = getIntWidth(Promotable);
4398 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004399 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4400 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4401}
4402
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004403/// \brief Recurses in pointer/array types until it finds an objc retainable
4404/// type and returns its ownership.
4405Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4406 while (!T.isNull()) {
4407 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4408 return T.getObjCLifetime();
4409 if (T->isArrayType())
4410 T = getBaseElementType(T);
4411 else if (const PointerType *PT = T->getAs<PointerType>())
4412 T = PT->getPointeeType();
4413 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004414 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004415 else
4416 break;
4417 }
4418
4419 return Qualifiers::OCL_None;
4420}
4421
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004422static const Type *getIntegerTypeForEnum(const EnumType *ET) {
4423 // Incomplete enum types are not treated as integer types.
4424 // FIXME: In C++, enum types are never integer types.
4425 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
4426 return ET->getDecl()->getIntegerType().getTypePtr();
4427 return NULL;
4428}
4429
Mike Stump11289f42009-09-09 15:08:12 +00004430/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004431/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004432/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004433int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004434 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4435 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004436
4437 // Unwrap enums to their underlying type.
4438 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
4439 LHSC = getIntegerTypeForEnum(ET);
4440 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
4441 RHSC = getIntegerTypeForEnum(ET);
4442
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004443 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004444
Chris Lattner76a00cf2008-04-06 22:59:24 +00004445 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4446 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004447
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004448 unsigned LHSRank = getIntegerRank(LHSC);
4449 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004450
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004451 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4452 if (LHSRank == RHSRank) return 0;
4453 return LHSRank > RHSRank ? 1 : -1;
4454 }
Mike Stump11289f42009-09-09 15:08:12 +00004455
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004456 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4457 if (LHSUnsigned) {
4458 // If the unsigned [LHS] type is larger, return it.
4459 if (LHSRank >= RHSRank)
4460 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004461
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004462 // If the signed type can represent all values of the unsigned type, it
4463 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004464 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004465 return -1;
4466 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004467
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004468 // If the unsigned [RHS] type is larger, return it.
4469 if (RHSRank >= LHSRank)
4470 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004471
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004472 // If the signed type can represent all values of the unsigned type, it
4473 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004474 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004475 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004476}
Anders Carlsson98f07902007-08-17 05:31:46 +00004477
Anders Carlsson6d417272009-11-14 21:45:58 +00004478static RecordDecl *
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004479CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
4480 DeclContext *DC, IdentifierInfo *Id) {
4481 SourceLocation Loc;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004482 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004483 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00004484 else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004485 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00004486}
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004487
Mike Stump11289f42009-09-09 15:08:12 +00004488// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00004489QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004490 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00004491 CFConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004492 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004493 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00004494 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004495
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004496 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00004497
Anders Carlsson98f07902007-08-17 05:31:46 +00004498 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004499 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004500 // int flags;
4501 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00004502 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004503 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00004504 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004505 FieldTypes[3] = LongTy;
4506
Anders Carlsson98f07902007-08-17 05:31:46 +00004507 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004508 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00004509 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004510 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00004511 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00004512 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00004513 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004514 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004515 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004516 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004517 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004518 }
4519
Douglas Gregord5058122010-02-11 01:19:42 +00004520 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00004521 }
Mike Stump11289f42009-09-09 15:08:12 +00004522
Anders Carlsson98f07902007-08-17 05:31:46 +00004523 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00004524}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004525
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004526QualType ASTContext::getObjCSuperType() const {
4527 if (ObjCSuperType.isNull()) {
4528 RecordDecl *ObjCSuperTypeDecl =
4529 CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get("objc_super"));
4530 TUDecl->addDecl(ObjCSuperTypeDecl);
4531 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4532 }
4533 return ObjCSuperType;
4534}
4535
Douglas Gregor512b0772009-04-23 22:29:11 +00004536void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004537 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00004538 assert(Rec && "Invalid CFConstantStringType");
4539 CFConstantStringTypeDecl = Rec->getDecl();
4540}
4541
Jay Foad39c79802011-01-12 09:06:06 +00004542QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004543 if (BlockDescriptorType)
4544 return getTagDeclType(BlockDescriptorType);
4545
4546 RecordDecl *T;
4547 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004548 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004549 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00004550 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004551
4552 QualType FieldTypes[] = {
4553 UnsignedLongTy,
4554 UnsignedLongTy,
4555 };
4556
Craig Topperd6d31ac2013-07-15 08:24:27 +00004557 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00004558 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004559 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004560 };
4561
4562 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004563 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00004564 SourceLocation(),
4565 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004566 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00004567 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004568 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004569 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004570 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00004571 T->addDecl(Field);
4572 }
4573
Douglas Gregord5058122010-02-11 01:19:42 +00004574 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004575
4576 BlockDescriptorType = T;
4577
4578 return getTagDeclType(BlockDescriptorType);
4579}
4580
Jay Foad39c79802011-01-12 09:06:06 +00004581QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004582 if (BlockDescriptorExtendedType)
4583 return getTagDeclType(BlockDescriptorExtendedType);
4584
4585 RecordDecl *T;
4586 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004587 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004588 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00004589 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004590
4591 QualType FieldTypes[] = {
4592 UnsignedLongTy,
4593 UnsignedLongTy,
4594 getPointerType(VoidPtrTy),
4595 getPointerType(VoidPtrTy)
4596 };
4597
Craig Topperd6d31ac2013-07-15 08:24:27 +00004598 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004599 "reserved",
4600 "Size",
4601 "CopyFuncPtr",
4602 "DestroyFuncPtr"
4603 };
4604
4605 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004606 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004607 SourceLocation(),
4608 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004609 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004610 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004611 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004612 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004613 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004614 T->addDecl(Field);
4615 }
4616
Douglas Gregord5058122010-02-11 01:19:42 +00004617 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004618
4619 BlockDescriptorExtendedType = T;
4620
4621 return getTagDeclType(BlockDescriptorExtendedType);
4622}
4623
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004624/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4625/// requires copy/dispose. Note that this must match the logic
4626/// in buildByrefHelpers.
4627bool ASTContext::BlockRequiresCopying(QualType Ty,
4628 const VarDecl *D) {
4629 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4630 const Expr *copyExpr = getBlockVarCopyInits(D);
4631 if (!copyExpr && record->hasTrivialDestructor()) return false;
4632
Mike Stump94967902009-10-21 18:16:27 +00004633 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004634 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004635
4636 if (!Ty->isObjCRetainableType()) return false;
4637
4638 Qualifiers qs = Ty.getQualifiers();
4639
4640 // If we have lifetime, that dominates.
4641 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4642 assert(getLangOpts().ObjCAutoRefCount);
4643
4644 switch (lifetime) {
4645 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4646
4647 // These are just bits as far as the runtime is concerned.
4648 case Qualifiers::OCL_ExplicitNone:
4649 case Qualifiers::OCL_Autoreleasing:
4650 return false;
4651
4652 // Tell the runtime that this is ARC __weak, called by the
4653 // byref routines.
4654 case Qualifiers::OCL_Weak:
4655 // ARC __strong __block variables need to be retained.
4656 case Qualifiers::OCL_Strong:
4657 return true;
4658 }
4659 llvm_unreachable("fell out of lifetime switch!");
4660 }
4661 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4662 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00004663}
4664
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004665bool ASTContext::getByrefLifetime(QualType Ty,
4666 Qualifiers::ObjCLifetime &LifeTime,
4667 bool &HasByrefExtendedLayout) const {
4668
4669 if (!getLangOpts().ObjC1 ||
4670 getLangOpts().getGC() != LangOptions::NonGC)
4671 return false;
4672
4673 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00004674 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004675 HasByrefExtendedLayout = true;
4676 LifeTime = Qualifiers::OCL_None;
4677 }
4678 else if (getLangOpts().ObjCAutoRefCount)
4679 LifeTime = Ty.getObjCLifetime();
4680 // MRR.
4681 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4682 LifeTime = Qualifiers::OCL_ExplicitNone;
4683 else
4684 LifeTime = Qualifiers::OCL_None;
4685 return true;
4686}
4687
Douglas Gregorbab8a962011-09-08 01:46:34 +00004688TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4689 if (!ObjCInstanceTypeDecl)
4690 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4691 getTranslationUnitDecl(),
4692 SourceLocation(),
4693 SourceLocation(),
4694 &Idents.get("instancetype"),
4695 getTrivialTypeSourceInfo(getObjCIdType()));
4696 return ObjCInstanceTypeDecl;
4697}
4698
Anders Carlsson18acd442007-10-29 06:33:42 +00004699// This returns true if a type has been typedefed to BOOL:
4700// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004701static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004702 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004703 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4704 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004705
Anders Carlssond8499822007-10-29 05:01:08 +00004706 return false;
4707}
4708
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004709/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004710/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004711CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004712 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4713 return CharUnits::Zero();
4714
Ken Dyck40775002010-01-11 17:06:35 +00004715 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004716
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004717 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004718 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004719 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004720 // Treat arrays as pointers, since that's how they're passed in.
4721 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004722 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004723 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004724}
4725
4726static inline
4727std::string charUnitsToString(const CharUnits &CU) {
4728 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004729}
4730
John McCall351762c2011-02-07 10:33:21 +00004731/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004732/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004733std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4734 std::string S;
4735
David Chisnall950a9512009-11-17 19:33:30 +00004736 const BlockDecl *Decl = Expr->getBlockDecl();
4737 QualType BlockTy =
4738 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4739 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004740 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004741 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None,
4742 BlockTy->getAs<FunctionType>()->getResultType(),
4743 S, true /*Extended*/);
4744 else
4745 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(),
4746 S);
David Chisnall950a9512009-11-17 19:33:30 +00004747 // Compute size of all parameters.
4748 // Start with computing size of a pointer in number of bytes.
4749 // FIXME: There might(should) be a better way of doing this computation!
4750 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004751 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4752 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00004753 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00004754 E = Decl->param_end(); PI != E; ++PI) {
4755 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004756 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00004757 if (sz.isZero())
4758 continue;
Ken Dyck40775002010-01-11 17:06:35 +00004759 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004760 ParmOffset += sz;
4761 }
4762 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004763 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004764 // Block pointer and offset.
4765 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004766
4767 // Argument types.
4768 ParmOffset = PtrSize;
4769 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4770 Decl->param_end(); PI != E; ++PI) {
4771 ParmVarDecl *PVDecl = *PI;
4772 QualType PType = PVDecl->getOriginalType();
4773 if (const ArrayType *AT =
4774 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4775 // Use array's original type only if it has known number of
4776 // elements.
4777 if (!isa<ConstantArrayType>(AT))
4778 PType = PVDecl->getType();
4779 } else if (PType->isFunctionType())
4780 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004781 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004782 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4783 S, true /*Extended*/);
4784 else
4785 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004786 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004787 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004788 }
John McCall351762c2011-02-07 10:33:21 +00004789
4790 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004791}
4792
Douglas Gregora9d84932011-05-27 01:19:52 +00004793bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004794 std::string& S) {
4795 // Encode result type.
4796 getObjCEncodingForType(Decl->getResultType(), S);
4797 CharUnits ParmOffset;
4798 // Compute size of all parameters.
4799 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4800 E = Decl->param_end(); PI != E; ++PI) {
4801 QualType PType = (*PI)->getType();
4802 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004803 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004804 continue;
4805
David Chisnall50e4eba2010-12-30 14:05:53 +00004806 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004807 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004808 ParmOffset += sz;
4809 }
4810 S += charUnitsToString(ParmOffset);
4811 ParmOffset = CharUnits::Zero();
4812
4813 // Argument types.
4814 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4815 E = Decl->param_end(); PI != E; ++PI) {
4816 ParmVarDecl *PVDecl = *PI;
4817 QualType PType = PVDecl->getOriginalType();
4818 if (const ArrayType *AT =
4819 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4820 // Use array's original type only if it has known number of
4821 // elements.
4822 if (!isa<ConstantArrayType>(AT))
4823 PType = PVDecl->getType();
4824 } else if (PType->isFunctionType())
4825 PType = PVDecl->getType();
4826 getObjCEncodingForType(PType, S);
4827 S += charUnitsToString(ParmOffset);
4828 ParmOffset += getObjCEncodingTypeSize(PType);
4829 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004830
4831 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004832}
4833
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004834/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4835/// method parameter or return type. If Extended, include class names and
4836/// block object types.
4837void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4838 QualType T, std::string& S,
4839 bool Extended) const {
4840 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4841 getObjCEncodingForTypeQualifier(QT, S);
4842 // Encode parameter type.
4843 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4844 true /*OutermostType*/,
4845 false /*EncodingProperty*/,
4846 false /*StructField*/,
4847 Extended /*EncodeBlockParameters*/,
4848 Extended /*EncodeClassNames*/);
4849}
4850
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004851/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004852/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004853bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004854 std::string& S,
4855 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004856 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004857 // Encode return type.
4858 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4859 Decl->getResultType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004860 // Compute size of all parameters.
4861 // Start with computing size of a pointer in number of bytes.
4862 // FIXME: There might(should) be a better way of doing this computation!
4863 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004864 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004865 // The first two arguments (self and _cmd) are pointers; account for
4866 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004867 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004868 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004869 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004870 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004871 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004872 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004873 continue;
4874
Ken Dyck40775002010-01-11 17:06:35 +00004875 assert (sz.isPositive() &&
4876 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004877 ParmOffset += sz;
4878 }
Ken Dyck40775002010-01-11 17:06:35 +00004879 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004880 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004881 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004882
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004883 // Argument types.
4884 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004885 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004886 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004887 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004888 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004889 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004890 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4891 // Use array's original type only if it has known number of
4892 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004893 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004894 PType = PVDecl->getType();
4895 } else if (PType->isFunctionType())
4896 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004897 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4898 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00004899 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004900 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004901 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004902
4903 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004904}
4905
Daniel Dunbar4932b362008-08-28 04:38:10 +00004906/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004907/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004908/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4909/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004910/// Property attributes are stored as a comma-delimited C string. The simple
4911/// attributes readonly and bycopy are encoded as single characters. The
4912/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4913/// encoded as single characters, followed by an identifier. Property types
4914/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004915/// these attributes are defined by the following enumeration:
4916/// @code
4917/// enum PropertyAttributes {
4918/// kPropertyReadOnly = 'R', // property is read-only.
4919/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4920/// kPropertyByref = '&', // property is a reference to the value last assigned
4921/// kPropertyDynamic = 'D', // property is dynamic
4922/// kPropertyGetter = 'G', // followed by getter selector name
4923/// kPropertySetter = 'S', // followed by setter selector name
4924/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00004925/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004926/// kPropertyWeak = 'W' // 'weak' property
4927/// kPropertyStrong = 'P' // property GC'able
4928/// kPropertyNonAtomic = 'N' // property non-atomic
4929/// };
4930/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00004931void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00004932 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00004933 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004934 // Collect information from the property implementation decl(s).
4935 bool Dynamic = false;
4936 ObjCPropertyImplDecl *SynthesizePID = 0;
4937
4938 // FIXME: Duplicated code due to poor abstraction.
4939 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00004940 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00004941 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4942 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004943 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004944 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004945 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004946 if (PID->getPropertyDecl() == PD) {
4947 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4948 Dynamic = true;
4949 } else {
4950 SynthesizePID = PID;
4951 }
4952 }
4953 }
4954 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00004955 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004956 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004957 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004958 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004959 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004960 if (PID->getPropertyDecl() == PD) {
4961 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4962 Dynamic = true;
4963 } else {
4964 SynthesizePID = PID;
4965 }
4966 }
Mike Stump11289f42009-09-09 15:08:12 +00004967 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00004968 }
4969 }
4970
4971 // FIXME: This is not very efficient.
4972 S = "T";
4973
4974 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004975 // GCC has some special rules regarding encoding of properties which
4976 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00004977 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004978 true /* outermost type */,
4979 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004980
4981 if (PD->isReadOnly()) {
4982 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00004983 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
4984 S += ",C";
4985 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
4986 S += ",&";
Daniel Dunbar4932b362008-08-28 04:38:10 +00004987 } else {
4988 switch (PD->getSetterKind()) {
4989 case ObjCPropertyDecl::Assign: break;
4990 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00004991 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00004992 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004993 }
4994 }
4995
4996 // It really isn't clear at all what this means, since properties
4997 // are "dynamic by default".
4998 if (Dynamic)
4999 S += ",D";
5000
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005001 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5002 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00005003
Daniel Dunbar4932b362008-08-28 04:38:10 +00005004 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5005 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00005006 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005007 }
5008
5009 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5010 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00005011 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005012 }
5013
5014 if (SynthesizePID) {
5015 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5016 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00005017 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005018 }
5019
5020 // FIXME: OBJCGC: weak & strong
5021}
5022
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005023/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00005024/// Another legacy compatibility encoding: 32-bit longs are encoded as
5025/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005026/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5027///
5028void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00005029 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00005030 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00005031 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005032 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00005033 else
Jay Foad39c79802011-01-12 09:06:06 +00005034 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005035 PointeeTy = IntTy;
5036 }
5037 }
5038}
5039
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005040void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00005041 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005042 // We follow the behavior of gcc, expanding structures which are
5043 // directly pointed to, and expanding embedded structures. Note that
5044 // these rules are sufficient to prevent recursive encoding of the
5045 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00005046 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00005047 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005048}
5049
John McCall393a78d2012-12-20 02:45:14 +00005050static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5051 BuiltinType::Kind kind) {
5052 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005053 case BuiltinType::Void: return 'v';
5054 case BuiltinType::Bool: return 'B';
5055 case BuiltinType::Char_U:
5056 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00005057 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00005058 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00005059 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00005060 case BuiltinType::UInt: return 'I';
5061 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00005062 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005063 case BuiltinType::UInt128: return 'T';
5064 case BuiltinType::ULongLong: return 'Q';
5065 case BuiltinType::Char_S:
5066 case BuiltinType::SChar: return 'c';
5067 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00005068 case BuiltinType::WChar_S:
5069 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00005070 case BuiltinType::Int: return 'i';
5071 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00005072 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005073 case BuiltinType::LongLong: return 'q';
5074 case BuiltinType::Int128: return 't';
5075 case BuiltinType::Float: return 'f';
5076 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00005077 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00005078 case BuiltinType::NullPtr: return '*'; // like char*
5079
5080 case BuiltinType::Half:
5081 // FIXME: potentially need @encodes for these!
5082 return ' ';
5083
5084 case BuiltinType::ObjCId:
5085 case BuiltinType::ObjCClass:
5086 case BuiltinType::ObjCSel:
5087 llvm_unreachable("@encoding ObjC primitive type");
5088
5089 // OpenCL and placeholder types don't need @encodings.
5090 case BuiltinType::OCLImage1d:
5091 case BuiltinType::OCLImage1dArray:
5092 case BuiltinType::OCLImage1dBuffer:
5093 case BuiltinType::OCLImage2d:
5094 case BuiltinType::OCLImage2dArray:
5095 case BuiltinType::OCLImage3d:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005096 case BuiltinType::OCLEvent:
Guy Benyei61054192013-02-07 10:55:47 +00005097 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00005098 case BuiltinType::Dependent:
5099#define BUILTIN_TYPE(KIND, ID)
5100#define PLACEHOLDER_TYPE(KIND, ID) \
5101 case BuiltinType::KIND:
5102#include "clang/AST/BuiltinTypes.def"
5103 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00005104 }
David Blaikie5a6a0202013-01-09 17:48:41 +00005105 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00005106}
5107
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005108static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5109 EnumDecl *Enum = ET->getDecl();
5110
5111 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5112 if (!Enum->isFixed())
5113 return 'i';
5114
5115 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00005116 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5117 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005118}
5119
Jay Foad39c79802011-01-12 09:06:06 +00005120static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00005121 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00005122 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005123 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00005124 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5125 // The GNU runtime requires more information; bitfields are encoded as b,
5126 // then the offset (in bits) of the first element, then the type of the
5127 // bitfield, then the size in bits. For example, in this structure:
5128 //
5129 // struct
5130 // {
5131 // int integer;
5132 // int flags:2;
5133 // };
5134 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5135 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5136 // information is not especially sensible, but we're stuck with it for
5137 // compatibility with GCC, although providing it breaks anything that
5138 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00005139 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005140 const RecordDecl *RD = FD->getParent();
5141 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00005142 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005143 if (const EnumType *ET = T->getAs<EnumType>())
5144 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00005145 else {
5146 const BuiltinType *BT = T->castAs<BuiltinType>();
5147 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5148 }
David Chisnallb190a2c2010-06-04 01:10:52 +00005149 }
Richard Smithcaf33902011-10-10 18:28:20 +00005150 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005151}
5152
Daniel Dunbar07d07852009-10-18 21:17:35 +00005153// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005154void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5155 bool ExpandPointedToStructures,
5156 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00005157 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005158 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005159 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005160 bool StructField,
5161 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005162 bool EncodeClassNames,
5163 bool EncodePointerToObjCTypedef) const {
John McCall393a78d2012-12-20 02:45:14 +00005164 CanQualType CT = getCanonicalType(T);
5165 switch (CT->getTypeClass()) {
5166 case Type::Builtin:
5167 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00005168 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00005169 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00005170 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5171 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5172 else
5173 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00005174 return;
Mike Stump11289f42009-09-09 15:08:12 +00005175
John McCall393a78d2012-12-20 02:45:14 +00005176 case Type::Complex: {
5177 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00005178 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00005179 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00005180 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005181 return;
5182 }
John McCall393a78d2012-12-20 02:45:14 +00005183
5184 case Type::Atomic: {
5185 const AtomicType *AT = T->castAs<AtomicType>();
5186 S += 'A';
5187 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, 0,
5188 false, false);
5189 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00005190 }
John McCall393a78d2012-12-20 02:45:14 +00005191
5192 // encoding for pointer or reference types.
5193 case Type::Pointer:
5194 case Type::LValueReference:
5195 case Type::RValueReference: {
5196 QualType PointeeTy;
5197 if (isa<PointerType>(CT)) {
5198 const PointerType *PT = T->castAs<PointerType>();
5199 if (PT->isObjCSelType()) {
5200 S += ':';
5201 return;
5202 }
5203 PointeeTy = PT->getPointeeType();
5204 } else {
5205 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5206 }
5207
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005208 bool isReadOnly = false;
5209 // For historical/compatibility reasons, the read-only qualifier of the
5210 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5211 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00005212 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00005213 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005214 if (OutermostType && T.isConstQualified()) {
5215 isReadOnly = true;
5216 S += 'r';
5217 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00005218 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005219 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005220 while (P->getAs<PointerType>())
5221 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005222 if (P.isConstQualified()) {
5223 isReadOnly = true;
5224 S += 'r';
5225 }
5226 }
5227 if (isReadOnly) {
5228 // Another legacy compatibility encoding. Some ObjC qualifier and type
5229 // combinations need to be rearranged.
5230 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005231 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00005232 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005233 }
Mike Stump11289f42009-09-09 15:08:12 +00005234
Anders Carlssond8499822007-10-29 05:01:08 +00005235 if (PointeeTy->isCharType()) {
5236 // char pointer types should be encoded as '*' unless it is a
5237 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00005238 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00005239 S += '*';
5240 return;
5241 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005242 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00005243 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5244 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5245 S += '#';
5246 return;
5247 }
5248 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5249 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5250 S += '@';
5251 return;
5252 }
5253 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00005254 }
Anders Carlssond8499822007-10-29 05:01:08 +00005255 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005256 getLegacyIntegralTypeEncoding(PointeeTy);
5257
Mike Stump11289f42009-09-09 15:08:12 +00005258 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005259 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005260 return;
5261 }
John McCall393a78d2012-12-20 02:45:14 +00005262
5263 case Type::ConstantArray:
5264 case Type::IncompleteArray:
5265 case Type::VariableArray: {
5266 const ArrayType *AT = cast<ArrayType>(CT);
5267
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005268 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005269 // Incomplete arrays are encoded as a pointer to the array element.
5270 S += '^';
5271
Mike Stump11289f42009-09-09 15:08:12 +00005272 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005273 false, ExpandStructures, FD);
5274 } else {
5275 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00005276
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00005277 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5278 S += llvm::utostr(CAT->getSize().getZExtValue());
5279 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005280 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005281 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5282 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00005283 S += '0';
5284 }
Mike Stump11289f42009-09-09 15:08:12 +00005285
5286 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005287 false, ExpandStructures, FD);
5288 S += ']';
5289 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005290 return;
5291 }
Mike Stump11289f42009-09-09 15:08:12 +00005292
John McCall393a78d2012-12-20 02:45:14 +00005293 case Type::FunctionNoProto:
5294 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00005295 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005296 return;
Mike Stump11289f42009-09-09 15:08:12 +00005297
John McCall393a78d2012-12-20 02:45:14 +00005298 case Type::Record: {
5299 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005300 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00005301 // Anonymous structures print as '?'
5302 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5303 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005304 if (ClassTemplateSpecializationDecl *Spec
5305 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5306 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00005307 llvm::raw_string_ostream OS(S);
5308 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005309 TemplateArgs.data(),
5310 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00005311 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005312 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00005313 } else {
5314 S += '?';
5315 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00005316 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005317 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005318 if (!RDecl->isUnion()) {
5319 getObjCEncodingForStructureImpl(RDecl, S, FD);
5320 } else {
5321 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5322 FieldEnd = RDecl->field_end();
5323 Field != FieldEnd; ++Field) {
5324 if (FD) {
5325 S += '"';
5326 S += Field->getNameAsString();
5327 S += '"';
5328 }
Mike Stump11289f42009-09-09 15:08:12 +00005329
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005330 // Special case bit-fields.
5331 if (Field->isBitField()) {
5332 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie40ed2972012-06-06 20:45:41 +00005333 *Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005334 } else {
5335 QualType qt = Field->getType();
5336 getLegacyIntegralTypeEncoding(qt);
5337 getObjCEncodingForTypeImpl(qt, S, false, true,
5338 FD, /*OutermostType*/false,
5339 /*EncodingProperty*/false,
5340 /*StructField*/true);
5341 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005342 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005343 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00005344 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005345 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005346 return;
5347 }
Mike Stump11289f42009-09-09 15:08:12 +00005348
John McCall393a78d2012-12-20 02:45:14 +00005349 case Type::BlockPointer: {
5350 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00005351 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005352 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00005353 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005354
5355 S += '<';
5356 // Block return type
5357 getObjCEncodingForTypeImpl(FT->getResultType(), S,
5358 ExpandPointedToStructures, ExpandStructures,
5359 FD,
5360 false /* OutermostType */,
5361 EncodingProperty,
5362 false /* StructField */,
5363 EncodeBlockParameters,
5364 EncodeClassNames);
5365 // Block self
5366 S += "@?";
5367 // Block parameters
5368 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
5369 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
5370 E = FPT->arg_type_end(); I && (I != E); ++I) {
5371 getObjCEncodingForTypeImpl(*I, S,
5372 ExpandPointedToStructures,
5373 ExpandStructures,
5374 FD,
5375 false /* OutermostType */,
5376 EncodingProperty,
5377 false /* StructField */,
5378 EncodeBlockParameters,
5379 EncodeClassNames);
5380 }
5381 }
5382 S += '>';
5383 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005384 return;
5385 }
Mike Stump11289f42009-09-09 15:08:12 +00005386
John McCall393a78d2012-12-20 02:45:14 +00005387 case Type::ObjCObject:
5388 case Type::ObjCInterface: {
5389 // Ignore protocol qualifiers when mangling at this level.
5390 T = T->castAs<ObjCObjectType>()->getBaseType();
John McCall8b07ec22010-05-15 11:32:37 +00005391
John McCall393a78d2012-12-20 02:45:14 +00005392 // The assumption seems to be that this assert will succeed
5393 // because nested levels will have filtered out 'id' and 'Class'.
5394 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005395 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00005396 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005397 S += '{';
5398 const IdentifierInfo *II = OI->getIdentifier();
5399 S += II->getName();
5400 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005401 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005402 DeepCollectObjCIvars(OI, true, Ivars);
5403 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005404 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005405 if (Field->isBitField())
5406 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005407 else
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005408 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5409 false, false, false, false, false,
5410 EncodePointerToObjCTypedef);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005411 }
5412 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005413 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005414 }
Mike Stump11289f42009-09-09 15:08:12 +00005415
John McCall393a78d2012-12-20 02:45:14 +00005416 case Type::ObjCObjectPointer: {
5417 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005418 if (OPT->isObjCIdType()) {
5419 S += '@';
5420 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005421 }
Mike Stump11289f42009-09-09 15:08:12 +00005422
Steve Narofff0c86112009-10-28 22:03:49 +00005423 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5424 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5425 // Since this is a binary compatibility issue, need to consult with runtime
5426 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005427 S += '#';
5428 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005429 }
Mike Stump11289f42009-09-09 15:08:12 +00005430
Chris Lattnere7cabb92009-07-13 00:10:46 +00005431 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005432 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005433 ExpandPointedToStructures,
5434 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005435 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005436 // Note that we do extended encoding of protocol qualifer list
5437 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005438 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00005439 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5440 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005441 S += '<';
5442 S += (*I)->getNameAsString();
5443 S += '>';
5444 }
5445 S += '"';
5446 }
5447 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005448 }
Mike Stump11289f42009-09-09 15:08:12 +00005449
Chris Lattnere7cabb92009-07-13 00:10:46 +00005450 QualType PointeeTy = OPT->getPointeeType();
5451 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005452 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5453 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005454 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005455 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005456 // {...};
5457 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005458 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00005459 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005460 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5461 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5462 DeepCollectObjCIvars(OI, true, Ivars);
5463 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5464 if (cast<FieldDecl>(Ivars[i]) == FD) {
5465 S += '{';
5466 S += OI->getIdentifier()->getName();
5467 S += '}';
5468 return;
5469 }
5470 }
5471 }
Mike Stump11289f42009-09-09 15:08:12 +00005472 getObjCEncodingForTypeImpl(PointeeTy, S,
5473 false, ExpandPointedToStructures,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005474 NULL,
5475 false, false, false, false, false,
5476 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005477 return;
5478 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005479
5480 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005481 if (OPT->getInterfaceDecl() &&
5482 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005483 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00005484 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00005485 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5486 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005487 S += '<';
5488 S += (*I)->getNameAsString();
5489 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005490 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005491 S += '"';
5492 }
5493 return;
5494 }
Mike Stump11289f42009-09-09 15:08:12 +00005495
John McCalla9e6e8d2010-05-17 23:56:34 +00005496 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00005497 // FIXME: we shoul do better than that. 'M' is available.
5498 case Type::MemberPointer:
John McCalla9e6e8d2010-05-17 23:56:34 +00005499 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005500
John McCall393a78d2012-12-20 02:45:14 +00005501 case Type::Vector:
5502 case Type::ExtVector:
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005503 // This matches gcc's encoding, even though technically it is
5504 // insufficient.
5505 // FIXME. We should do a better job than gcc.
5506 return;
John McCall393a78d2012-12-20 02:45:14 +00005507
Richard Smith27d807c2013-04-30 13:56:41 +00005508 case Type::Auto:
5509 // We could see an undeduced auto type here during error recovery.
5510 // Just ignore it.
5511 return;
5512
John McCall393a78d2012-12-20 02:45:14 +00005513#define ABSTRACT_TYPE(KIND, BASE)
5514#define TYPE(KIND, BASE)
5515#define DEPENDENT_TYPE(KIND, BASE) \
5516 case Type::KIND:
5517#define NON_CANONICAL_TYPE(KIND, BASE) \
5518 case Type::KIND:
5519#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5520 case Type::KIND:
5521#include "clang/AST/TypeNodes.def"
5522 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005523 }
John McCall393a78d2012-12-20 02:45:14 +00005524 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00005525}
5526
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005527void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5528 std::string &S,
5529 const FieldDecl *FD,
5530 bool includeVBases) const {
5531 assert(RDecl && "Expected non-null RecordDecl");
5532 assert(!RDecl->isUnion() && "Should not be called for unions");
5533 if (!RDecl->getDefinition())
5534 return;
5535
5536 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5537 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5538 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5539
5540 if (CXXRec) {
5541 for (CXXRecordDecl::base_class_iterator
5542 BI = CXXRec->bases_begin(),
5543 BE = CXXRec->bases_end(); BI != BE; ++BI) {
5544 if (!BI->isVirtual()) {
5545 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005546 if (base->isEmpty())
5547 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005548 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005549 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5550 std::make_pair(offs, base));
5551 }
5552 }
5553 }
5554
5555 unsigned i = 0;
5556 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5557 FieldEnd = RDecl->field_end();
5558 Field != FieldEnd; ++Field, ++i) {
5559 uint64_t offs = layout.getFieldOffset(i);
5560 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie40ed2972012-06-06 20:45:41 +00005561 std::make_pair(offs, *Field));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005562 }
5563
5564 if (CXXRec && includeVBases) {
5565 for (CXXRecordDecl::base_class_iterator
5566 BI = CXXRec->vbases_begin(),
5567 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
5568 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005569 if (base->isEmpty())
5570 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005571 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00005572 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
5573 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00005574 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5575 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005576 }
5577 }
5578
5579 CharUnits size;
5580 if (CXXRec) {
5581 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5582 } else {
5583 size = layout.getSize();
5584 }
5585
5586 uint64_t CurOffs = 0;
5587 std::multimap<uint64_t, NamedDecl *>::iterator
5588 CurLayObj = FieldOrBaseOffsets.begin();
5589
Douglas Gregorf5d6c742012-04-27 22:30:01 +00005590 if (CXXRec && CXXRec->isDynamicClass() &&
5591 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005592 if (FD) {
5593 S += "\"_vptr$";
5594 std::string recname = CXXRec->getNameAsString();
5595 if (recname.empty()) recname = "?";
5596 S += recname;
5597 S += '"';
5598 }
5599 S += "^^?";
5600 CurOffs += getTypeSize(VoidPtrTy);
5601 }
5602
5603 if (!RDecl->hasFlexibleArrayMember()) {
5604 // Mark the end of the structure.
5605 uint64_t offs = toBits(size);
5606 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5607 std::make_pair(offs, (NamedDecl*)0));
5608 }
5609
5610 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5611 assert(CurOffs <= CurLayObj->first);
5612
5613 if (CurOffs < CurLayObj->first) {
5614 uint64_t padding = CurLayObj->first - CurOffs;
5615 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5616 // packing/alignment of members is different that normal, in which case
5617 // the encoding will be out-of-sync with the real layout.
5618 // If the runtime switches to just consider the size of types without
5619 // taking into account alignment, we could make padding explicit in the
5620 // encoding (e.g. using arrays of chars). The encoding strings would be
5621 // longer then though.
5622 CurOffs += padding;
5623 }
5624
5625 NamedDecl *dcl = CurLayObj->second;
5626 if (dcl == 0)
5627 break; // reached end of structure.
5628
5629 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5630 // We expand the bases without their virtual bases since those are going
5631 // in the initial structure. Note that this differs from gcc which
5632 // expands virtual bases each time one is encountered in the hierarchy,
5633 // making the encoding type bigger than it really is.
5634 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005635 assert(!base->isEmpty());
5636 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005637 } else {
5638 FieldDecl *field = cast<FieldDecl>(dcl);
5639 if (FD) {
5640 S += '"';
5641 S += field->getNameAsString();
5642 S += '"';
5643 }
5644
5645 if (field->isBitField()) {
5646 EncodeBitField(this, S, field->getType(), field);
Richard Smithcaf33902011-10-10 18:28:20 +00005647 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005648 } else {
5649 QualType qt = field->getType();
5650 getLegacyIntegralTypeEncoding(qt);
5651 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5652 /*OutermostType*/false,
5653 /*EncodingProperty*/false,
5654 /*StructField*/true);
5655 CurOffs += getTypeSize(field->getType());
5656 }
5657 }
5658 }
5659}
5660
Mike Stump11289f42009-09-09 15:08:12 +00005661void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005662 std::string& S) const {
5663 if (QT & Decl::OBJC_TQ_In)
5664 S += 'n';
5665 if (QT & Decl::OBJC_TQ_Inout)
5666 S += 'N';
5667 if (QT & Decl::OBJC_TQ_Out)
5668 S += 'o';
5669 if (QT & Decl::OBJC_TQ_Bycopy)
5670 S += 'O';
5671 if (QT & Decl::OBJC_TQ_Byref)
5672 S += 'R';
5673 if (QT & Decl::OBJC_TQ_Oneway)
5674 S += 'V';
5675}
5676
Douglas Gregor3ea72692011-08-12 05:46:01 +00005677TypedefDecl *ASTContext::getObjCIdDecl() const {
5678 if (!ObjCIdDecl) {
5679 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5680 T = getObjCObjectPointerType(T);
5681 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
5682 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5683 getTranslationUnitDecl(),
5684 SourceLocation(), SourceLocation(),
5685 &Idents.get("id"), IdInfo);
5686 }
5687
5688 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00005689}
5690
Douglas Gregor52e02802011-08-12 06:17:30 +00005691TypedefDecl *ASTContext::getObjCSelDecl() const {
5692 if (!ObjCSelDecl) {
5693 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5694 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5695 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5696 getTranslationUnitDecl(),
5697 SourceLocation(), SourceLocation(),
5698 &Idents.get("SEL"), SelInfo);
5699 }
5700 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00005701}
5702
Douglas Gregor0a586182011-08-12 05:59:41 +00005703TypedefDecl *ASTContext::getObjCClassDecl() const {
5704 if (!ObjCClassDecl) {
5705 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5706 T = getObjCObjectPointerType(T);
5707 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5708 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5709 getTranslationUnitDecl(),
5710 SourceLocation(), SourceLocation(),
5711 &Idents.get("Class"), ClassInfo);
5712 }
5713
5714 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00005715}
5716
Douglas Gregord53ae832012-01-17 18:09:05 +00005717ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5718 if (!ObjCProtocolClassDecl) {
5719 ObjCProtocolClassDecl
5720 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5721 SourceLocation(),
5722 &Idents.get("Protocol"),
5723 /*PrevDecl=*/0,
5724 SourceLocation(), true);
5725 }
5726
5727 return ObjCProtocolClassDecl;
5728}
5729
Meador Inge5d3fb222012-06-16 03:34:49 +00005730//===----------------------------------------------------------------------===//
5731// __builtin_va_list Construction Functions
5732//===----------------------------------------------------------------------===//
5733
5734static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5735 // typedef char* __builtin_va_list;
5736 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5737 TypeSourceInfo *TInfo
5738 = Context->getTrivialTypeSourceInfo(CharPtrType);
5739
5740 TypedefDecl *VaListTypeDecl
5741 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5742 Context->getTranslationUnitDecl(),
5743 SourceLocation(), SourceLocation(),
5744 &Context->Idents.get("__builtin_va_list"),
5745 TInfo);
5746 return VaListTypeDecl;
5747}
5748
5749static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5750 // typedef void* __builtin_va_list;
5751 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5752 TypeSourceInfo *TInfo
5753 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5754
5755 TypedefDecl *VaListTypeDecl
5756 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5757 Context->getTranslationUnitDecl(),
5758 SourceLocation(), SourceLocation(),
5759 &Context->Idents.get("__builtin_va_list"),
5760 TInfo);
5761 return VaListTypeDecl;
5762}
5763
Tim Northover9bb857a2013-01-31 12:13:10 +00005764static TypedefDecl *
5765CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
5766 RecordDecl *VaListTagDecl;
5767 if (Context->getLangOpts().CPlusPlus) {
5768 // namespace std { struct __va_list {
5769 NamespaceDecl *NS;
5770 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5771 Context->getTranslationUnitDecl(),
5772 /*Inline*/false, SourceLocation(),
5773 SourceLocation(), &Context->Idents.get("std"),
5774 /*PrevDecl*/0);
5775
5776 VaListTagDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5777 Context->getTranslationUnitDecl(),
5778 SourceLocation(), SourceLocation(),
5779 &Context->Idents.get("__va_list"));
5780 VaListTagDecl->setDeclContext(NS);
5781 } else {
5782 // struct __va_list
5783 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5784 Context->getTranslationUnitDecl(),
5785 &Context->Idents.get("__va_list"));
5786 }
5787
5788 VaListTagDecl->startDefinition();
5789
5790 const size_t NumFields = 5;
5791 QualType FieldTypes[NumFields];
5792 const char *FieldNames[NumFields];
5793
5794 // void *__stack;
5795 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
5796 FieldNames[0] = "__stack";
5797
5798 // void *__gr_top;
5799 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
5800 FieldNames[1] = "__gr_top";
5801
5802 // void *__vr_top;
5803 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5804 FieldNames[2] = "__vr_top";
5805
5806 // int __gr_offs;
5807 FieldTypes[3] = Context->IntTy;
5808 FieldNames[3] = "__gr_offs";
5809
5810 // int __vr_offs;
5811 FieldTypes[4] = Context->IntTy;
5812 FieldNames[4] = "__vr_offs";
5813
5814 // Create fields
5815 for (unsigned i = 0; i < NumFields; ++i) {
5816 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5817 VaListTagDecl,
5818 SourceLocation(),
5819 SourceLocation(),
5820 &Context->Idents.get(FieldNames[i]),
5821 FieldTypes[i], /*TInfo=*/0,
5822 /*BitWidth=*/0,
5823 /*Mutable=*/false,
5824 ICIS_NoInit);
5825 Field->setAccess(AS_public);
5826 VaListTagDecl->addDecl(Field);
5827 }
5828 VaListTagDecl->completeDefinition();
5829 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5830 Context->VaListTagTy = VaListTagType;
5831
5832 // } __builtin_va_list;
5833 TypedefDecl *VaListTypedefDecl
5834 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5835 Context->getTranslationUnitDecl(),
5836 SourceLocation(), SourceLocation(),
5837 &Context->Idents.get("__builtin_va_list"),
5838 Context->getTrivialTypeSourceInfo(VaListTagType));
5839
5840 return VaListTypedefDecl;
5841}
5842
Meador Inge5d3fb222012-06-16 03:34:49 +00005843static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5844 // typedef struct __va_list_tag {
5845 RecordDecl *VaListTagDecl;
5846
5847 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5848 Context->getTranslationUnitDecl(),
5849 &Context->Idents.get("__va_list_tag"));
5850 VaListTagDecl->startDefinition();
5851
5852 const size_t NumFields = 5;
5853 QualType FieldTypes[NumFields];
5854 const char *FieldNames[NumFields];
5855
5856 // unsigned char gpr;
5857 FieldTypes[0] = Context->UnsignedCharTy;
5858 FieldNames[0] = "gpr";
5859
5860 // unsigned char fpr;
5861 FieldTypes[1] = Context->UnsignedCharTy;
5862 FieldNames[1] = "fpr";
5863
5864 // unsigned short reserved;
5865 FieldTypes[2] = Context->UnsignedShortTy;
5866 FieldNames[2] = "reserved";
5867
5868 // void* overflow_arg_area;
5869 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5870 FieldNames[3] = "overflow_arg_area";
5871
5872 // void* reg_save_area;
5873 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5874 FieldNames[4] = "reg_save_area";
5875
5876 // Create fields
5877 for (unsigned i = 0; i < NumFields; ++i) {
5878 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5879 SourceLocation(),
5880 SourceLocation(),
5881 &Context->Idents.get(FieldNames[i]),
5882 FieldTypes[i], /*TInfo=*/0,
5883 /*BitWidth=*/0,
5884 /*Mutable=*/false,
5885 ICIS_NoInit);
5886 Field->setAccess(AS_public);
5887 VaListTagDecl->addDecl(Field);
5888 }
5889 VaListTagDecl->completeDefinition();
5890 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005891 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005892
5893 // } __va_list_tag;
5894 TypedefDecl *VaListTagTypedefDecl
5895 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5896 Context->getTranslationUnitDecl(),
5897 SourceLocation(), SourceLocation(),
5898 &Context->Idents.get("__va_list_tag"),
5899 Context->getTrivialTypeSourceInfo(VaListTagType));
5900 QualType VaListTagTypedefType =
5901 Context->getTypedefType(VaListTagTypedefDecl);
5902
5903 // typedef __va_list_tag __builtin_va_list[1];
5904 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5905 QualType VaListTagArrayType
5906 = Context->getConstantArrayType(VaListTagTypedefType,
5907 Size, ArrayType::Normal, 0);
5908 TypeSourceInfo *TInfo
5909 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5910 TypedefDecl *VaListTypedefDecl
5911 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5912 Context->getTranslationUnitDecl(),
5913 SourceLocation(), SourceLocation(),
5914 &Context->Idents.get("__builtin_va_list"),
5915 TInfo);
5916
5917 return VaListTypedefDecl;
5918}
5919
5920static TypedefDecl *
5921CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5922 // typedef struct __va_list_tag {
5923 RecordDecl *VaListTagDecl;
5924 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5925 Context->getTranslationUnitDecl(),
5926 &Context->Idents.get("__va_list_tag"));
5927 VaListTagDecl->startDefinition();
5928
5929 const size_t NumFields = 4;
5930 QualType FieldTypes[NumFields];
5931 const char *FieldNames[NumFields];
5932
5933 // unsigned gp_offset;
5934 FieldTypes[0] = Context->UnsignedIntTy;
5935 FieldNames[0] = "gp_offset";
5936
5937 // unsigned fp_offset;
5938 FieldTypes[1] = Context->UnsignedIntTy;
5939 FieldNames[1] = "fp_offset";
5940
5941 // void* overflow_arg_area;
5942 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5943 FieldNames[2] = "overflow_arg_area";
5944
5945 // void* reg_save_area;
5946 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5947 FieldNames[3] = "reg_save_area";
5948
5949 // Create fields
5950 for (unsigned i = 0; i < NumFields; ++i) {
5951 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5952 VaListTagDecl,
5953 SourceLocation(),
5954 SourceLocation(),
5955 &Context->Idents.get(FieldNames[i]),
5956 FieldTypes[i], /*TInfo=*/0,
5957 /*BitWidth=*/0,
5958 /*Mutable=*/false,
5959 ICIS_NoInit);
5960 Field->setAccess(AS_public);
5961 VaListTagDecl->addDecl(Field);
5962 }
5963 VaListTagDecl->completeDefinition();
5964 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005965 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005966
5967 // } __va_list_tag;
5968 TypedefDecl *VaListTagTypedefDecl
5969 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5970 Context->getTranslationUnitDecl(),
5971 SourceLocation(), SourceLocation(),
5972 &Context->Idents.get("__va_list_tag"),
5973 Context->getTrivialTypeSourceInfo(VaListTagType));
5974 QualType VaListTagTypedefType =
5975 Context->getTypedefType(VaListTagTypedefDecl);
5976
5977 // typedef __va_list_tag __builtin_va_list[1];
5978 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5979 QualType VaListTagArrayType
5980 = Context->getConstantArrayType(VaListTagTypedefType,
5981 Size, ArrayType::Normal,0);
5982 TypeSourceInfo *TInfo
5983 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5984 TypedefDecl *VaListTypedefDecl
5985 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5986 Context->getTranslationUnitDecl(),
5987 SourceLocation(), SourceLocation(),
5988 &Context->Idents.get("__builtin_va_list"),
5989 TInfo);
5990
5991 return VaListTypedefDecl;
5992}
5993
5994static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5995 // typedef int __builtin_va_list[4];
5996 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5997 QualType IntArrayType
5998 = Context->getConstantArrayType(Context->IntTy,
5999 Size, ArrayType::Normal, 0);
6000 TypedefDecl *VaListTypedefDecl
6001 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6002 Context->getTranslationUnitDecl(),
6003 SourceLocation(), SourceLocation(),
6004 &Context->Idents.get("__builtin_va_list"),
6005 Context->getTrivialTypeSourceInfo(IntArrayType));
6006
6007 return VaListTypedefDecl;
6008}
6009
Logan Chien57086ce2012-10-10 06:56:20 +00006010static TypedefDecl *
6011CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
6012 RecordDecl *VaListDecl;
6013 if (Context->getLangOpts().CPlusPlus) {
6014 // namespace std { struct __va_list {
6015 NamespaceDecl *NS;
6016 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6017 Context->getTranslationUnitDecl(),
6018 /*Inline*/false, SourceLocation(),
6019 SourceLocation(), &Context->Idents.get("std"),
6020 /*PrevDecl*/0);
6021
6022 VaListDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
6023 Context->getTranslationUnitDecl(),
6024 SourceLocation(), SourceLocation(),
6025 &Context->Idents.get("__va_list"));
6026
6027 VaListDecl->setDeclContext(NS);
6028
6029 } else {
6030 // struct __va_list {
6031 VaListDecl = CreateRecordDecl(*Context, TTK_Struct,
6032 Context->getTranslationUnitDecl(),
6033 &Context->Idents.get("__va_list"));
6034 }
6035
6036 VaListDecl->startDefinition();
6037
6038 // void * __ap;
6039 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6040 VaListDecl,
6041 SourceLocation(),
6042 SourceLocation(),
6043 &Context->Idents.get("__ap"),
6044 Context->getPointerType(Context->VoidTy),
6045 /*TInfo=*/0,
6046 /*BitWidth=*/0,
6047 /*Mutable=*/false,
6048 ICIS_NoInit);
6049 Field->setAccess(AS_public);
6050 VaListDecl->addDecl(Field);
6051
6052 // };
6053 VaListDecl->completeDefinition();
6054
6055 // typedef struct __va_list __builtin_va_list;
6056 TypeSourceInfo *TInfo
6057 = Context->getTrivialTypeSourceInfo(Context->getRecordType(VaListDecl));
6058
6059 TypedefDecl *VaListTypeDecl
6060 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6061 Context->getTranslationUnitDecl(),
6062 SourceLocation(), SourceLocation(),
6063 &Context->Idents.get("__builtin_va_list"),
6064 TInfo);
6065
6066 return VaListTypeDecl;
6067}
6068
Ulrich Weigand47445072013-05-06 16:26:41 +00006069static TypedefDecl *
6070CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
6071 // typedef struct __va_list_tag {
6072 RecordDecl *VaListTagDecl;
6073 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
6074 Context->getTranslationUnitDecl(),
6075 &Context->Idents.get("__va_list_tag"));
6076 VaListTagDecl->startDefinition();
6077
6078 const size_t NumFields = 4;
6079 QualType FieldTypes[NumFields];
6080 const char *FieldNames[NumFields];
6081
6082 // long __gpr;
6083 FieldTypes[0] = Context->LongTy;
6084 FieldNames[0] = "__gpr";
6085
6086 // long __fpr;
6087 FieldTypes[1] = Context->LongTy;
6088 FieldNames[1] = "__fpr";
6089
6090 // void *__overflow_arg_area;
6091 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6092 FieldNames[2] = "__overflow_arg_area";
6093
6094 // void *__reg_save_area;
6095 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6096 FieldNames[3] = "__reg_save_area";
6097
6098 // Create fields
6099 for (unsigned i = 0; i < NumFields; ++i) {
6100 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6101 VaListTagDecl,
6102 SourceLocation(),
6103 SourceLocation(),
6104 &Context->Idents.get(FieldNames[i]),
6105 FieldTypes[i], /*TInfo=*/0,
6106 /*BitWidth=*/0,
6107 /*Mutable=*/false,
6108 ICIS_NoInit);
6109 Field->setAccess(AS_public);
6110 VaListTagDecl->addDecl(Field);
6111 }
6112 VaListTagDecl->completeDefinition();
6113 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6114 Context->VaListTagTy = VaListTagType;
6115
6116 // } __va_list_tag;
6117 TypedefDecl *VaListTagTypedefDecl
6118 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6119 Context->getTranslationUnitDecl(),
6120 SourceLocation(), SourceLocation(),
6121 &Context->Idents.get("__va_list_tag"),
6122 Context->getTrivialTypeSourceInfo(VaListTagType));
6123 QualType VaListTagTypedefType =
6124 Context->getTypedefType(VaListTagTypedefDecl);
6125
6126 // typedef __va_list_tag __builtin_va_list[1];
6127 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6128 QualType VaListTagArrayType
6129 = Context->getConstantArrayType(VaListTagTypedefType,
6130 Size, ArrayType::Normal,0);
6131 TypeSourceInfo *TInfo
6132 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
6133 TypedefDecl *VaListTypedefDecl
6134 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6135 Context->getTranslationUnitDecl(),
6136 SourceLocation(), SourceLocation(),
6137 &Context->Idents.get("__builtin_va_list"),
6138 TInfo);
6139
6140 return VaListTypedefDecl;
6141}
6142
Meador Inge5d3fb222012-06-16 03:34:49 +00006143static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6144 TargetInfo::BuiltinVaListKind Kind) {
6145 switch (Kind) {
6146 case TargetInfo::CharPtrBuiltinVaList:
6147 return CreateCharPtrBuiltinVaListDecl(Context);
6148 case TargetInfo::VoidPtrBuiltinVaList:
6149 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00006150 case TargetInfo::AArch64ABIBuiltinVaList:
6151 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006152 case TargetInfo::PowerABIBuiltinVaList:
6153 return CreatePowerABIBuiltinVaListDecl(Context);
6154 case TargetInfo::X86_64ABIBuiltinVaList:
6155 return CreateX86_64ABIBuiltinVaListDecl(Context);
6156 case TargetInfo::PNaClABIBuiltinVaList:
6157 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00006158 case TargetInfo::AAPCSABIBuiltinVaList:
6159 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00006160 case TargetInfo::SystemZBuiltinVaList:
6161 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006162 }
6163
6164 llvm_unreachable("Unhandled __builtin_va_list type kind");
6165}
6166
6167TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
6168 if (!BuiltinVaListDecl)
6169 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
6170
6171 return BuiltinVaListDecl;
6172}
6173
Meador Ingecfb60902012-07-01 15:57:25 +00006174QualType ASTContext::getVaListTagType() const {
6175 // Force the creation of VaListTagTy by building the __builtin_va_list
6176 // declaration.
6177 if (VaListTagTy.isNull())
6178 (void) getBuiltinVaListDecl();
6179
6180 return VaListTagTy;
6181}
6182
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006183void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00006184 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00006185 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00006186
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006187 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00006188}
6189
John McCalld28ae272009-12-02 08:04:21 +00006190/// \brief Retrieve the template name that corresponds to a non-empty
6191/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00006192TemplateName
6193ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6194 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00006195 unsigned size = End - Begin;
6196 assert(size > 1 && "set is not overloaded!");
6197
6198 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6199 size * sizeof(FunctionTemplateDecl*));
6200 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6201
6202 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00006203 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00006204 NamedDecl *D = *I;
6205 assert(isa<FunctionTemplateDecl>(D) ||
6206 (isa<UsingShadowDecl>(D) &&
6207 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6208 *Storage++ = D;
6209 }
6210
6211 return TemplateName(OT);
6212}
6213
Douglas Gregordc572a32009-03-30 22:58:21 +00006214/// \brief Retrieve the template name that represents a qualified
6215/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00006216TemplateName
6217ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6218 bool TemplateKeyword,
6219 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00006220 assert(NNS && "Missing nested-name-specifier in qualified template name");
6221
Douglas Gregorc42075a2010-02-04 18:10:26 +00006222 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00006223 llvm::FoldingSetNodeID ID;
6224 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6225
6226 void *InsertPos = 0;
6227 QualifiedTemplateName *QTN =
6228 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6229 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00006230 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6231 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00006232 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6233 }
6234
6235 return TemplateName(QTN);
6236}
6237
6238/// \brief Retrieve the template name that represents a dependent
6239/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00006240TemplateName
6241ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6242 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00006243 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00006244 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00006245
6246 llvm::FoldingSetNodeID ID;
6247 DependentTemplateName::Profile(ID, NNS, Name);
6248
6249 void *InsertPos = 0;
6250 DependentTemplateName *QTN =
6251 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6252
6253 if (QTN)
6254 return TemplateName(QTN);
6255
6256 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6257 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006258 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6259 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00006260 } else {
6261 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00006262 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6263 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006264 DependentTemplateName *CheckQTN =
6265 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6266 assert(!CheckQTN && "Dependent type name canonicalization broken");
6267 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00006268 }
6269
6270 DependentTemplateNames.InsertNode(QTN, InsertPos);
6271 return TemplateName(QTN);
6272}
6273
Douglas Gregor71395fa2009-11-04 00:56:37 +00006274/// \brief Retrieve the template name that represents a dependent
6275/// template name such as \c MetaFun::template operator+.
6276TemplateName
6277ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00006278 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00006279 assert((!NNS || NNS->isDependent()) &&
6280 "Nested name specifier must be dependent");
6281
6282 llvm::FoldingSetNodeID ID;
6283 DependentTemplateName::Profile(ID, NNS, Operator);
6284
6285 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00006286 DependentTemplateName *QTN
6287 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006288
6289 if (QTN)
6290 return TemplateName(QTN);
6291
6292 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6293 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006294 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6295 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006296 } else {
6297 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00006298 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6299 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006300
6301 DependentTemplateName *CheckQTN
6302 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6303 assert(!CheckQTN && "Dependent template name canonicalization broken");
6304 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00006305 }
6306
6307 DependentTemplateNames.InsertNode(QTN, InsertPos);
6308 return TemplateName(QTN);
6309}
6310
Douglas Gregor5590be02011-01-15 06:45:20 +00006311TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00006312ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6313 TemplateName replacement) const {
6314 llvm::FoldingSetNodeID ID;
6315 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
6316
6317 void *insertPos = 0;
6318 SubstTemplateTemplateParmStorage *subst
6319 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6320
6321 if (!subst) {
6322 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6323 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6324 }
6325
6326 return TemplateName(subst);
6327}
6328
6329TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00006330ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6331 const TemplateArgument &ArgPack) const {
6332 ASTContext &Self = const_cast<ASTContext &>(*this);
6333 llvm::FoldingSetNodeID ID;
6334 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
6335
6336 void *InsertPos = 0;
6337 SubstTemplateTemplateParmPackStorage *Subst
6338 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6339
6340 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00006341 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00006342 ArgPack.pack_size(),
6343 ArgPack.pack_begin());
6344 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6345 }
6346
6347 return TemplateName(Subst);
6348}
6349
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006350/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00006351/// TargetInfo, produce the corresponding type. The unsigned @p Type
6352/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00006353CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006354 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00006355 case TargetInfo::NoInt: return CanQualType();
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00006356 case TargetInfo::SignedChar: return SignedCharTy;
6357 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006358 case TargetInfo::SignedShort: return ShortTy;
6359 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6360 case TargetInfo::SignedInt: return IntTy;
6361 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6362 case TargetInfo::SignedLong: return LongTy;
6363 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6364 case TargetInfo::SignedLongLong: return LongLongTy;
6365 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6366 }
6367
David Blaikie83d382b2011-09-23 05:06:16 +00006368 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006369}
Ted Kremenek77c51b22008-07-24 23:58:27 +00006370
6371//===----------------------------------------------------------------------===//
6372// Type Predicates.
6373//===----------------------------------------------------------------------===//
6374
Fariborz Jahanian96207692009-02-18 21:49:28 +00006375/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6376/// garbage collection attribute.
6377///
John McCall553d45a2011-01-12 00:34:59 +00006378Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006379 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00006380 return Qualifiers::GCNone;
6381
David Blaikiebbafb8a2012-03-11 07:00:24 +00006382 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00006383 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6384
6385 // Default behaviour under objective-C's gc is for ObjC pointers
6386 // (or pointers to them) be treated as though they were declared
6387 // as __strong.
6388 if (GCAttrs == Qualifiers::GCNone) {
6389 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6390 return Qualifiers::Strong;
6391 else if (Ty->isPointerType())
6392 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6393 } else {
6394 // It's not valid to set GC attributes on anything that isn't a
6395 // pointer.
6396#ifndef NDEBUG
6397 QualType CT = Ty->getCanonicalTypeInternal();
6398 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6399 CT = AT->getElementType();
6400 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6401#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00006402 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00006403 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00006404}
6405
Chris Lattner49af6a42008-04-07 06:51:04 +00006406//===----------------------------------------------------------------------===//
6407// Type Compatibility Testing
6408//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00006409
Mike Stump11289f42009-09-09 15:08:12 +00006410/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006411/// compatible.
6412static bool areCompatVectorTypes(const VectorType *LHS,
6413 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00006414 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00006415 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00006416 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00006417}
6418
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006419bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6420 QualType SecondVec) {
6421 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6422 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6423
6424 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6425 return true;
6426
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006427 // Treat Neon vector types and most AltiVec vector types as if they are the
6428 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006429 const VectorType *First = FirstVec->getAs<VectorType>();
6430 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006431 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006432 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006433 First->getVectorKind() != VectorType::AltiVecPixel &&
6434 First->getVectorKind() != VectorType::AltiVecBool &&
6435 Second->getVectorKind() != VectorType::AltiVecPixel &&
6436 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006437 return true;
6438
6439 return false;
6440}
6441
Steve Naroff8e6aee52009-07-23 01:01:38 +00006442//===----------------------------------------------------------------------===//
6443// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6444//===----------------------------------------------------------------------===//
6445
6446/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6447/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00006448bool
6449ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6450 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00006451 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006452 return true;
6453 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
6454 E = rProto->protocol_end(); PI != E; ++PI)
6455 if (ProtocolCompatibleWithProtocol(lProto, *PI))
6456 return true;
6457 return false;
6458}
6459
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006460/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6461/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006462bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6463 QualType rhs) {
6464 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6465 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6466 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6467
6468 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6469 E = lhsQID->qual_end(); I != E; ++I) {
6470 bool match = false;
6471 ObjCProtocolDecl *lhsProto = *I;
6472 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6473 E = rhsOPT->qual_end(); J != E; ++J) {
6474 ObjCProtocolDecl *rhsProto = *J;
6475 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6476 match = true;
6477 break;
6478 }
6479 }
6480 if (!match)
6481 return false;
6482 }
6483 return true;
6484}
6485
Steve Naroff8e6aee52009-07-23 01:01:38 +00006486/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6487/// ObjCQualifiedIDType.
6488bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6489 bool compare) {
6490 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00006491 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006492 lhs->isObjCIdType() || lhs->isObjCClassType())
6493 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006494 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006495 rhs->isObjCIdType() || rhs->isObjCClassType())
6496 return true;
6497
6498 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00006499 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006500
Steve Naroff8e6aee52009-07-23 01:01:38 +00006501 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00006502
Steve Naroff8e6aee52009-07-23 01:01:38 +00006503 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00006504 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006505 // make sure we check the class hierarchy.
6506 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6507 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6508 E = lhsQID->qual_end(); I != E; ++I) {
6509 // when comparing an id<P> on lhs with a static type on rhs,
6510 // see if static class implements all of id's protocols, directly or
6511 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00006512 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006513 return false;
6514 }
6515 }
6516 // If there are no qualifiers and no interface, we have an 'id'.
6517 return true;
6518 }
Mike Stump11289f42009-09-09 15:08:12 +00006519 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006520 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6521 E = lhsQID->qual_end(); I != E; ++I) {
6522 ObjCProtocolDecl *lhsProto = *I;
6523 bool match = false;
6524
6525 // when comparing an id<P> on lhs with a static type on rhs,
6526 // see if static class implements all of id's protocols, directly or
6527 // through its super class and categories.
6528 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6529 E = rhsOPT->qual_end(); J != E; ++J) {
6530 ObjCProtocolDecl *rhsProto = *J;
6531 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6532 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6533 match = true;
6534 break;
6535 }
6536 }
Mike Stump11289f42009-09-09 15:08:12 +00006537 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006538 // make sure we check the class hierarchy.
6539 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6540 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6541 E = lhsQID->qual_end(); I != E; ++I) {
6542 // when comparing an id<P> on lhs with a static type on rhs,
6543 // see if static class implements all of id's protocols, directly or
6544 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00006545 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006546 match = true;
6547 break;
6548 }
6549 }
6550 }
6551 if (!match)
6552 return false;
6553 }
Mike Stump11289f42009-09-09 15:08:12 +00006554
Steve Naroff8e6aee52009-07-23 01:01:38 +00006555 return true;
6556 }
Mike Stump11289f42009-09-09 15:08:12 +00006557
Steve Naroff8e6aee52009-07-23 01:01:38 +00006558 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6559 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6560
Mike Stump11289f42009-09-09 15:08:12 +00006561 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00006562 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006563 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006564 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
6565 E = lhsOPT->qual_end(); I != E; ++I) {
6566 ObjCProtocolDecl *lhsProto = *I;
6567 bool match = false;
6568
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006569 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00006570 // see if static class implements all of id's protocols, directly or
6571 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006572 // First, lhs protocols in the qualifier list must be found, direct
6573 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006574 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6575 E = rhsQID->qual_end(); J != E; ++J) {
6576 ObjCProtocolDecl *rhsProto = *J;
6577 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6578 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6579 match = true;
6580 break;
6581 }
6582 }
6583 if (!match)
6584 return false;
6585 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006586
6587 // Static class's protocols, or its super class or category protocols
6588 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6589 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6590 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6591 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6592 // This is rather dubious but matches gcc's behavior. If lhs has
6593 // no type qualifier and its class has no static protocol(s)
6594 // assume that it is mismatch.
6595 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6596 return false;
6597 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6598 LHSInheritedProtocols.begin(),
6599 E = LHSInheritedProtocols.end(); I != E; ++I) {
6600 bool match = false;
6601 ObjCProtocolDecl *lhsProto = (*I);
6602 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6603 E = rhsQID->qual_end(); J != E; ++J) {
6604 ObjCProtocolDecl *rhsProto = *J;
6605 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6606 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6607 match = true;
6608 break;
6609 }
6610 }
6611 if (!match)
6612 return false;
6613 }
6614 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00006615 return true;
6616 }
6617 return false;
6618}
6619
Eli Friedman47f77112008-08-22 00:56:42 +00006620/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006621/// compatible for assignment from RHS to LHS. This handles validation of any
6622/// protocol qualifiers on the LHS or RHS.
6623///
Steve Naroff7cae42b2009-07-10 23:34:53 +00006624bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6625 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00006626 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6627 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6628
Steve Naroff1329fa02009-07-15 18:40:39 +00006629 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00006630 if (LHS->isObjCUnqualifiedIdOrClass() ||
6631 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00006632 return true;
6633
John McCall8b07ec22010-05-15 11:32:37 +00006634 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00006635 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6636 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00006637 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006638
6639 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6640 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6641 QualType(RHSOPT,0));
6642
John McCall8b07ec22010-05-15 11:32:37 +00006643 // If we have 2 user-defined types, fall into that path.
6644 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00006645 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006646
Steve Naroff8e6aee52009-07-23 01:01:38 +00006647 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006648}
6649
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006650/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00006651/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006652/// arguments in block literals. When passed as arguments, passing 'A*' where
6653/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6654/// not OK. For the return type, the opposite is not OK.
6655bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6656 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006657 const ObjCObjectPointerType *RHSOPT,
6658 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006659 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006660 return true;
6661
6662 if (LHSOPT->isObjCBuiltinType()) {
6663 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6664 }
6665
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006666 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006667 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6668 QualType(RHSOPT,0),
6669 false);
6670
6671 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6672 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6673 if (LHS && RHS) { // We have 2 user-defined types.
6674 if (LHS != RHS) {
6675 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006676 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006677 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006678 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006679 }
6680 else
6681 return true;
6682 }
6683 return false;
6684}
6685
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006686/// getIntersectionOfProtocols - This routine finds the intersection of set
6687/// of protocols inherited from two distinct objective-c pointer objects.
6688/// It is used to build composite qualifier list of the composite type of
6689/// the conditional expression involving two objective-c pointer objects.
6690static
6691void getIntersectionOfProtocols(ASTContext &Context,
6692 const ObjCObjectPointerType *LHSOPT,
6693 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006694 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006695
John McCall8b07ec22010-05-15 11:32:37 +00006696 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6697 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6698 assert(LHS->getInterface() && "LHS must have an interface base");
6699 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006700
6701 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6702 unsigned LHSNumProtocols = LHS->getNumProtocols();
6703 if (LHSNumProtocols > 0)
6704 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6705 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006706 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006707 Context.CollectInheritedProtocols(LHS->getInterface(),
6708 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006709 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6710 LHSInheritedProtocols.end());
6711 }
6712
6713 unsigned RHSNumProtocols = RHS->getNumProtocols();
6714 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00006715 ObjCProtocolDecl **RHSProtocols =
6716 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006717 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6718 if (InheritedProtocolSet.count(RHSProtocols[i]))
6719 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00006720 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006721 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006722 Context.CollectInheritedProtocols(RHS->getInterface(),
6723 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006724 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6725 RHSInheritedProtocols.begin(),
6726 E = RHSInheritedProtocols.end(); I != E; ++I)
6727 if (InheritedProtocolSet.count((*I)))
6728 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006729 }
6730}
6731
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006732/// areCommonBaseCompatible - Returns common base class of the two classes if
6733/// one found. Note that this is O'2 algorithm. But it will be called as the
6734/// last type comparison in a ?-exp of ObjC pointer types before a
6735/// warning is issued. So, its invokation is extremely rare.
6736QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00006737 const ObjCObjectPointerType *Lptr,
6738 const ObjCObjectPointerType *Rptr) {
6739 const ObjCObjectType *LHS = Lptr->getObjectType();
6740 const ObjCObjectType *RHS = Rptr->getObjectType();
6741 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6742 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00006743 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006744 return QualType();
6745
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006746 do {
John McCall8b07ec22010-05-15 11:32:37 +00006747 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006748 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006749 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00006750 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6751
6752 QualType Result = QualType(LHS, 0);
6753 if (!Protocols.empty())
6754 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6755 Result = getObjCObjectPointerType(Result);
6756 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006757 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006758 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006759
6760 return QualType();
6761}
6762
John McCall8b07ec22010-05-15 11:32:37 +00006763bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6764 const ObjCObjectType *RHS) {
6765 assert(LHS->getInterface() && "LHS is not an interface type");
6766 assert(RHS->getInterface() && "RHS is not an interface type");
6767
Chris Lattner49af6a42008-04-07 06:51:04 +00006768 // Verify that the base decls are compatible: the RHS must be a subclass of
6769 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00006770 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00006771 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006772
Chris Lattner49af6a42008-04-07 06:51:04 +00006773 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6774 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00006775 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00006776 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006777
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006778 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6779 // more detailed analysis is required.
6780 if (RHS->getNumProtocols() == 0) {
6781 // OK, if LHS is a superclass of RHS *and*
6782 // this superclass is assignment compatible with LHS.
6783 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006784 bool IsSuperClass =
6785 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6786 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006787 // OK if conversion of LHS to SuperClass results in narrowing of types
6788 // ; i.e., SuperClass may implement at least one of the protocols
6789 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6790 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6791 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006792 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006793 // If super class has no protocols, it is not a match.
6794 if (SuperClassInheritedProtocols.empty())
6795 return false;
6796
6797 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6798 LHSPE = LHS->qual_end();
6799 LHSPI != LHSPE; LHSPI++) {
6800 bool SuperImplementsProtocol = false;
6801 ObjCProtocolDecl *LHSProto = (*LHSPI);
6802
6803 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6804 SuperClassInheritedProtocols.begin(),
6805 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6806 ObjCProtocolDecl *SuperClassProto = (*I);
6807 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6808 SuperImplementsProtocol = true;
6809 break;
6810 }
6811 }
6812 if (!SuperImplementsProtocol)
6813 return false;
6814 }
6815 return true;
6816 }
6817 return false;
6818 }
Mike Stump11289f42009-09-09 15:08:12 +00006819
John McCall8b07ec22010-05-15 11:32:37 +00006820 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6821 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00006822 LHSPI != LHSPE; LHSPI++) {
6823 bool RHSImplementsProtocol = false;
6824
6825 // If the RHS doesn't implement the protocol on the left, the types
6826 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00006827 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6828 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00006829 RHSPI != RHSPE; RHSPI++) {
6830 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00006831 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00006832 break;
6833 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006834 }
6835 // FIXME: For better diagnostics, consider passing back the protocol name.
6836 if (!RHSImplementsProtocol)
6837 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00006838 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006839 // The RHS implements all protocols listed on the LHS.
6840 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00006841}
6842
Steve Naroffb7605152009-02-12 17:52:19 +00006843bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6844 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00006845 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6846 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006847
Steve Naroff7cae42b2009-07-10 23:34:53 +00006848 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00006849 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006850
6851 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6852 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00006853}
6854
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006855bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6856 return canAssignObjCInterfaces(
6857 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6858 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6859}
6860
Mike Stump11289f42009-09-09 15:08:12 +00006861/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00006862/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00006863/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00006864/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006865bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6866 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006867 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00006868 return hasSameType(LHS, RHS);
6869
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006870 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00006871}
6872
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006873bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00006874 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006875}
6876
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006877bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6878 return !mergeTypes(LHS, RHS, true).isNull();
6879}
6880
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006881/// mergeTransparentUnionType - if T is a transparent union type and a member
6882/// of T is compatible with SubType, return the merged type, else return
6883/// QualType()
6884QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6885 bool OfBlockPointer,
6886 bool Unqualified) {
6887 if (const RecordType *UT = T->getAsUnionType()) {
6888 RecordDecl *UD = UT->getDecl();
6889 if (UD->hasAttr<TransparentUnionAttr>()) {
6890 for (RecordDecl::field_iterator it = UD->field_begin(),
6891 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00006892 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006893 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6894 if (!MT.isNull())
6895 return MT;
6896 }
6897 }
6898 }
6899
6900 return QualType();
6901}
6902
6903/// mergeFunctionArgumentTypes - merge two types which appear as function
6904/// argument types
6905QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
6906 bool OfBlockPointer,
6907 bool Unqualified) {
6908 // GNU extension: two types are compatible if they appear as a function
6909 // argument, one of the types is a transparent union type and the other
6910 // type is compatible with a union member
6911 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6912 Unqualified);
6913 if (!lmerge.isNull())
6914 return lmerge;
6915
6916 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6917 Unqualified);
6918 if (!rmerge.isNull())
6919 return rmerge;
6920
6921 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6922}
6923
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006924QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006925 bool OfBlockPointer,
6926 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00006927 const FunctionType *lbase = lhs->getAs<FunctionType>();
6928 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006929 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6930 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00006931 bool allLTypes = true;
6932 bool allRTypes = true;
6933
6934 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006935 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00006936 if (OfBlockPointer) {
6937 QualType RHS = rbase->getResultType();
6938 QualType LHS = lbase->getResultType();
6939 bool UnqualifiedResult = Unqualified;
6940 if (!UnqualifiedResult)
6941 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006942 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00006943 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006944 else
John McCall8c6b56f2010-12-15 01:06:38 +00006945 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6946 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006947 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006948
6949 if (Unqualified)
6950 retType = retType.getUnqualifiedType();
6951
6952 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6953 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6954 if (Unqualified) {
6955 LRetType = LRetType.getUnqualifiedType();
6956 RRetType = RRetType.getUnqualifiedType();
6957 }
6958
6959 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006960 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006961 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006962 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006963
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00006964 // FIXME: double check this
6965 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6966 // rbase->getRegParmAttr() != 0 &&
6967 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00006968 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6969 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00006970
Douglas Gregor8c940862010-01-18 17:14:39 +00006971 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00006972 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Douglas Gregor8c940862010-01-18 17:14:39 +00006973 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006974
John McCall8c6b56f2010-12-15 01:06:38 +00006975 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00006976 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6977 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00006978 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6979 return QualType();
6980
John McCall31168b02011-06-15 23:02:42 +00006981 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6982 return QualType();
6983
John McCall8c6b56f2010-12-15 01:06:38 +00006984 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6985 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00006986
Rafael Espindola8778c282012-11-29 16:09:03 +00006987 if (lbaseInfo.getNoReturn() != NoReturn)
6988 allLTypes = false;
6989 if (rbaseInfo.getNoReturn() != NoReturn)
6990 allRTypes = false;
6991
John McCall31168b02011-06-15 23:02:42 +00006992 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00006993
Eli Friedman47f77112008-08-22 00:56:42 +00006994 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006995 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6996 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006997 unsigned lproto_nargs = lproto->getNumArgs();
6998 unsigned rproto_nargs = rproto->getNumArgs();
6999
7000 // Compatible functions must have the same number of arguments
7001 if (lproto_nargs != rproto_nargs)
7002 return QualType();
7003
7004 // Variadic and non-variadic functions aren't compatible
7005 if (lproto->isVariadic() != rproto->isVariadic())
7006 return QualType();
7007
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00007008 if (lproto->getTypeQuals() != rproto->getTypeQuals())
7009 return QualType();
7010
Fariborz Jahanian97676972011-09-28 21:52:05 +00007011 if (LangOpts.ObjCAutoRefCount &&
7012 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
7013 return QualType();
7014
Eli Friedman47f77112008-08-22 00:56:42 +00007015 // Check argument compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007016 SmallVector<QualType, 10> types;
Eli Friedman47f77112008-08-22 00:56:42 +00007017 for (unsigned i = 0; i < lproto_nargs; i++) {
7018 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
7019 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007020 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
7021 OfBlockPointer,
7022 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007023 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007024
7025 if (Unqualified)
7026 argtype = argtype.getUnqualifiedType();
7027
Eli Friedman47f77112008-08-22 00:56:42 +00007028 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007029 if (Unqualified) {
7030 largtype = largtype.getUnqualifiedType();
7031 rargtype = rargtype.getUnqualifiedType();
7032 }
7033
Chris Lattner465fa322008-10-05 17:34:18 +00007034 if (getCanonicalType(argtype) != getCanonicalType(largtype))
7035 allLTypes = false;
7036 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
7037 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00007038 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00007039
Eli Friedman47f77112008-08-22 00:56:42 +00007040 if (allLTypes) return lhs;
7041 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007042
7043 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7044 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00007045 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007046 }
7047
7048 if (lproto) allRTypes = false;
7049 if (rproto) allLTypes = false;
7050
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007051 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00007052 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007053 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00007054 if (proto->isVariadic()) return QualType();
7055 // Check that the types are compatible with the types that
7056 // would result from default argument promotions (C99 6.7.5.3p15).
7057 // The only types actually affected are promotable integer
7058 // types and floats, which would be passed as a different
7059 // type depending on whether the prototype is visible.
7060 unsigned proto_nargs = proto->getNumArgs();
7061 for (unsigned i = 0; i < proto_nargs; ++i) {
7062 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00007063
Eli Friedman448ce402012-08-30 00:44:15 +00007064 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00007065 // to pass enum values.
Eli Friedman448ce402012-08-30 00:44:15 +00007066 if (const EnumType *Enum = argTy->getAs<EnumType>()) {
7067 argTy = Enum->getDecl()->getIntegerType();
7068 if (argTy.isNull())
7069 return QualType();
7070 }
Douglas Gregor2973d402010-02-03 19:27:29 +00007071
Eli Friedman47f77112008-08-22 00:56:42 +00007072 if (argTy->isPromotableIntegerType() ||
7073 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
7074 return QualType();
7075 }
7076
7077 if (allLTypes) return lhs;
7078 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007079
7080 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7081 EPI.ExtInfo = einfo;
Reid Kleckner896b32f2013-06-10 20:51:09 +00007082 return getFunctionType(retType, proto->getArgTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007083 }
7084
7085 if (allLTypes) return lhs;
7086 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00007087 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00007088}
7089
John McCall433c2e62013-03-21 00:10:07 +00007090/// Given that we have an enum type and a non-enum type, try to merge them.
7091static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7092 QualType other, bool isBlockReturnType) {
7093 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7094 // a signed integer type, or an unsigned integer type.
7095 // Compatibility is based on the underlying type, not the promotion
7096 // type.
7097 QualType underlyingType = ET->getDecl()->getIntegerType();
7098 if (underlyingType.isNull()) return QualType();
7099 if (Context.hasSameType(underlyingType, other))
7100 return other;
7101
7102 // In block return types, we're more permissive and accept any
7103 // integral type of the same size.
7104 if (isBlockReturnType && other->isIntegerType() &&
7105 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7106 return other;
7107
7108 return QualType();
7109}
7110
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007111QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007112 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007113 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00007114 // C++ [expr]: If an expression initially has the type "reference to T", the
7115 // type is adjusted to "T" prior to any further analysis, the expression
7116 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007117 // expression is an lvalue unless the reference is an rvalue reference and
7118 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00007119 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7120 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007121
7122 if (Unqualified) {
7123 LHS = LHS.getUnqualifiedType();
7124 RHS = RHS.getUnqualifiedType();
7125 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00007126
Eli Friedman47f77112008-08-22 00:56:42 +00007127 QualType LHSCan = getCanonicalType(LHS),
7128 RHSCan = getCanonicalType(RHS);
7129
7130 // If two types are identical, they are compatible.
7131 if (LHSCan == RHSCan)
7132 return LHS;
7133
John McCall8ccfcb52009-09-24 19:53:00 +00007134 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007135 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7136 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00007137 if (LQuals != RQuals) {
7138 // If any of these qualifiers are different, we have a type
7139 // mismatch.
7140 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00007141 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7142 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00007143 return QualType();
7144
7145 // Exactly one GC qualifier difference is allowed: __strong is
7146 // okay if the other type has no GC qualifier but is an Objective
7147 // C object pointer (i.e. implicitly strong by default). We fix
7148 // this by pretending that the unqualified type was actually
7149 // qualified __strong.
7150 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7151 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7152 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7153
7154 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7155 return QualType();
7156
7157 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7158 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7159 }
7160 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7161 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7162 }
Eli Friedman47f77112008-08-22 00:56:42 +00007163 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00007164 }
7165
7166 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00007167
Eli Friedmandcca6332009-06-01 01:22:52 +00007168 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7169 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00007170
Chris Lattnerfd652912008-01-14 05:45:46 +00007171 // We want to consider the two function types to be the same for these
7172 // comparisons, just force one to the other.
7173 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7174 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00007175
7176 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00007177 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7178 LHSClass = Type::ConstantArray;
7179 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7180 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00007181
John McCall8b07ec22010-05-15 11:32:37 +00007182 // ObjCInterfaces are just specialized ObjCObjects.
7183 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7184 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7185
Nate Begemance4d7fc2008-04-18 23:10:10 +00007186 // Canonicalize ExtVector -> Vector.
7187 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7188 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00007189
Chris Lattner95554662008-04-07 05:43:21 +00007190 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007191 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00007192 // Note that we only have special rules for turning block enum
7193 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00007194 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007195 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007196 }
John McCall9dd450b2009-09-21 23:43:11 +00007197 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007198 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007199 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007200 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00007201 if (OfBlockPointer && !BlockReturnType) {
7202 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7203 return LHS;
7204 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7205 return RHS;
7206 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007207
Eli Friedman47f77112008-08-22 00:56:42 +00007208 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00007209 }
Eli Friedman47f77112008-08-22 00:56:42 +00007210
Steve Naroffc6edcbd2008-01-09 22:43:08 +00007211 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007212 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007213#define TYPE(Class, Base)
7214#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00007215#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007216#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7217#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7218#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00007219 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007220
Richard Smith27d807c2013-04-30 13:56:41 +00007221 case Type::Auto:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007222 case Type::LValueReference:
7223 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007224 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00007225 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007226
John McCall8b07ec22010-05-15 11:32:37 +00007227 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007228 case Type::IncompleteArray:
7229 case Type::VariableArray:
7230 case Type::FunctionProto:
7231 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00007232 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007233
Chris Lattnerfd652912008-01-14 05:45:46 +00007234 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00007235 {
7236 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007237 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7238 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007239 if (Unqualified) {
7240 LHSPointee = LHSPointee.getUnqualifiedType();
7241 RHSPointee = RHSPointee.getUnqualifiedType();
7242 }
7243 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7244 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007245 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00007246 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007247 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00007248 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007249 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007250 return getPointerType(ResultType);
7251 }
Steve Naroff68e167d2008-12-10 17:49:55 +00007252 case Type::BlockPointer:
7253 {
7254 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007255 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7256 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007257 if (Unqualified) {
7258 LHSPointee = LHSPointee.getUnqualifiedType();
7259 RHSPointee = RHSPointee.getUnqualifiedType();
7260 }
7261 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7262 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00007263 if (ResultType.isNull()) return QualType();
7264 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7265 return LHS;
7266 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7267 return RHS;
7268 return getBlockPointerType(ResultType);
7269 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00007270 case Type::Atomic:
7271 {
7272 // Merge two pointer types, while trying to preserve typedef info
7273 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7274 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7275 if (Unqualified) {
7276 LHSValue = LHSValue.getUnqualifiedType();
7277 RHSValue = RHSValue.getUnqualifiedType();
7278 }
7279 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7280 Unqualified);
7281 if (ResultType.isNull()) return QualType();
7282 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7283 return LHS;
7284 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7285 return RHS;
7286 return getAtomicType(ResultType);
7287 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007288 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00007289 {
7290 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7291 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7292 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7293 return QualType();
7294
7295 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7296 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007297 if (Unqualified) {
7298 LHSElem = LHSElem.getUnqualifiedType();
7299 RHSElem = RHSElem.getUnqualifiedType();
7300 }
7301
7302 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007303 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00007304 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7305 return LHS;
7306 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7307 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00007308 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7309 ArrayType::ArraySizeModifier(), 0);
7310 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7311 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007312 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7313 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00007314 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7315 return LHS;
7316 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7317 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007318 if (LVAT) {
7319 // FIXME: This isn't correct! But tricky to implement because
7320 // the array's size has to be the size of LHS, but the type
7321 // has to be different.
7322 return LHS;
7323 }
7324 if (RVAT) {
7325 // FIXME: This isn't correct! But tricky to implement because
7326 // the array's size has to be the size of RHS, but the type
7327 // has to be different.
7328 return RHS;
7329 }
Eli Friedman3e62c212008-08-22 01:48:21 +00007330 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7331 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00007332 return getIncompleteArrayType(ResultType,
7333 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007334 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007335 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007336 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007337 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007338 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00007339 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00007340 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007341 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00007342 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00007343 case Type::Complex:
7344 // Distinct complex types are incompatible.
7345 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007346 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00007347 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00007348 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7349 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00007350 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00007351 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00007352 case Type::ObjCObject: {
7353 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00007354 // FIXME: This should be type compatibility, e.g. whether
7355 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00007356 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7357 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7358 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00007359 return LHS;
7360
Eli Friedman47f77112008-08-22 00:56:42 +00007361 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00007362 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007363 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007364 if (OfBlockPointer) {
7365 if (canAssignObjCInterfacesInBlockPointer(
7366 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007367 RHS->getAs<ObjCObjectPointerType>(),
7368 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00007369 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007370 return QualType();
7371 }
John McCall9dd450b2009-09-21 23:43:11 +00007372 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7373 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007374 return LHS;
7375
Steve Naroffc68cfcf2008-12-10 22:14:21 +00007376 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00007377 }
Steve Naroff32e44c02007-10-15 20:41:53 +00007378 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007379
David Blaikie8a40f702012-01-17 06:56:22 +00007380 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00007381}
Ted Kremenekfc581a92007-10-31 17:10:13 +00007382
Fariborz Jahanian97676972011-09-28 21:52:05 +00007383bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7384 const FunctionProtoType *FromFunctionType,
7385 const FunctionProtoType *ToFunctionType) {
7386 if (FromFunctionType->hasAnyConsumedArgs() !=
7387 ToFunctionType->hasAnyConsumedArgs())
7388 return false;
7389 FunctionProtoType::ExtProtoInfo FromEPI =
7390 FromFunctionType->getExtProtoInfo();
7391 FunctionProtoType::ExtProtoInfo ToEPI =
7392 ToFunctionType->getExtProtoInfo();
7393 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
7394 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
7395 ArgIdx != NumArgs; ++ArgIdx) {
7396 if (FromEPI.ConsumedArguments[ArgIdx] !=
7397 ToEPI.ConsumedArguments[ArgIdx])
7398 return false;
7399 }
7400 return true;
7401}
7402
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007403/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7404/// 'RHS' attributes and returns the merged version; including for function
7405/// return types.
7406QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7407 QualType LHSCan = getCanonicalType(LHS),
7408 RHSCan = getCanonicalType(RHS);
7409 // If two types are identical, they are compatible.
7410 if (LHSCan == RHSCan)
7411 return LHS;
7412 if (RHSCan->isFunctionType()) {
7413 if (!LHSCan->isFunctionType())
7414 return QualType();
7415 QualType OldReturnType =
7416 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
7417 QualType NewReturnType =
7418 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
7419 QualType ResReturnType =
7420 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7421 if (ResReturnType.isNull())
7422 return QualType();
7423 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7424 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7425 // In either case, use OldReturnType to build the new function type.
7426 const FunctionType *F = LHS->getAs<FunctionType>();
7427 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00007428 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7429 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00007430 QualType ResultType =
7431 getFunctionType(OldReturnType, FPT->getArgTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007432 return ResultType;
7433 }
7434 }
7435 return QualType();
7436 }
7437
7438 // If the qualifiers are different, the types can still be merged.
7439 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7440 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7441 if (LQuals != RQuals) {
7442 // If any of these qualifiers are different, we have a type mismatch.
7443 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7444 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7445 return QualType();
7446
7447 // Exactly one GC qualifier difference is allowed: __strong is
7448 // okay if the other type has no GC qualifier but is an Objective
7449 // C object pointer (i.e. implicitly strong by default). We fix
7450 // this by pretending that the unqualified type was actually
7451 // qualified __strong.
7452 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7453 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7454 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7455
7456 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7457 return QualType();
7458
7459 if (GC_L == Qualifiers::Strong)
7460 return LHS;
7461 if (GC_R == Qualifiers::Strong)
7462 return RHS;
7463 return QualType();
7464 }
7465
7466 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7467 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7468 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7469 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7470 if (ResQT == LHSBaseQT)
7471 return LHS;
7472 if (ResQT == RHSBaseQT)
7473 return RHS;
7474 }
7475 return QualType();
7476}
7477
Chris Lattner4ba0cef2008-04-07 07:01:58 +00007478//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007479// Integer Predicates
7480//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00007481
Jay Foad39c79802011-01-12 09:06:06 +00007482unsigned ASTContext::getIntWidth(QualType T) const {
Richard Smithe9521062013-10-15 04:56:17 +00007483 if (const EnumType *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00007484 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00007485 if (T->isBooleanType())
7486 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00007487 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007488 return (unsigned)getTypeSize(T);
7489}
7490
Abramo Bagnara13640492012-09-09 10:21:24 +00007491QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007492 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00007493
7494 // Turn <4 x signed int> -> <4 x unsigned int>
7495 if (const VectorType *VTy = T->getAs<VectorType>())
7496 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00007497 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00007498
7499 // For enums, we return the unsigned version of the base type.
7500 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007501 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00007502
7503 const BuiltinType *BTy = T->getAs<BuiltinType>();
7504 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007505 switch (BTy->getKind()) {
7506 case BuiltinType::Char_S:
7507 case BuiltinType::SChar:
7508 return UnsignedCharTy;
7509 case BuiltinType::Short:
7510 return UnsignedShortTy;
7511 case BuiltinType::Int:
7512 return UnsignedIntTy;
7513 case BuiltinType::Long:
7514 return UnsignedLongTy;
7515 case BuiltinType::LongLong:
7516 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00007517 case BuiltinType::Int128:
7518 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007519 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007520 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007521 }
7522}
7523
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00007524ASTMutationListener::~ASTMutationListener() { }
7525
Richard Smith1fa5d642013-05-11 05:45:24 +00007526void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7527 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00007528
7529//===----------------------------------------------------------------------===//
7530// Builtin Type Computation
7531//===----------------------------------------------------------------------===//
7532
7533/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00007534/// pointer over the consumed characters. This returns the resultant type. If
7535/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7536/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7537/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007538///
7539/// RequiresICE is filled in on return to indicate whether the value is required
7540/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00007541static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00007542 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007543 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00007544 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00007545 // Modifiers.
7546 int HowLong = 0;
7547 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007548 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00007549
Chris Lattnerdc226c22010-10-01 22:42:38 +00007550 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00007551 bool Done = false;
7552 while (!Done) {
7553 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00007554 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00007555 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007556 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00007557 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007558 case 'S':
7559 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7560 assert(!Signed && "Can't use 'S' modifier multiple times!");
7561 Signed = true;
7562 break;
7563 case 'U':
7564 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7565 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7566 Unsigned = true;
7567 break;
7568 case 'L':
7569 assert(HowLong <= 2 && "Can't have LLLL modifier");
7570 ++HowLong;
7571 break;
7572 }
7573 }
7574
7575 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00007576
Chris Lattnerecd79c62009-06-14 00:45:47 +00007577 // Read the base type.
7578 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00007579 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007580 case 'v':
7581 assert(HowLong == 0 && !Signed && !Unsigned &&
7582 "Bad modifiers used with 'v'!");
7583 Type = Context.VoidTy;
7584 break;
Jack Carter24bef982013-08-15 15:16:57 +00007585 case 'h':
7586 assert(HowLong == 0 && !Signed && !Unsigned &&
7587 "Bad modifiers used with 'f'!");
7588 Type = Context.HalfTy;
7589 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007590 case 'f':
7591 assert(HowLong == 0 && !Signed && !Unsigned &&
7592 "Bad modifiers used with 'f'!");
7593 Type = Context.FloatTy;
7594 break;
7595 case 'd':
7596 assert(HowLong < 2 && !Signed && !Unsigned &&
7597 "Bad modifiers used with 'd'!");
7598 if (HowLong)
7599 Type = Context.LongDoubleTy;
7600 else
7601 Type = Context.DoubleTy;
7602 break;
7603 case 's':
7604 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7605 if (Unsigned)
7606 Type = Context.UnsignedShortTy;
7607 else
7608 Type = Context.ShortTy;
7609 break;
7610 case 'i':
7611 if (HowLong == 3)
7612 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7613 else if (HowLong == 2)
7614 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7615 else if (HowLong == 1)
7616 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7617 else
7618 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7619 break;
7620 case 'c':
7621 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7622 if (Signed)
7623 Type = Context.SignedCharTy;
7624 else if (Unsigned)
7625 Type = Context.UnsignedCharTy;
7626 else
7627 Type = Context.CharTy;
7628 break;
7629 case 'b': // boolean
7630 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7631 Type = Context.BoolTy;
7632 break;
7633 case 'z': // size_t.
7634 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7635 Type = Context.getSizeType();
7636 break;
7637 case 'F':
7638 Type = Context.getCFConstantStringType();
7639 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00007640 case 'G':
7641 Type = Context.getObjCIdType();
7642 break;
7643 case 'H':
7644 Type = Context.getObjCSelType();
7645 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00007646 case 'M':
7647 Type = Context.getObjCSuperType();
7648 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007649 case 'a':
7650 Type = Context.getBuiltinVaListType();
7651 assert(!Type.isNull() && "builtin va list type not initialized!");
7652 break;
7653 case 'A':
7654 // This is a "reference" to a va_list; however, what exactly
7655 // this means depends on how va_list is defined. There are two
7656 // different kinds of va_list: ones passed by value, and ones
7657 // passed by reference. An example of a by-value va_list is
7658 // x86, where va_list is a char*. An example of by-ref va_list
7659 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7660 // we want this argument to be a char*&; for x86-64, we want
7661 // it to be a __va_list_tag*.
7662 Type = Context.getBuiltinVaListType();
7663 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007664 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00007665 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007666 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00007667 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007668 break;
7669 case 'V': {
7670 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007671 unsigned NumElements = strtoul(Str, &End, 10);
7672 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007673 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00007674
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007675 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7676 RequiresICE, false);
7677 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00007678
7679 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00007680 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00007681 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007682 break;
7683 }
Douglas Gregorfed66992012-06-07 18:08:25 +00007684 case 'E': {
7685 char *End;
7686
7687 unsigned NumElements = strtoul(Str, &End, 10);
7688 assert(End != Str && "Missing vector size");
7689
7690 Str = End;
7691
7692 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7693 false);
7694 Type = Context.getExtVectorType(ElementType, NumElements);
7695 break;
7696 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007697 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007698 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7699 false);
7700 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007701 Type = Context.getComplexType(ElementType);
7702 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00007703 }
7704 case 'Y' : {
7705 Type = Context.getPointerDiffType();
7706 break;
7707 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00007708 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00007709 Type = Context.getFILEType();
7710 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007711 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007712 return QualType();
7713 }
Mike Stump2adb4da2009-07-28 23:47:15 +00007714 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00007715 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00007716 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00007717 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00007718 else
7719 Type = Context.getjmp_bufType();
7720
Mike Stump2adb4da2009-07-28 23:47:15 +00007721 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007722 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00007723 return QualType();
7724 }
7725 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00007726 case 'K':
7727 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7728 Type = Context.getucontext_tType();
7729
7730 if (Type.isNull()) {
7731 Error = ASTContext::GE_Missing_ucontext;
7732 return QualType();
7733 }
7734 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00007735 case 'p':
7736 Type = Context.getProcessIDType();
7737 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00007738 }
Mike Stump11289f42009-09-09 15:08:12 +00007739
Chris Lattnerdc226c22010-10-01 22:42:38 +00007740 // If there are modifiers and if we're allowed to parse them, go for it.
7741 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007742 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00007743 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007744 default: Done = true; --Str; break;
7745 case '*':
7746 case '&': {
7747 // Both pointers and references can have their pointee types
7748 // qualified with an address space.
7749 char *End;
7750 unsigned AddrSpace = strtoul(Str, &End, 10);
7751 if (End != Str && AddrSpace != 0) {
7752 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7753 Str = End;
7754 }
7755 if (c == '*')
7756 Type = Context.getPointerType(Type);
7757 else
7758 Type = Context.getLValueReferenceType(Type);
7759 break;
7760 }
7761 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7762 case 'C':
7763 Type = Type.withConst();
7764 break;
7765 case 'D':
7766 Type = Context.getVolatileType(Type);
7767 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00007768 case 'R':
7769 Type = Type.withRestrict();
7770 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007771 }
7772 }
Chris Lattner84733392010-10-01 07:13:18 +00007773
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007774 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00007775 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00007776
Chris Lattnerecd79c62009-06-14 00:45:47 +00007777 return Type;
7778}
7779
7780/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00007781QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007782 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00007783 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007784 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00007785
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007786 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00007787
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007788 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007789 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007790 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7791 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007792 if (Error != GE_None)
7793 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007794
7795 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7796
Chris Lattnerecd79c62009-06-14 00:45:47 +00007797 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007798 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007799 if (Error != GE_None)
7800 return QualType();
7801
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007802 // If this argument is required to be an IntegerConstantExpression and the
7803 // caller cares, fill in the bitmask we return.
7804 if (RequiresICE && IntegerConstantArgs)
7805 *IntegerConstantArgs |= 1 << ArgTypes.size();
7806
Chris Lattnerecd79c62009-06-14 00:45:47 +00007807 // Do array -> pointer decay. The builtin should use the decayed type.
7808 if (Ty->isArrayType())
7809 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00007810
Chris Lattnerecd79c62009-06-14 00:45:47 +00007811 ArgTypes.push_back(Ty);
7812 }
7813
7814 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7815 "'.' should only occur at end of builtin type list!");
7816
Reid Kleckner78af0702013-08-27 23:08:25 +00007817 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00007818 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7819
7820 bool Variadic = (TypeStr[0] == '.');
7821
7822 // We really shouldn't be making a no-proto type here, especially in C++.
7823 if (ArgTypes.empty() && Variadic)
7824 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00007825
John McCalldb40c7f2010-12-14 08:05:40 +00007826 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00007827 EPI.ExtInfo = EI;
7828 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00007829
Jordan Rose5c382722013-03-08 21:51:21 +00007830 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007831}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00007832
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007833GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007834 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007835 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007836
Rafael Espindola3ae00052013-05-13 00:12:11 +00007837 GVALinkage External = GVA_StrongExternal;
7838 switch (FD->getTemplateSpecializationKind()) {
7839 case TSK_Undeclared:
7840 case TSK_ExplicitSpecialization:
7841 External = GVA_StrongExternal;
7842 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007843
Rafael Espindola3ae00052013-05-13 00:12:11 +00007844 case TSK_ExplicitInstantiationDefinition:
7845 return GVA_ExplicitTemplateInstantiation;
7846
7847 case TSK_ExplicitInstantiationDeclaration:
7848 case TSK_ImplicitInstantiation:
7849 External = GVA_TemplateInstantiation;
7850 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007851 }
7852
7853 if (!FD->isInlined())
7854 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00007855
7856 if ((!getLangOpts().CPlusPlus && !getLangOpts().MicrosoftMode) ||
7857 FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007858 // GNU or C99 inline semantics. Determine whether this symbol should be
7859 // externally visible.
7860 if (FD->isInlineDefinitionExternallyVisible())
7861 return External;
7862
7863 // C99 inline semantics, where the symbol is not externally visible.
7864 return GVA_C99Inline;
7865 }
7866
7867 // C++0x [temp.explicit]p9:
7868 // [ Note: The intent is that an inline function that is the subject of
7869 // an explicit instantiation declaration will still be implicitly
7870 // instantiated when used so that the body can be considered for
7871 // inlining, but that no out-of-line copy of the inline function would be
7872 // generated in the translation unit. -- end note ]
7873 if (FD->getTemplateSpecializationKind()
7874 == TSK_ExplicitInstantiationDeclaration)
7875 return GVA_C99Inline;
7876
7877 return GVA_CXXInline;
7878}
7879
7880GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007881 if (!VD->isExternallyVisible())
7882 return GVA_Internal;
7883
Richard Smith8809a0c2013-09-27 20:14:12 +00007884 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007885 case TSK_Undeclared:
7886 case TSK_ExplicitSpecialization:
7887 return GVA_StrongExternal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007888
Rafael Espindola3ae00052013-05-13 00:12:11 +00007889 case TSK_ExplicitInstantiationDeclaration:
7890 llvm_unreachable("Variable should not be instantiated");
7891 // Fall through to treat this like any other instantiation.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007892
Rafael Espindola3ae00052013-05-13 00:12:11 +00007893 case TSK_ExplicitInstantiationDefinition:
7894 return GVA_ExplicitTemplateInstantiation;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007895
Rafael Espindola3ae00052013-05-13 00:12:11 +00007896 case TSK_ImplicitInstantiation:
7897 return GVA_TemplateInstantiation;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007898 }
Rafael Espindola27699c82013-05-13 14:05:53 +00007899
7900 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007901}
7902
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00007903bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007904 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7905 if (!VD->isFileVarDecl())
7906 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00007907 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7908 // We never need to emit an uninstantiated function template.
7909 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
7910 return false;
7911 } else
7912 return false;
7913
7914 // If this is a member of a class template, we do not need to emit it.
7915 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007916 return false;
7917
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007918 // Weak references don't produce any output by themselves.
7919 if (D->hasAttr<WeakRefAttr>())
7920 return false;
7921
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007922 // Aliases and used decls are required.
7923 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7924 return true;
7925
7926 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7927 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00007928 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00007929 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007930
7931 // Constructors and destructors are required.
7932 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7933 return true;
7934
John McCall6bd2a892013-01-25 22:31:03 +00007935 // The key function for a class is required. This rule only comes
7936 // into play when inline functions can be key functions, though.
7937 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7938 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7939 const CXXRecordDecl *RD = MD->getParent();
7940 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7941 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
7942 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7943 return true;
7944 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007945 }
7946 }
7947
7948 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7949
7950 // static, static inline, always_inline, and extern inline functions can
7951 // always be deferred. Normal inline functions can be deferred in C99/C++.
7952 // Implicit template instantiations can also be deferred in C++.
7953 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev79de4d42012-02-02 06:06:34 +00007954 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007955 return false;
7956 return true;
7957 }
Douglas Gregor87d81242011-09-10 00:22:34 +00007958
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007959 const VarDecl *VD = cast<VarDecl>(D);
7960 assert(VD->isFileVarDecl() && "Expected file scoped var");
7961
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007962 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7963 return false;
7964
Richard Smitha0e5e542012-11-12 21:38:00 +00007965 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007966 GVALinkage L = GetGVALinkageForVariable(VD);
Richard Smitha0e5e542012-11-12 21:38:00 +00007967 if (L != GVA_Internal && L != GVA_TemplateInstantiation)
7968 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007969
Richard Smitha0e5e542012-11-12 21:38:00 +00007970 // Variables that have destruction with side-effects are required.
7971 if (VD->getType().isDestructedType())
7972 return true;
7973
7974 // Variables that have initialization with side-effects are required.
7975 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
7976 return true;
7977
7978 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007979}
Charles Davis53c59df2010-08-16 03:33:14 +00007980
Reid Kleckner78af0702013-08-27 23:08:25 +00007981CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
7982 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00007983 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00007984 if (IsCXXMethod)
7985 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007986
Reid Kleckner78af0702013-08-27 23:08:25 +00007987 return (LangOpts.MRTD && !IsVariadic) ? CC_X86StdCall : CC_C;
Charles Davis99202b32010-11-09 18:04:24 +00007988}
7989
Jay Foad39c79802011-01-12 09:06:06 +00007990bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00007991 // Pass through to the C++ ABI object
7992 return ABI->isNearlyEmpty(RD);
7993}
7994
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007995MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00007996 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00007997 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00007998 case TargetCXXABI::GenericItanium:
7999 case TargetCXXABI::GenericARM:
8000 case TargetCXXABI::iOS:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008001 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00008002 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008003 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008004 }
David Blaikie83d382b2011-09-23 05:06:16 +00008005 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008006}
8007
Charles Davis53c59df2010-08-16 03:33:14 +00008008CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008009
8010size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00008011 return ASTRecordLayouts.getMemorySize() +
8012 llvm::capacity_in_bytes(ObjCLayouts) +
8013 llvm::capacity_in_bytes(KeyFunctions) +
8014 llvm::capacity_in_bytes(ObjCImpls) +
8015 llvm::capacity_in_bytes(BlockVarCopyInits) +
8016 llvm::capacity_in_bytes(DeclAttrs) +
8017 llvm::capacity_in_bytes(TemplateOrInstantiation) +
8018 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
8019 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
8020 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
8021 llvm::capacity_in_bytes(OverriddenMethods) +
8022 llvm::capacity_in_bytes(Types) +
8023 llvm::capacity_in_bytes(VariableArrayTypes) +
8024 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008025}
Ted Kremenek540017e2011-10-06 05:00:56 +00008026
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00008027/// getIntTypeForBitwidth -
8028/// sets integer QualTy according to specified details:
8029/// bitwidth, signed/unsigned.
8030/// Returns empty type if there is no appropriate target types.
8031QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
8032 unsigned Signed) const {
8033 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
8034 CanQualType QualTy = getFromTargetType(Ty);
8035 if (!QualTy && DestWidth == 128)
8036 return Signed ? Int128Ty : UnsignedInt128Ty;
8037 return QualTy;
8038}
8039
8040/// getRealTypeForBitwidth -
8041/// sets floating point QualTy according to specified bitwidth.
8042/// Returns empty type if there is no appropriate target types.
8043QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
8044 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
8045 switch (Ty) {
8046 case TargetInfo::Float:
8047 return FloatTy;
8048 case TargetInfo::Double:
8049 return DoubleTy;
8050 case TargetInfo::LongDouble:
8051 return LongDoubleTy;
8052 case TargetInfo::NoFloat:
8053 return QualType();
8054 }
8055
8056 llvm_unreachable("Unhandled TargetInfo::RealType value");
8057}
8058
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008059void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
8060 if (Number > 1)
8061 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00008062}
8063
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008064unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
8065 llvm::DenseMap<const NamedDecl *, unsigned>::const_iterator I =
8066 MangleNumbers.find(ND);
8067 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00008068}
8069
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008070MangleNumberingContext &
8071ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00008072 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
8073 MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
8074 if (!MCtx)
8075 MCtx = createMangleNumberingContext();
8076 return *MCtx;
8077}
8078
8079MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
8080 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00008081}
8082
Ted Kremenek540017e2011-10-06 05:00:56 +00008083void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8084 ParamIndices[D] = index;
8085}
8086
8087unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8088 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8089 assert(I != ParamIndices.end() &&
8090 "ParmIndices lacks entry set by ParmVarDecl");
8091 return I->second;
8092}
Fariborz Jahanian615de762013-05-28 17:37:39 +00008093
Richard Smithe6c01442013-06-05 00:46:14 +00008094APValue *
8095ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8096 bool MayCreate) {
8097 assert(E && E->getStorageDuration() == SD_Static &&
8098 "don't need to cache the computed value for this temporary");
8099 if (MayCreate)
8100 return &MaterializedTemporaryValues[E];
8101
8102 llvm::DenseMap<const MaterializeTemporaryExpr *, APValue>::iterator I =
8103 MaterializedTemporaryValues.find(E);
8104 return I == MaterializedTemporaryValues.end() ? 0 : &I->second;
8105}
8106
Fariborz Jahanian615de762013-05-28 17:37:39 +00008107bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8108 const llvm::Triple &T = getTargetInfo().getTriple();
8109 if (!T.isOSDarwin())
8110 return false;
8111
8112 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8113 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8114 uint64_t Size = sizeChars.getQuantity();
8115 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8116 unsigned Align = alignChars.getQuantity();
8117 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8118 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8119}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008120
8121namespace {
8122
8123 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8124 /// parents as defined by the \c RecursiveASTVisitor.
8125 ///
8126 /// Note that the relationship described here is purely in terms of AST
8127 /// traversal - there are other relationships (for example declaration context)
8128 /// in the AST that are better modeled by special matchers.
8129 ///
8130 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
8131 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
8132
8133 public:
8134 /// \brief Builds and returns the translation unit's parent map.
8135 ///
8136 /// The caller takes ownership of the returned \c ParentMap.
8137 static ASTContext::ParentMap *buildMap(TranslationUnitDecl &TU) {
8138 ParentMapASTVisitor Visitor(new ASTContext::ParentMap);
8139 Visitor.TraverseDecl(&TU);
8140 return Visitor.Parents;
8141 }
8142
8143 private:
8144 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8145
8146 ParentMapASTVisitor(ASTContext::ParentMap *Parents) : Parents(Parents) {
8147 }
8148
8149 bool shouldVisitTemplateInstantiations() const {
8150 return true;
8151 }
8152 bool shouldVisitImplicitCode() const {
8153 return true;
8154 }
8155 // Disables data recursion. We intercept Traverse* methods in the RAV, which
8156 // are not triggered during data recursion.
8157 bool shouldUseDataRecursionFor(clang::Stmt *S) const {
8158 return false;
8159 }
8160
8161 template <typename T>
8162 bool TraverseNode(T *Node, bool(VisitorBase:: *traverse) (T *)) {
8163 if (Node == NULL)
8164 return true;
8165 if (ParentStack.size() > 0)
8166 // FIXME: Currently we add the same parent multiple times, for example
8167 // when we visit all subexpressions of template instantiations; this is
8168 // suboptimal, bug benign: the only way to visit those is with
8169 // hasAncestor / hasParent, and those do not create new matches.
8170 // The plan is to enable DynTypedNode to be storable in a map or hash
8171 // map. The main problem there is to implement hash functions /
8172 // comparison operators for all types that DynTypedNode supports that
8173 // do not have pointer identity.
8174 (*Parents)[Node].push_back(ParentStack.back());
8175 ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node));
8176 bool Result = (this ->* traverse) (Node);
8177 ParentStack.pop_back();
8178 return Result;
8179 }
8180
8181 bool TraverseDecl(Decl *DeclNode) {
8182 return TraverseNode(DeclNode, &VisitorBase::TraverseDecl);
8183 }
8184
8185 bool TraverseStmt(Stmt *StmtNode) {
8186 return TraverseNode(StmtNode, &VisitorBase::TraverseStmt);
8187 }
8188
8189 ASTContext::ParentMap *Parents;
8190 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8191
8192 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8193 };
8194
8195} // end namespace
8196
8197ASTContext::ParentVector
8198ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
8199 assert(Node.getMemoizationData() &&
8200 "Invariant broken: only nodes that support memoization may be "
8201 "used in the parent map.");
8202 if (!AllParents) {
8203 // We always need to run over the whole translation unit, as
8204 // hasAncestor can escape any subtree.
8205 AllParents.reset(
8206 ParentMapASTVisitor::buildMap(*getTranslationUnitDecl()));
8207 }
8208 ParentMap::const_iterator I = AllParents->find(Node.getMemoizationData());
8209 if (I == AllParents->end()) {
8210 return ParentVector();
8211 }
8212 return I->second;
8213}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008214
8215bool
8216ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
8217 const ObjCMethodDecl *MethodImpl) {
8218 // No point trying to match an unavailable/deprecated mothod.
8219 if (MethodDecl->hasAttr<UnavailableAttr>()
8220 || MethodDecl->hasAttr<DeprecatedAttr>())
8221 return false;
8222 if (MethodDecl->getObjCDeclQualifier() !=
8223 MethodImpl->getObjCDeclQualifier())
8224 return false;
8225 if (!hasSameType(MethodDecl->getResultType(),
8226 MethodImpl->getResultType()))
8227 return false;
8228
8229 if (MethodDecl->param_size() != MethodImpl->param_size())
8230 return false;
8231
8232 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
8233 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
8234 EF = MethodDecl->param_end();
8235 IM != EM && IF != EF; ++IM, ++IF) {
8236 const ParmVarDecl *DeclVar = (*IF);
8237 const ParmVarDecl *ImplVar = (*IM);
8238 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
8239 return false;
8240 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
8241 return false;
8242 }
8243 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
8244
8245}