blob: f97e6e9119cca513ac6dd29d9f946684bc67e2d9 [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"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000028#include "clang/AST/RecordLayout.h"
29#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000030#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000031#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000032#include "clang/Basic/TargetInfo.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000033#include "llvm/ADT/SmallString.h"
Anders Carlssond8499822007-10-29 05:01:08 +000034#include "llvm/ADT/StringExtras.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000035#include "llvm/Support/Capacity.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000036#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000037#include "llvm/Support/raw_ostream.h"
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +000038#include <map>
Anders Carlssona4267a62009-07-18 21:19:52 +000039
Chris Lattnerddc135e2006-11-10 06:34:16 +000040using namespace clang;
41
Douglas Gregor9672f922010-07-03 00:47:00 +000042unsigned ASTContext::NumImplicitDefaultConstructors;
43unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000044unsigned ASTContext::NumImplicitCopyConstructors;
45unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000046unsigned ASTContext::NumImplicitMoveConstructors;
47unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +000048unsigned ASTContext::NumImplicitCopyAssignmentOperators;
49unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000050unsigned ASTContext::NumImplicitMoveAssignmentOperators;
51unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +000052unsigned ASTContext::NumImplicitDestructors;
53unsigned ASTContext::NumImplicitDestructorsDeclared;
54
Steve Naroff0af91202007-04-27 21:51:21 +000055enum FloatingRank {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +000056 HalfRank, FloatRank, DoubleRank, LongDoubleRank
Steve Naroff0af91202007-04-27 21:51:21 +000057};
58
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000059RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000060 if (!CommentsLoaded && ExternalSource) {
61 ExternalSource->ReadComments();
62 CommentsLoaded = true;
63 }
64
65 assert(D);
66
Dmitri Gribenkodf17d642012-06-28 16:19:39 +000067 // User can not attach documentation to implicit declarations.
68 if (D->isImplicit())
69 return NULL;
70
Dmitri Gribenkob2610882012-08-14 17:17:18 +000071 // User can not attach documentation to implicit instantiations.
72 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
73 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
74 return NULL;
75 }
76
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000077 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
78 if (VD->isStaticDataMember() &&
79 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
80 return NULL;
81 }
82
83 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
84 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
85 return NULL;
86 }
87
Dmitri Gribenko01b06512013-01-27 21:18:39 +000088 if (const ClassTemplateSpecializationDecl *CTSD =
89 dyn_cast<ClassTemplateSpecializationDecl>(D)) {
90 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
91 if (TSK == TSK_ImplicitInstantiation ||
92 TSK == TSK_Undeclared)
93 return NULL;
94 }
95
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000096 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
97 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
98 return NULL;
99 }
100
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000101 // TODO: handle comments for function parameters properly.
102 if (isa<ParmVarDecl>(D))
103 return NULL;
104
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000105 // TODO: we could look up template parameter documentation in the template
106 // documentation.
107 if (isa<TemplateTypeParmDecl>(D) ||
108 isa<NonTypeTemplateParmDecl>(D) ||
109 isa<TemplateTemplateParmDecl>(D))
110 return NULL;
111
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000112 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000113
114 // If there are no comments anywhere, we won't find anything.
115 if (RawComments.empty())
116 return NULL;
117
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000118 // Find declaration location.
119 // For Objective-C declarations we generally don't expect to have multiple
120 // declarators, thus use declaration starting location as the "declaration
121 // location".
122 // For all other declarations multiple declarators are used quite frequently,
123 // so we use the location of the identifier as the "declaration location".
124 SourceLocation DeclLoc;
125 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000126 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +0000127 isa<RedeclarableTemplateDecl>(D) ||
128 isa<ClassTemplateSpecializationDecl>(D))
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000129 DeclLoc = D->getLocStart();
130 else
131 DeclLoc = D->getLocation();
132
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000133 // If the declaration doesn't map directly to a location in a file, we
134 // can't find the comment.
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000135 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
136 return NULL;
137
138 // Find the comment that occurs just after this declaration.
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000139 ArrayRef<RawComment *>::iterator Comment;
140 {
141 // When searching for comments during parsing, the comment we are looking
142 // for is usually among the last two comments we parsed -- check them
143 // first.
144 RawComment CommentAtDeclLoc(SourceMgr, SourceRange(DeclLoc));
145 BeforeThanCompare<RawComment> Compare(SourceMgr);
146 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
147 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
148 if (!Found && RawComments.size() >= 2) {
149 MaybeBeforeDecl--;
150 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
151 }
152
153 if (Found) {
154 Comment = MaybeBeforeDecl + 1;
155 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
156 &CommentAtDeclLoc, Compare));
157 } else {
158 // Slow path.
159 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
160 &CommentAtDeclLoc, Compare);
161 }
162 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000163
164 // Decompose the location for the declaration and find the beginning of the
165 // file buffer.
166 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
167
168 // First check whether we have a trailing comment.
169 if (Comment != RawComments.end() &&
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000170 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
Dmitri Gribenko44cd7e62012-07-06 23:27:33 +0000171 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D))) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000172 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000173 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000174 // Check that Doxygen trailing comment comes after the declaration, starts
175 // on the same line and in the same file as the declaration.
176 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
177 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
178 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
179 CommentBeginDecomp.second)) {
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000180 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000181 }
182 }
183
184 // The comment just after the declaration was not a trailing comment.
185 // Let's look at the previous comment.
186 if (Comment == RawComments.begin())
187 return NULL;
188 --Comment;
189
190 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000191 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000192 return NULL;
193
194 // Decompose the end of the comment.
195 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000196 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000197
198 // If the comment and the declaration aren't in the same file, then they
199 // aren't related.
200 if (DeclLocDecomp.first != CommentEndDecomp.first)
201 return NULL;
202
203 // Get the corresponding buffer.
204 bool Invalid = false;
205 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
206 &Invalid).data();
207 if (Invalid)
208 return NULL;
209
210 // Extract text between the comment and declaration.
211 StringRef Text(Buffer + CommentEndDecomp.second,
212 DeclLocDecomp.second - CommentEndDecomp.second);
213
Dmitri Gribenko7e8729b2012-06-27 23:43:37 +0000214 // There should be no other declarations or preprocessor directives between
215 // comment and declaration.
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000216 if (Text.find_first_of(",;{}#@") != StringRef::npos)
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000217 return NULL;
218
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000219 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000220}
221
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000222namespace {
223/// If we have a 'templated' declaration for a template, adjust 'D' to
224/// refer to the actual template.
Dmitri Gribenko90631802012-08-22 17:44:32 +0000225/// If we have an implicit instantiation, adjust 'D' to refer to template.
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000226const Decl *adjustDeclToTemplate(const Decl *D) {
Douglas Gregor35ceb272012-08-13 16:37:30 +0000227 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000228 // Is this function declaration part of a function template?
Douglas Gregor35ceb272012-08-13 16:37:30 +0000229 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko90631802012-08-22 17:44:32 +0000230 return FTD;
231
232 // Nothing to do if function is not an implicit instantiation.
233 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
234 return D;
235
236 // Function is an implicit instantiation of a function template?
237 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
238 return FTD;
239
240 // Function is instantiated from a member definition of a class template?
241 if (const FunctionDecl *MemberDecl =
242 FD->getInstantiatedFromMemberFunction())
243 return MemberDecl;
244
245 return D;
Douglas Gregor35ceb272012-08-13 16:37:30 +0000246 }
Dmitri Gribenko90631802012-08-22 17:44:32 +0000247 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
248 // Static data member is instantiated from a member definition of a class
249 // template?
250 if (VD->isStaticDataMember())
251 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
252 return MemberDecl;
253
254 return D;
255 }
256 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
257 // Is this class declaration part of a class template?
258 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
259 return CTD;
260
261 // Class is an implicit instantiation of a class template or partial
262 // specialization?
263 if (const ClassTemplateSpecializationDecl *CTSD =
264 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
265 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
266 return D;
267 llvm::PointerUnion<ClassTemplateDecl *,
268 ClassTemplatePartialSpecializationDecl *>
269 PU = CTSD->getSpecializedTemplateOrPartial();
270 return PU.is<ClassTemplateDecl*>() ?
271 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
272 static_cast<const Decl*>(
273 PU.get<ClassTemplatePartialSpecializationDecl *>());
274 }
275
276 // Class is instantiated from a member definition of a class template?
277 if (const MemberSpecializationInfo *Info =
278 CRD->getMemberSpecializationInfo())
279 return Info->getInstantiatedFrom();
280
281 return D;
282 }
283 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
284 // Enum is instantiated from a member definition of a class template?
285 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
286 return MemberDecl;
287
288 return D;
289 }
290 // FIXME: Adjust alias templates?
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000291 return D;
292}
293} // unnamed namespace
294
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000295const RawComment *ASTContext::getRawCommentForAnyRedecl(
296 const Decl *D,
297 const Decl **OriginalDecl) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000298 D = adjustDeclToTemplate(D);
Douglas Gregor35ceb272012-08-13 16:37:30 +0000299
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000300 // Check whether we have cached a comment for this declaration already.
301 {
302 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
303 RedeclComments.find(D);
304 if (Pos != RedeclComments.end()) {
305 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000306 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
307 if (OriginalDecl)
308 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000309 return Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000310 }
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000311 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000312 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000313
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000314 // Search for comments attached to declarations in the redeclaration chain.
315 const RawComment *RC = NULL;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000316 const Decl *OriginalDeclForRC = NULL;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000317 for (Decl::redecl_iterator I = D->redecls_begin(),
318 E = D->redecls_end();
319 I != E; ++I) {
320 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
321 RedeclComments.find(*I);
322 if (Pos != RedeclComments.end()) {
323 const RawCommentAndCacheFlags &Raw = Pos->second;
324 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
325 RC = Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000326 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000327 break;
328 }
329 } else {
330 RC = getRawCommentForDeclNoCache(*I);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000331 OriginalDeclForRC = *I;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000332 RawCommentAndCacheFlags Raw;
333 if (RC) {
334 Raw.setRaw(RC);
335 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
336 } else
337 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000338 Raw.setOriginalDecl(*I);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000339 RedeclComments[*I] = Raw;
340 if (RC)
341 break;
342 }
343 }
344
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000345 // If we found a comment, it should be a documentation comment.
346 assert(!RC || RC->isDocumentation());
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000347
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000348 if (OriginalDecl)
349 *OriginalDecl = OriginalDeclForRC;
350
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000351 // Update cache for every declaration in the redeclaration chain.
352 RawCommentAndCacheFlags Raw;
353 Raw.setRaw(RC);
354 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000355 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000356
357 for (Decl::redecl_iterator I = D->redecls_begin(),
358 E = D->redecls_end();
359 I != E; ++I) {
360 RawCommentAndCacheFlags &R = RedeclComments[*I];
361 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
362 R = Raw;
363 }
364
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000365 return RC;
366}
367
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000368static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
369 SmallVectorImpl<const NamedDecl *> &Redeclared) {
370 const DeclContext *DC = ObjCMethod->getDeclContext();
371 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
372 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
373 if (!ID)
374 return;
375 // Add redeclared method here.
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000376 for (ObjCInterfaceDecl::known_extensions_iterator
377 Ext = ID->known_extensions_begin(),
378 ExtEnd = ID->known_extensions_end();
379 Ext != ExtEnd; ++Ext) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000380 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000381 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000382 ObjCMethod->isInstanceMethod()))
383 Redeclared.push_back(RedeclaredMethod);
384 }
385 }
386}
387
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000388comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
389 const Decl *D) const {
390 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
391 ThisDeclInfo->CommentDecl = D;
392 ThisDeclInfo->IsFilled = false;
393 ThisDeclInfo->fill();
394 ThisDeclInfo->CommentDecl = FC->getDecl();
395 comments::FullComment *CFC =
396 new (*this) comments::FullComment(FC->getBlocks(),
397 ThisDeclInfo);
398 return CFC;
399
400}
401
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000402comments::FullComment *ASTContext::getCommentForDecl(
403 const Decl *D,
404 const Preprocessor *PP) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000405 D = adjustDeclToTemplate(D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000406
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000407 const Decl *Canonical = D->getCanonicalDecl();
408 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
409 ParsedComments.find(Canonical);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000410
411 if (Pos != ParsedComments.end()) {
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000412 if (Canonical != D) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000413 comments::FullComment *FC = Pos->second;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000414 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000415 return CFC;
416 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000417 return Pos->second;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000418 }
419
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000420 const Decl *OriginalDecl;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000421
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000422 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000423 if (!RC) {
424 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000425 SmallVector<const NamedDecl*, 8> Overridden;
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000426 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000427 if (OMD && OMD->isPropertyAccessor())
428 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
429 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
430 return cloneFullComment(FC, D);
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000431 if (OMD)
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000432 addRedeclaredMethods(OMD, Overridden);
433 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000434 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
435 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
436 return cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000437 }
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000438 else if (const TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000439 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000440 // does not have one of its own.
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000441 QualType QT = TD->getUnderlyingType();
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000442 if (const TagType *TT = QT->getAs<TagType>())
443 if (const Decl *TD = TT->getDecl())
444 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000445 return cloneFullComment(FC, D);
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000446 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000447 return NULL;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000448 }
449
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000450 // If the RawComment was attached to other redeclaration of this Decl, we
451 // should parse the comment in context of that other Decl. This is important
452 // because comments can contain references to parameter names which can be
453 // different across redeclarations.
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000454 if (D != OriginalDecl)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000455 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000456
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000457 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000458 ParsedComments[Canonical] = FC;
459 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000460}
461
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000462void
463ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
464 TemplateTemplateParmDecl *Parm) {
465 ID.AddInteger(Parm->getDepth());
466 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000467 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000468
469 TemplateParameterList *Params = Parm->getTemplateParameters();
470 ID.AddInteger(Params->size());
471 for (TemplateParameterList::const_iterator P = Params->begin(),
472 PEnd = Params->end();
473 P != PEnd; ++P) {
474 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
475 ID.AddInteger(0);
476 ID.AddBoolean(TTP->isParameterPack());
477 continue;
478 }
479
480 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
481 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000482 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000483 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000484 if (NTTP->isExpandedParameterPack()) {
485 ID.AddBoolean(true);
486 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000487 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
488 QualType T = NTTP->getExpansionType(I);
489 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
490 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000491 } else
492 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000493 continue;
494 }
495
496 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
497 ID.AddInteger(2);
498 Profile(ID, TTP);
499 }
500}
501
502TemplateTemplateParmDecl *
503ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000504 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000505 // Check if we already have a canonical template template parameter.
506 llvm::FoldingSetNodeID ID;
507 CanonicalTemplateTemplateParm::Profile(ID, TTP);
508 void *InsertPos = 0;
509 CanonicalTemplateTemplateParm *Canonical
510 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
511 if (Canonical)
512 return Canonical->getParam();
513
514 // Build a canonical template parameter list.
515 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000516 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000517 CanonParams.reserve(Params->size());
518 for (TemplateParameterList::const_iterator P = Params->begin(),
519 PEnd = Params->end();
520 P != PEnd; ++P) {
521 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
522 CanonParams.push_back(
523 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000524 SourceLocation(),
525 SourceLocation(),
526 TTP->getDepth(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000527 TTP->getIndex(), 0, false,
528 TTP->isParameterPack()));
529 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000530 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
531 QualType T = getCanonicalType(NTTP->getType());
532 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
533 NonTypeTemplateParmDecl *Param;
534 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000535 SmallVector<QualType, 2> ExpandedTypes;
536 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000537 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
538 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
539 ExpandedTInfos.push_back(
540 getTrivialTypeSourceInfo(ExpandedTypes.back()));
541 }
542
543 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000544 SourceLocation(),
545 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000546 NTTP->getDepth(),
547 NTTP->getPosition(), 0,
548 T,
549 TInfo,
550 ExpandedTypes.data(),
551 ExpandedTypes.size(),
552 ExpandedTInfos.data());
553 } else {
554 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000555 SourceLocation(),
556 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000557 NTTP->getDepth(),
558 NTTP->getPosition(), 0,
559 T,
560 NTTP->isParameterPack(),
561 TInfo);
562 }
563 CanonParams.push_back(Param);
564
565 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000566 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
567 cast<TemplateTemplateParmDecl>(*P)));
568 }
569
570 TemplateTemplateParmDecl *CanonTTP
571 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
572 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000573 TTP->getPosition(),
574 TTP->isParameterPack(),
575 0,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000576 TemplateParameterList::Create(*this, SourceLocation(),
577 SourceLocation(),
578 CanonParams.data(),
579 CanonParams.size(),
580 SourceLocation()));
581
582 // Get the new insert position for the node we care about.
583 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
584 assert(Canonical == 0 && "Shouldn't be in the map!");
585 (void)Canonical;
586
587 // Create the canonical template template parameter entry.
588 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
589 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
590 return CanonTTP;
591}
592
Charles Davis53c59df2010-08-16 03:33:14 +0000593CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000594 if (!LangOpts.CPlusPlus) return 0;
595
John McCall359b8852013-01-25 22:30:49 +0000596 switch (T.getCXXABI().getKind()) {
597 case TargetCXXABI::GenericARM:
598 case TargetCXXABI::iOS:
John McCall86353412010-08-21 22:46:04 +0000599 return CreateARMCXXABI(*this);
Tim Northover9bb857a2013-01-31 12:13:10 +0000600 case TargetCXXABI::GenericAArch64: // Same as Itanium at this level
John McCall359b8852013-01-25 22:30:49 +0000601 case TargetCXXABI::GenericItanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000602 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000603 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000604 return CreateMicrosoftCXXABI(*this);
605 }
David Blaikie8a40f702012-01-17 06:56:22 +0000606 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000607}
608
Douglas Gregore8bbc122011-09-02 00:18:52 +0000609static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000610 const LangOptions &LOpts) {
611 if (LOpts.FakeAddressSpaceMap) {
612 // The fake address space map must have a distinct entry for each
613 // language-specific address space.
614 static const unsigned FakeAddrSpaceMap[] = {
615 1, // opencl_global
616 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000617 3, // opencl_constant
618 4, // cuda_device
619 5, // cuda_constant
620 6 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000621 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000622 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000623 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000624 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000625 }
626}
627
Douglas Gregor7018d5b2011-09-01 20:23:19 +0000628ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000629 const TargetInfo *t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000630 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000631 Builtin::Context &builtins,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000632 unsigned size_reserve,
633 bool DelayInitialization)
634 : FunctionProtoTypes(this_()),
635 TemplateSpecializationTypes(this_()),
636 DependentTemplateSpecializationTypes(this_()),
637 SubstTemplateTemplateParmPacks(this_()),
638 GlobalNestedNameSpecifier(0),
639 Int128Decl(0), UInt128Decl(0),
Meador Inge5d3fb222012-06-16 03:34:49 +0000640 BuiltinVaListDecl(0),
Douglas Gregord53ae832012-01-17 18:09:05 +0000641 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Fariborz Jahanianf2578572012-08-30 18:49:41 +0000642 BOOLDecl(0),
Douglas Gregorbab8a962011-09-08 01:46:34 +0000643 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000644 FILEDecl(0),
Rafael Espindola6cfa82b2011-11-13 21:51:09 +0000645 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
646 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
647 cudaConfigureCallDecl(0),
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000648 NullTypeSourceInfo(QualType()),
649 FirstLocalImport(), LastLocalImport(),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000650 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000651 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000652 Idents(idents), Selectors(sels),
653 BuiltinInfo(builtins),
654 DeclarationNames(*this),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000655 ExternalSource(0), Listener(0),
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000656 Comments(SM), CommentsLoaded(false),
Dmitri Gribenko7acbf002012-09-10 20:32:42 +0000657 CommentCommandTraits(BumpAlloc),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000658 LastSDM(0, 0),
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +0000659 UniqueBlockByRefTypeID(0)
Douglas Gregore8bbc122011-09-02 00:18:52 +0000660{
Mike Stump11289f42009-09-09 15:08:12 +0000661 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000662 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000663
664 if (!DelayInitialization) {
665 assert(t && "No target supplied for ASTContext initialization");
666 InitBuiltinTypes(*t);
667 }
Daniel Dunbar221fa942008-08-11 04:54:23 +0000668}
669
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000670ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000671 // Release the DenseMaps associated with DeclContext objects.
672 // FIXME: Is this the ideal solution?
673 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000674
Douglas Gregor5b11d492010-07-25 17:53:33 +0000675 // Call all of the deallocation functions.
676 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
677 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor1a809332010-05-23 18:26:36 +0000678
Ted Kremenek076baeb2010-06-08 23:00:58 +0000679 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000680 // because they can contain DenseMaps.
681 for (llvm::DenseMap<const ObjCContainerDecl*,
682 const ASTRecordLayout*>::iterator
683 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
684 // Increment in loop to prevent using deallocated memory.
685 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
686 R->Destroy(*this);
687
Ted Kremenek076baeb2010-06-08 23:00:58 +0000688 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
689 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
690 // Increment in loop to prevent using deallocated memory.
691 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
692 R->Destroy(*this);
693 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000694
695 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
696 AEnd = DeclAttrs.end();
697 A != AEnd; ++A)
698 A->second->~AttrVec();
699}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000700
Douglas Gregor1a809332010-05-23 18:26:36 +0000701void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
702 Deallocations.push_back(std::make_pair(Callback, Data));
703}
704
Mike Stump11289f42009-09-09 15:08:12 +0000705void
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000706ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000707 ExternalSource.reset(Source.take());
708}
709
Chris Lattner4eb445d2007-01-26 01:27:23 +0000710void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000711 llvm::errs() << "\n*** AST Context Stats:\n";
712 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000713
Douglas Gregora30d0462009-05-26 14:40:08 +0000714 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000715#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000716#define ABSTRACT_TYPE(Name, Parent)
717#include "clang/AST/TypeNodes.def"
718 0 // Extra
719 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000720
Chris Lattner4eb445d2007-01-26 01:27:23 +0000721 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
722 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000723 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000724 }
725
Douglas Gregora30d0462009-05-26 14:40:08 +0000726 unsigned Idx = 0;
727 unsigned TotalBytes = 0;
728#define TYPE(Name, Parent) \
729 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000730 llvm::errs() << " " << counts[Idx] << " " << #Name \
731 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000732 TotalBytes += counts[Idx] * sizeof(Name##Type); \
733 ++Idx;
734#define ABSTRACT_TYPE(Name, Parent)
735#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000736
Chandler Carruth3c147a72011-07-04 05:32:14 +0000737 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
738
Douglas Gregor7454c562010-07-02 20:37:36 +0000739 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000740 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
741 << NumImplicitDefaultConstructors
742 << " implicit default constructors created\n";
743 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
744 << NumImplicitCopyConstructors
745 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000746 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000747 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
748 << NumImplicitMoveConstructors
749 << " implicit move constructors created\n";
750 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
751 << NumImplicitCopyAssignmentOperators
752 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000753 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000754 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
755 << NumImplicitMoveAssignmentOperators
756 << " implicit move assignment operators created\n";
757 llvm::errs() << NumImplicitDestructorsDeclared << "/"
758 << NumImplicitDestructors
759 << " implicit destructors created\n";
760
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000761 if (ExternalSource.get()) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000762 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000763 ExternalSource->PrintStats();
764 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000765
Douglas Gregor5b11d492010-07-25 17:53:33 +0000766 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000767}
768
Douglas Gregor801c99d2011-08-12 06:49:56 +0000769TypedefDecl *ASTContext::getInt128Decl() const {
770 if (!Int128Decl) {
771 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
772 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
773 getTranslationUnitDecl(),
774 SourceLocation(),
775 SourceLocation(),
776 &Idents.get("__int128_t"),
777 TInfo);
778 }
779
780 return Int128Decl;
781}
782
783TypedefDecl *ASTContext::getUInt128Decl() const {
784 if (!UInt128Decl) {
785 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
786 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
787 getTranslationUnitDecl(),
788 SourceLocation(),
789 SourceLocation(),
790 &Idents.get("__uint128_t"),
791 TInfo);
792 }
793
794 return UInt128Decl;
795}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000796
John McCall48f2d582009-10-23 23:03:21 +0000797void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000798 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000799 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000800 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000801}
802
Douglas Gregore8bbc122011-09-02 00:18:52 +0000803void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
804 assert((!this->Target || this->Target == &Target) &&
805 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000806 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000807
Douglas Gregore8bbc122011-09-02 00:18:52 +0000808 this->Target = &Target;
809
810 ABI.reset(createCXXABI(Target));
811 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
812
Chris Lattner970e54e2006-11-12 00:37:36 +0000813 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000814 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000815
Chris Lattner970e54e2006-11-12 00:37:36 +0000816 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000817 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000818 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000819 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000820 InitBuiltinType(CharTy, BuiltinType::Char_S);
821 else
822 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000823 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000824 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
825 InitBuiltinType(ShortTy, BuiltinType::Short);
826 InitBuiltinType(IntTy, BuiltinType::Int);
827 InitBuiltinType(LongTy, BuiltinType::Long);
828 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000829
Chris Lattner970e54e2006-11-12 00:37:36 +0000830 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000831 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
832 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
833 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
834 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
835 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000836
Chris Lattner970e54e2006-11-12 00:37:36 +0000837 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000838 InitBuiltinType(FloatTy, BuiltinType::Float);
839 InitBuiltinType(DoubleTy, BuiltinType::Double);
840 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000841
Chris Lattnerf122cef2009-04-30 02:43:43 +0000842 // GNU extension, 128-bit integers.
843 InitBuiltinType(Int128Ty, BuiltinType::Int128);
844 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
845
Abramo Bagnara06782942012-09-09 10:13:32 +0000846 if (LangOpts.CPlusPlus && LangOpts.WChar) { // C++ 3.9.1p5
Eli Friedman786d0872011-04-30 19:24:24 +0000847 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattnerad3467e2010-12-25 23:25:43 +0000848 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
849 else // -fshort-wchar makes wchar_t be unsigned.
850 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
Abramo Bagnara06782942012-09-09 10:13:32 +0000851 } else // C99 (or C++ using -fno-wchar)
Chris Lattner007cb022009-02-26 23:43:47 +0000852 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000853
James Molloy36365542012-05-04 10:55:22 +0000854 WIntTy = getFromTargetType(Target.getWIntType());
855
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000856 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
857 InitBuiltinType(Char16Ty, BuiltinType::Char16);
858 else // C99
859 Char16Ty = getFromTargetType(Target.getChar16Type());
860
861 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
862 InitBuiltinType(Char32Ty, BuiltinType::Char32);
863 else // C99
864 Char32Ty = getFromTargetType(Target.getChar32Type());
865
Douglas Gregor4619e432008-12-05 23:32:09 +0000866 // Placeholder type for type-dependent expressions whose type is
867 // completely unknown. No code should ever check a type against
868 // DependentTy and users should never see it; however, it is here to
869 // help diagnose failures to properly check for type-dependent
870 // expressions.
871 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000872
John McCall36e7fe32010-10-12 00:20:44 +0000873 // Placeholder type for functions.
874 InitBuiltinType(OverloadTy, BuiltinType::Overload);
875
John McCall0009fcc2011-04-26 20:42:42 +0000876 // Placeholder type for bound members.
877 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
878
John McCall526ab472011-10-25 17:37:35 +0000879 // Placeholder type for pseudo-objects.
880 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
881
John McCall31996342011-04-07 08:22:57 +0000882 // "any" type; useful for debugger-like clients.
883 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
884
John McCall8a6b59a2011-10-17 18:09:15 +0000885 // Placeholder type for unbridged ARC casts.
886 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
887
Eli Friedman34866c72012-08-31 00:14:07 +0000888 // Placeholder type for builtin functions.
889 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
890
Chris Lattner970e54e2006-11-12 00:37:36 +0000891 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000892 FloatComplexTy = getComplexType(FloatTy);
893 DoubleComplexTy = getComplexType(DoubleTy);
894 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000895
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000896 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000897 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
898 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000899 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000900
901 if (LangOpts.OpenCL) {
902 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
903 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
904 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
905 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
906 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
907 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +0000908
909 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000910 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000911
912 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +0000913 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
914 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000915
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000916 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +0000917
918 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000919
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000920 // void * type
921 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000922
923 // nullptr type (C++0x 2.14.7)
924 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000925
926 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
927 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +0000928
929 // Builtin type used to help define __builtin_va_list.
930 VaListTagTy = QualType();
Chris Lattner970e54e2006-11-12 00:37:36 +0000931}
932
David Blaikie9c902b52011-09-25 23:23:43 +0000933DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000934 return SourceMgr.getDiagnostics();
935}
936
Douglas Gregor561eceb2010-08-30 16:49:28 +0000937AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
938 AttrVec *&Result = DeclAttrs[D];
939 if (!Result) {
940 void *Mem = Allocate(sizeof(AttrVec));
941 Result = new (Mem) AttrVec;
942 }
943
944 return *Result;
945}
946
947/// \brief Erase the attributes corresponding to the given declaration.
948void ASTContext::eraseDeclAttrs(const Decl *D) {
949 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
950 if (Pos != DeclAttrs.end()) {
951 Pos->second->~AttrVec();
952 DeclAttrs.erase(Pos);
953 }
954}
955
Douglas Gregor86d142a2009-10-08 07:24:58 +0000956MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000957ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000958 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000959 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000960 = InstantiatedFromStaticDataMember.find(Var);
961 if (Pos == InstantiatedFromStaticDataMember.end())
962 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000963
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000964 return Pos->second;
965}
966
Mike Stump11289f42009-09-09 15:08:12 +0000967void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000968ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000969 TemplateSpecializationKind TSK,
970 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000971 assert(Inst->isStaticDataMember() && "Not a static data member");
972 assert(Tmpl->isStaticDataMember() && "Not a static data member");
973 assert(!InstantiatedFromStaticDataMember[Inst] &&
974 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000975 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000976 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000977}
978
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000979FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
980 const FunctionDecl *FD){
981 assert(FD && "Specialization is 0");
982 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +0000983 = ClassScopeSpecializationPattern.find(FD);
984 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000985 return 0;
986
987 return Pos->second;
988}
989
990void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
991 FunctionDecl *Pattern) {
992 assert(FD && "Specialization is 0");
993 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +0000994 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000995}
996
John McCalle61f2ba2009-11-18 02:36:19 +0000997NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000998ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000999 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +00001000 = InstantiatedFromUsingDecl.find(UUD);
1001 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001002 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001003
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001004 return Pos->second;
1005}
1006
1007void
John McCallb96ec562009-12-04 22:46:56 +00001008ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1009 assert((isa<UsingDecl>(Pattern) ||
1010 isa<UnresolvedUsingValueDecl>(Pattern) ||
1011 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1012 "pattern decl is not a using decl");
1013 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1014 InstantiatedFromUsingDecl[Inst] = Pattern;
1015}
1016
1017UsingShadowDecl *
1018ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1019 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1020 = InstantiatedFromUsingShadowDecl.find(Inst);
1021 if (Pos == InstantiatedFromUsingShadowDecl.end())
1022 return 0;
1023
1024 return Pos->second;
1025}
1026
1027void
1028ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1029 UsingShadowDecl *Pattern) {
1030 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1031 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001032}
1033
Anders Carlsson5da84842009-09-01 04:26:58 +00001034FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1035 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1036 = InstantiatedFromUnnamedFieldDecl.find(Field);
1037 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1038 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001039
Anders Carlsson5da84842009-09-01 04:26:58 +00001040 return Pos->second;
1041}
1042
1043void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1044 FieldDecl *Tmpl) {
1045 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1046 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1047 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1048 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001049
Anders Carlsson5da84842009-09-01 04:26:58 +00001050 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1051}
1052
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +00001053bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
1054 const FieldDecl *LastFD) const {
1055 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001056 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +00001057}
1058
Fariborz Jahanianeb397412011-05-02 17:20:56 +00001059bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
1060 const FieldDecl *LastFD) const {
1061 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001062 FD->getBitWidthValue(*this) == 0 &&
1063 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanianeb397412011-05-02 17:20:56 +00001064}
1065
Fariborz Jahanian84335f72011-05-04 18:51:37 +00001066bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
1067 const FieldDecl *LastFD) const {
1068 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001069 FD->getBitWidthValue(*this) &&
1070 LastFD->getBitWidthValue(*this));
Fariborz Jahanian84335f72011-05-04 18:51:37 +00001071}
1072
Chad Rosierf01a7dd2011-08-04 23:34:15 +00001073bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +00001074 const FieldDecl *LastFD) const {
1075 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001076 LastFD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +00001077}
1078
Chad Rosierf01a7dd2011-08-04 23:34:15 +00001079bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +00001080 const FieldDecl *LastFD) const {
1081 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001082 FD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +00001083}
1084
Douglas Gregor832940b2010-03-02 23:58:15 +00001085ASTContext::overridden_cxx_method_iterator
1086ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1087 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001088 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001089 if (Pos == OverriddenMethods.end())
1090 return 0;
1091
1092 return Pos->second.begin();
1093}
1094
1095ASTContext::overridden_cxx_method_iterator
1096ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1097 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001098 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001099 if (Pos == OverriddenMethods.end())
1100 return 0;
1101
1102 return Pos->second.end();
1103}
1104
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001105unsigned
1106ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1107 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001108 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001109 if (Pos == OverriddenMethods.end())
1110 return 0;
1111
1112 return Pos->second.size();
1113}
1114
Douglas Gregor832940b2010-03-02 23:58:15 +00001115void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1116 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001117 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001118 OverriddenMethods[Method].push_back(Overridden);
1119}
1120
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001121void ASTContext::getOverriddenMethods(
1122 const NamedDecl *D,
1123 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001124 assert(D);
1125
1126 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001127 Overridden.append(CXXMethod->begin_overridden_methods(),
1128 CXXMethod->end_overridden_methods());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001129 return;
1130 }
1131
1132 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1133 if (!Method)
1134 return;
1135
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001136 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1137 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001138 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001139}
1140
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001141void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1142 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1143 assert(!Import->isFromASTFile() && "Non-local import declaration");
1144 if (!FirstLocalImport) {
1145 FirstLocalImport = Import;
1146 LastLocalImport = Import;
1147 return;
1148 }
1149
1150 LastLocalImport->NextLocalImport = Import;
1151 LastLocalImport = Import;
1152}
1153
Chris Lattner53cfe802007-07-18 17:52:12 +00001154//===----------------------------------------------------------------------===//
1155// Type Sizing and Analysis
1156//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001157
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001158/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1159/// scalar floating point type.
1160const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001161 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001162 assert(BT && "Not a floating point type!");
1163 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001164 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001165 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001166 case BuiltinType::Float: return Target->getFloatFormat();
1167 case BuiltinType::Double: return Target->getDoubleFormat();
1168 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001169 }
1170}
1171
Ken Dyck160146e2010-01-27 17:10:57 +00001172/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +00001173/// specified decl. Note that bitfields do not have a valid alignment, so
1174/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001175/// If @p RefAsPointee, references are treated like their underlying type
1176/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad39c79802011-01-12 09:06:06 +00001177CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001178 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001179
John McCall94268702010-10-08 18:24:19 +00001180 bool UseAlignAttrOnly = false;
1181 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1182 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001183
John McCall94268702010-10-08 18:24:19 +00001184 // __attribute__((aligned)) can increase or decrease alignment
1185 // *except* on a struct or struct member, where it only increases
1186 // alignment unless 'packed' is also specified.
1187 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001188 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001189 // ignore that possibility; Sema should diagnose it.
1190 if (isa<FieldDecl>(D)) {
1191 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1192 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1193 } else {
1194 UseAlignAttrOnly = true;
1195 }
1196 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001197 else if (isa<FieldDecl>(D))
1198 UseAlignAttrOnly =
1199 D->hasAttr<PackedAttr>() ||
1200 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001201
John McCall4e819612011-01-20 07:57:12 +00001202 // If we're using the align attribute only, just ignore everything
1203 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001204 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001205 // do nothing
1206
John McCall94268702010-10-08 18:24:19 +00001207 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001208 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001209 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001210 if (RefAsPointee)
1211 T = RT->getPointeeType();
1212 else
1213 T = getPointerType(RT->getPointeeType());
1214 }
1215 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +00001216 // Adjust alignments of declarations with array type by the
1217 // large-array alignment on the target.
Douglas Gregore8bbc122011-09-02 00:18:52 +00001218 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall33ddac02011-01-19 10:06:00 +00001219 const ArrayType *arrayType;
1220 if (MinWidth && (arrayType = getAsArrayType(T))) {
1221 if (isa<VariableArrayType>(arrayType))
Douglas Gregore8bbc122011-09-02 00:18:52 +00001222 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall33ddac02011-01-19 10:06:00 +00001223 else if (isa<ConstantArrayType>(arrayType) &&
1224 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregore8bbc122011-09-02 00:18:52 +00001225 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedman19a546c2009-02-22 02:56:25 +00001226
John McCall33ddac02011-01-19 10:06:00 +00001227 // Walk through any array types while we're at it.
1228 T = getBaseElementType(arrayType);
1229 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001230 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedman19a546c2009-02-22 02:56:25 +00001231 }
John McCall4e819612011-01-20 07:57:12 +00001232
1233 // Fields can be subject to extra alignment constraints, like if
1234 // the field is packed, the struct is packed, or the struct has a
1235 // a max-field-alignment constraint (#pragma pack). So calculate
1236 // the actual alignment of the field within the struct, and then
1237 // (as we're expected to) constrain that by the alignment of the type.
1238 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
1239 // So calculate the alignment of the field.
1240 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
1241
1242 // Start with the record's overall alignment.
Ken Dyck7ad11e72011-02-15 02:32:40 +00001243 unsigned fieldAlign = toBits(layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001244
1245 // Use the GCD of that and the offset within the record.
1246 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
1247 if (offset > 0) {
1248 // Alignment is always a power of 2, so the GCD will be a power of 2,
1249 // which means we get to do this crazy thing instead of Euclid's.
1250 uint64_t lowBitOfOffset = offset & (~offset + 1);
1251 if (lowBitOfOffset < fieldAlign)
1252 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
1253 }
1254
1255 Align = std::min(Align, fieldAlign);
Charles Davis3fc51072010-02-23 04:52:00 +00001256 }
Chris Lattner68061312009-01-24 21:53:27 +00001257 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001258
Ken Dyckcc56c542011-01-15 18:38:59 +00001259 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001260}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001261
John McCallf1249922012-08-21 04:10:00 +00001262// getTypeInfoDataSizeInChars - Return the size of a type, in
1263// chars. If the type is a record, its data size is returned. This is
1264// the size of the memcpy that's performed when assigning this type
1265// using a trivial copy/move assignment operator.
1266std::pair<CharUnits, CharUnits>
1267ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1268 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1269
1270 // In C++, objects can sometimes be allocated into the tail padding
1271 // of a base-class subobject. We decide whether that's possible
1272 // during class layout, so here we can just trust the layout results.
1273 if (getLangOpts().CPlusPlus) {
1274 if (const RecordType *RT = T->getAs<RecordType>()) {
1275 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1276 sizeAndAlign.first = layout.getDataSize();
1277 }
1278 }
1279
1280 return sizeAndAlign;
1281}
1282
John McCall87fe5d52010-05-20 01:18:31 +00001283std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001284ASTContext::getTypeInfoInChars(const Type *T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001285 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +00001286 return std::make_pair(toCharUnitsFromBits(Info.first),
1287 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +00001288}
1289
1290std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001291ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001292 return getTypeInfoInChars(T.getTypePtr());
1293}
1294
Daniel Dunbarc6475872012-03-09 04:12:54 +00001295std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1296 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1297 if (it != MemoizedTypeInfo.end())
1298 return it->second;
1299
1300 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1301 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1302 return Info;
1303}
1304
1305/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1306/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001307///
1308/// FIXME: Pointers into different addr spaces could have different sizes and
1309/// alignment requirements: getPointerInfo should take an AddrSpace, this
1310/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +00001311std::pair<uint64_t, unsigned>
Daniel Dunbarc6475872012-03-09 04:12:54 +00001312ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +00001313 uint64_t Width=0;
1314 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001315 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001316#define TYPE(Class, Base)
1317#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001318#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001319#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1320#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001321 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001322
Chris Lattner355332d2007-07-13 22:27:08 +00001323 case Type::FunctionNoProto:
1324 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001325 // GCC extension: alignof(function) = 32 bits
1326 Width = 0;
1327 Align = 32;
1328 break;
1329
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001330 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001331 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001332 Width = 0;
1333 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1334 break;
1335
Steve Naroff5c131802007-08-30 01:06:46 +00001336 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001337 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001338
Chris Lattner37e05872008-03-05 18:54:05 +00001339 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001340 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarc6475872012-03-09 04:12:54 +00001341 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1342 "Overflow in array type bit size evaluation");
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001343 Width = EltInfo.first*Size;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001344 Align = EltInfo.second;
Argyrios Kyrtzidisae40e4e2011-04-26 21:05:39 +00001345 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001346 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001347 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001348 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001349 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001350 const VectorType *VT = cast<VectorType>(T);
1351 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1352 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001353 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001354 // If the alignment is not a power of 2, round up to the next power of 2.
1355 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001356 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001357 Align = llvm::NextPowerOf2(Align);
1358 Width = llvm::RoundUpToAlignment(Width, Align);
1359 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001360 // Adjust the alignment based on the target max.
1361 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1362 if (TargetVectorAlign && TargetVectorAlign < Align)
1363 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001364 break;
1365 }
Chris Lattner647fb222007-07-18 18:26:58 +00001366
Chris Lattner7570e9c2008-03-08 08:52:55 +00001367 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001368 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001369 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001370 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001371 // GCC extension: alignof(void) = 8 bits.
1372 Width = 0;
1373 Align = 8;
1374 break;
1375
Chris Lattner6a4f7452007-12-19 19:23:28 +00001376 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001377 Width = Target->getBoolWidth();
1378 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001379 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001380 case BuiltinType::Char_S:
1381 case BuiltinType::Char_U:
1382 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001383 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001384 Width = Target->getCharWidth();
1385 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001386 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001387 case BuiltinType::WChar_S:
1388 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001389 Width = Target->getWCharWidth();
1390 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001391 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001392 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001393 Width = Target->getChar16Width();
1394 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001395 break;
1396 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001397 Width = Target->getChar32Width();
1398 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001399 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001400 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001401 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001402 Width = Target->getShortWidth();
1403 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001404 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001405 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001406 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001407 Width = Target->getIntWidth();
1408 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001409 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001410 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001411 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001412 Width = Target->getLongWidth();
1413 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001414 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001415 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001416 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001417 Width = Target->getLongLongWidth();
1418 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001419 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001420 case BuiltinType::Int128:
1421 case BuiltinType::UInt128:
1422 Width = 128;
1423 Align = 128; // int128_t is 128-bit aligned on all targets.
1424 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001425 case BuiltinType::Half:
1426 Width = Target->getHalfWidth();
1427 Align = Target->getHalfAlign();
1428 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001429 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001430 Width = Target->getFloatWidth();
1431 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001432 break;
1433 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001434 Width = Target->getDoubleWidth();
1435 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001436 break;
1437 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001438 Width = Target->getLongDoubleWidth();
1439 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001440 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001441 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001442 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1443 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001444 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001445 case BuiltinType::ObjCId:
1446 case BuiltinType::ObjCClass:
1447 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001448 Width = Target->getPointerWidth(0);
1449 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001450 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001451 case BuiltinType::OCLEvent:
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001452 case BuiltinType::OCLImage1d:
1453 case BuiltinType::OCLImage1dArray:
1454 case BuiltinType::OCLImage1dBuffer:
1455 case BuiltinType::OCLImage2d:
1456 case BuiltinType::OCLImage2dArray:
1457 case BuiltinType::OCLImage3d:
1458 // Currently these types are pointers to opaque types.
1459 Width = Target->getPointerWidth(0);
1460 Align = Target->getPointerAlign(0);
1461 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001462 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001463 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001464 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001465 Width = Target->getPointerWidth(0);
1466 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001467 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001468 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001469 unsigned AS = getTargetAddressSpace(
1470 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001471 Width = Target->getPointerWidth(AS);
1472 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001473 break;
1474 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001475 case Type::LValueReference:
1476 case Type::RValueReference: {
1477 // alignof and sizeof should never enter this code path here, so we go
1478 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001479 unsigned AS = getTargetAddressSpace(
1480 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001481 Width = Target->getPointerWidth(AS);
1482 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001483 break;
1484 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001485 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001486 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001487 Width = Target->getPointerWidth(AS);
1488 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001489 break;
1490 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001491 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001492 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001493 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +00001494 getTypeInfo(getPointerDiffType());
Charles Davis53c59df2010-08-16 03:33:14 +00001495 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001496 Align = PtrDiffInfo.second;
1497 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001498 }
Chris Lattner647fb222007-07-18 18:26:58 +00001499 case Type::Complex: {
1500 // Complex types have the same alignment as their elements, but twice the
1501 // size.
Mike Stump11289f42009-09-09 15:08:12 +00001502 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +00001503 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +00001504 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +00001505 Align = EltInfo.second;
1506 break;
1507 }
John McCall8b07ec22010-05-15 11:32:37 +00001508 case Type::ObjCObject:
1509 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001510 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001511 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001512 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001513 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001514 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001515 break;
1516 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001517 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001518 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001519 const TagType *TT = cast<TagType>(T);
1520
1521 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001522 Width = 8;
1523 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001524 break;
1525 }
Mike Stump11289f42009-09-09 15:08:12 +00001526
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001527 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +00001528 return getTypeInfo(ET->getDecl()->getIntegerType());
1529
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001530 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +00001531 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001532 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001533 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +00001534 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001535 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001536
Chris Lattner63d2b362009-10-22 05:17:15 +00001537 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001538 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1539 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001540
Richard Smith30482bc2011-02-20 03:19:35 +00001541 case Type::Auto: {
1542 const AutoType *A = cast<AutoType>(T);
1543 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001544 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001545 }
1546
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001547 case Type::Paren:
1548 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1549
Douglas Gregoref462e62009-04-30 17:32:17 +00001550 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001551 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +00001552 std::pair<uint64_t, unsigned> Info
1553 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001554 // If the typedef has an aligned attribute on it, it overrides any computed
1555 // alignment we have. This violates the GCC documentation (which says that
1556 // attribute(aligned) can only round up) but matches its implementation.
1557 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1558 Align = AttrAlign;
1559 else
1560 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +00001561 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +00001562 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001563 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001564
1565 case Type::TypeOfExpr:
1566 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1567 .getTypePtr());
1568
1569 case Type::TypeOf:
1570 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1571
Anders Carlsson81df7b82009-06-24 19:06:50 +00001572 case Type::Decltype:
1573 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1574 .getTypePtr());
1575
Alexis Hunte852b102011-05-24 22:41:36 +00001576 case Type::UnaryTransform:
1577 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1578
Abramo Bagnara6150c882010-05-11 21:36:43 +00001579 case Type::Elaborated:
1580 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001581
John McCall81904512011-01-06 01:58:22 +00001582 case Type::Attributed:
1583 return getTypeInfo(
1584 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1585
Richard Smith3f1b5d02011-05-05 21:57:07 +00001586 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00001587 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +00001588 "Cannot request the size of a dependent type");
Richard Smith3f1b5d02011-05-05 21:57:07 +00001589 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1590 // A type alias template specialization may refer to a typedef with the
1591 // aligned attribute on it.
1592 if (TST->isTypeAlias())
1593 return getTypeInfo(TST->getAliasedType().getTypePtr());
1594 else
1595 return getTypeInfo(getCanonicalType(T));
1596 }
1597
Eli Friedman0dfb8892011-10-06 23:00:33 +00001598 case Type::Atomic: {
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001599 std::pair<uint64_t, unsigned> Info
1600 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1601 Width = Info.first;
1602 Align = Info.second;
1603 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1604 llvm::isPowerOf2_64(Width)) {
1605 // We can potentially perform lock-free atomic operations for this
1606 // type; promote the alignment appropriately.
1607 // FIXME: We could potentially promote the width here as well...
1608 // is that worthwhile? (Non-struct atomic types generally have
1609 // power-of-two size anyway, but structs might not. Requires a bit
1610 // of implementation work to make sure we zero out the extra bits.)
1611 Align = static_cast<unsigned>(Width);
1612 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001613 }
1614
Douglas Gregoref462e62009-04-30 17:32:17 +00001615 }
Mike Stump11289f42009-09-09 15:08:12 +00001616
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001617 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +00001618 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001619}
1620
Ken Dyckcc56c542011-01-15 18:38:59 +00001621/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1622CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1623 return CharUnits::fromQuantity(BitSize / getCharWidth());
1624}
1625
Ken Dyckb0fcc592011-02-11 01:54:29 +00001626/// toBits - Convert a size in characters to a size in characters.
1627int64_t ASTContext::toBits(CharUnits CharSize) const {
1628 return CharSize.getQuantity() * getCharWidth();
1629}
1630
Ken Dyck8c89d592009-12-22 14:23:30 +00001631/// getTypeSizeInChars - Return the size of the specified type, in characters.
1632/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001633CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001634 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001635}
Jay Foad39c79802011-01-12 09:06:06 +00001636CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001637 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001638}
1639
Ken Dycka6046ab2010-01-26 17:25:18 +00001640/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001641/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001642CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001643 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001644}
Jay Foad39c79802011-01-12 09:06:06 +00001645CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001646 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001647}
1648
Chris Lattnera3402cd2009-01-27 18:08:34 +00001649/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1650/// type for the current target in bits. This can be different than the ABI
1651/// alignment in cases where it is beneficial for performance to overalign
1652/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001653unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +00001654 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +00001655
1656 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +00001657 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001658 T = CT->getElementType().getTypePtr();
1659 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001660 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1661 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman7ab09572009-05-25 21:27:19 +00001662 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1663
Chris Lattnera3402cd2009-01-27 18:08:34 +00001664 return ABIAlign;
1665}
1666
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001667/// DeepCollectObjCIvars -
1668/// This routine first collects all declared, but not synthesized, ivars in
1669/// super class and then collects all ivars, including those synthesized for
1670/// current class. This routine is used for implementation of current class
1671/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001672///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001673void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1674 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001675 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001676 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1677 DeepCollectObjCIvars(SuperClass, false, Ivars);
1678 if (!leafClass) {
1679 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1680 E = OI->ivar_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001681 Ivars.push_back(*I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001682 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001683 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001684 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001685 Iv= Iv->getNextIvar())
1686 Ivars.push_back(Iv);
1687 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001688}
1689
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001690/// CollectInheritedProtocols - Collect all protocols in current class and
1691/// those inherited by it.
1692void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001693 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001694 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001695 // We can use protocol_iterator here instead of
1696 // all_referenced_protocol_iterator since we are walking all categories.
1697 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1698 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001699 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001700 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001701 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001702 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001703 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001704 CollectInheritedProtocols(*P, Protocols);
1705 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001706 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001707
1708 // Categories of this Interface.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001709 for (ObjCInterfaceDecl::visible_categories_iterator
1710 Cat = OI->visible_categories_begin(),
1711 CatEnd = OI->visible_categories_end();
1712 Cat != CatEnd; ++Cat) {
1713 CollectInheritedProtocols(*Cat, Protocols);
1714 }
1715
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001716 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1717 while (SD) {
1718 CollectInheritedProtocols(SD, Protocols);
1719 SD = SD->getSuperClass();
1720 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001721 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001722 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001723 PE = OC->protocol_end(); P != PE; ++P) {
1724 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001725 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001726 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1727 PE = Proto->protocol_end(); P != PE; ++P)
1728 CollectInheritedProtocols(*P, Protocols);
1729 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001730 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001731 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1732 PE = OP->protocol_end(); P != PE; ++P) {
1733 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001734 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001735 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1736 PE = Proto->protocol_end(); P != PE; ++P)
1737 CollectInheritedProtocols(*P, Protocols);
1738 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001739 }
1740}
1741
Jay Foad39c79802011-01-12 09:06:06 +00001742unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001743 unsigned count = 0;
1744 // Count ivars declared in class extension.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001745 for (ObjCInterfaceDecl::known_extensions_iterator
1746 Ext = OI->known_extensions_begin(),
1747 ExtEnd = OI->known_extensions_end();
1748 Ext != ExtEnd; ++Ext) {
1749 count += Ext->ivar_size();
1750 }
1751
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001752 // Count ivar defined in this class's implementation. This
1753 // includes synthesized ivars.
1754 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001755 count += ImplDecl->ivar_size();
1756
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001757 return count;
1758}
1759
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001760bool ASTContext::isSentinelNullExpr(const Expr *E) {
1761 if (!E)
1762 return false;
1763
1764 // nullptr_t is always treated as null.
1765 if (E->getType()->isNullPtrType()) return true;
1766
1767 if (E->getType()->isAnyPointerType() &&
1768 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1769 Expr::NPC_ValueDependentIsNull))
1770 return true;
1771
1772 // Unfortunately, __null has type 'int'.
1773 if (isa<GNUNullExpr>(E)) return true;
1774
1775 return false;
1776}
1777
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001778/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1779ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1780 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1781 I = ObjCImpls.find(D);
1782 if (I != ObjCImpls.end())
1783 return cast<ObjCImplementationDecl>(I->second);
1784 return 0;
1785}
1786/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1787ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1788 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1789 I = ObjCImpls.find(D);
1790 if (I != ObjCImpls.end())
1791 return cast<ObjCCategoryImplDecl>(I->second);
1792 return 0;
1793}
1794
1795/// \brief Set the implementation of ObjCInterfaceDecl.
1796void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1797 ObjCImplementationDecl *ImplD) {
1798 assert(IFaceD && ImplD && "Passed null params");
1799 ObjCImpls[IFaceD] = ImplD;
1800}
1801/// \brief Set the implementation of ObjCCategoryDecl.
1802void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1803 ObjCCategoryImplDecl *ImplD) {
1804 assert(CatD && ImplD && "Passed null params");
1805 ObjCImpls[CatD] = ImplD;
1806}
1807
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001808const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
1809 const NamedDecl *ND) const {
1810 if (const ObjCInterfaceDecl *ID =
1811 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001812 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001813 if (const ObjCCategoryDecl *CD =
1814 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001815 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001816 if (const ObjCImplDecl *IMD =
1817 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001818 return IMD->getClassInterface();
1819
1820 return 0;
1821}
1822
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001823/// \brief Get the copy initialization expression of VarDecl,or NULL if
1824/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001825Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001826 assert(VD && "Passed null params");
1827 assert(VD->hasAttr<BlocksAttr>() &&
1828 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001829 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001830 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001831 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1832}
1833
1834/// \brief Set the copy inialization expression of a block var decl.
1835void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1836 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001837 assert(VD->hasAttr<BlocksAttr>() &&
1838 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001839 BlockVarCopyInits[VD] = Init;
1840}
1841
John McCallbcd03502009-12-07 02:54:59 +00001842TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001843 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001844 if (!DataSize)
1845 DataSize = TypeLoc::getFullDataSizeForType(T);
1846 else
1847 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001848 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001849
John McCallbcd03502009-12-07 02:54:59 +00001850 TypeSourceInfo *TInfo =
1851 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1852 new (TInfo) TypeSourceInfo(T);
1853 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001854}
1855
John McCallbcd03502009-12-07 02:54:59 +00001856TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001857 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001858 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001859 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001860 return DI;
1861}
1862
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001863const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001864ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001865 return getObjCLayout(D, 0);
1866}
1867
1868const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001869ASTContext::getASTObjCImplementationLayout(
1870 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001871 return getObjCLayout(D->getClassInterface(), D);
1872}
1873
Chris Lattner983a8bb2007-07-13 22:13:22 +00001874//===----------------------------------------------------------------------===//
1875// Type creation/memoization methods
1876//===----------------------------------------------------------------------===//
1877
Jay Foad39c79802011-01-12 09:06:06 +00001878QualType
John McCall33ddac02011-01-19 10:06:00 +00001879ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1880 unsigned fastQuals = quals.getFastQualifiers();
1881 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001882
1883 // Check if we've already instantiated this type.
1884 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001885 ExtQuals::Profile(ID, baseType, quals);
1886 void *insertPos = 0;
1887 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1888 assert(eq->getQualifiers() == quals);
1889 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001890 }
1891
John McCall33ddac02011-01-19 10:06:00 +00001892 // If the base type is not canonical, make the appropriate canonical type.
1893 QualType canon;
1894 if (!baseType->isCanonicalUnqualified()) {
1895 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00001896 canonSplit.Quals.addConsistentQualifiers(quals);
1897 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00001898
1899 // Re-find the insert position.
1900 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1901 }
1902
1903 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1904 ExtQualNodes.InsertNode(eq, insertPos);
1905 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001906}
1907
Jay Foad39c79802011-01-12 09:06:06 +00001908QualType
1909ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001910 QualType CanT = getCanonicalType(T);
1911 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001912 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001913
John McCall8ccfcb52009-09-24 19:53:00 +00001914 // If we are composing extended qualifiers together, merge together
1915 // into one ExtQuals node.
1916 QualifierCollector Quals;
1917 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001918
John McCall8ccfcb52009-09-24 19:53:00 +00001919 // If this type already has an address space specified, it cannot get
1920 // another one.
1921 assert(!Quals.hasAddressSpace() &&
1922 "Type cannot be in multiple addr spaces!");
1923 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001924
John McCall8ccfcb52009-09-24 19:53:00 +00001925 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001926}
1927
Chris Lattnerd60183d2009-02-18 22:53:11 +00001928QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001929 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001930 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001931 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001932 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001933
John McCall53fa7142010-12-24 02:08:15 +00001934 if (const PointerType *ptr = T->getAs<PointerType>()) {
1935 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001936 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001937 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1938 return getPointerType(ResultType);
1939 }
1940 }
Mike Stump11289f42009-09-09 15:08:12 +00001941
John McCall8ccfcb52009-09-24 19:53:00 +00001942 // If we are composing extended qualifiers together, merge together
1943 // into one ExtQuals node.
1944 QualifierCollector Quals;
1945 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001946
John McCall8ccfcb52009-09-24 19:53:00 +00001947 // If this type already has an ObjCGC specified, it cannot get
1948 // another one.
1949 assert(!Quals.hasObjCGCAttr() &&
1950 "Type cannot have multiple ObjCGCs!");
1951 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001952
John McCall8ccfcb52009-09-24 19:53:00 +00001953 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001954}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001955
John McCall4f5019e2010-12-19 02:44:49 +00001956const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1957 FunctionType::ExtInfo Info) {
1958 if (T->getExtInfo() == Info)
1959 return T;
1960
1961 QualType Result;
1962 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1963 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1964 } else {
1965 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1966 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1967 EPI.ExtInfo = Info;
1968 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1969 FPT->getNumArgs(), EPI);
1970 }
1971
1972 return cast<FunctionType>(Result.getTypePtr());
1973}
1974
Chris Lattnerc6395932007-06-22 20:56:16 +00001975/// getComplexType - Return the uniqued reference to the type for a complex
1976/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001977QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00001978 // Unique pointers, to guarantee there is only one pointer of a particular
1979 // structure.
1980 llvm::FoldingSetNodeID ID;
1981 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001982
Chris Lattnerc6395932007-06-22 20:56:16 +00001983 void *InsertPos = 0;
1984 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1985 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001986
Chris Lattnerc6395932007-06-22 20:56:16 +00001987 // If the pointee type isn't canonical, this won't be a canonical type either,
1988 // so fill in the canonical type field.
1989 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001990 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001991 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001992
Chris Lattnerc6395932007-06-22 20:56:16 +00001993 // Get the new insert position for the node we care about.
1994 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001995 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001996 }
John McCall90d1c2d2009-09-24 23:30:46 +00001997 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001998 Types.push_back(New);
1999 ComplexTypes.InsertNode(New, InsertPos);
2000 return QualType(New, 0);
2001}
2002
Chris Lattner970e54e2006-11-12 00:37:36 +00002003/// getPointerType - Return the uniqued reference to the type for a pointer to
2004/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002005QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002006 // Unique pointers, to guarantee there is only one pointer of a particular
2007 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002008 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002009 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002010
Chris Lattner67521df2007-01-27 01:29:36 +00002011 void *InsertPos = 0;
2012 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002013 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002014
Chris Lattner7ccecb92006-11-12 08:50:50 +00002015 // If the pointee type isn't canonical, this won't be a canonical type either,
2016 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002017 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002018 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002019 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002020
Chris Lattner67521df2007-01-27 01:29:36 +00002021 // Get the new insert position for the node we care about.
2022 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002023 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00002024 }
John McCall90d1c2d2009-09-24 23:30:46 +00002025 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002026 Types.push_back(New);
2027 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002028 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002029}
2030
Mike Stump11289f42009-09-09 15:08:12 +00002031/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002032/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002033QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002034 assert(T->isFunctionType() && "block of function types only");
2035 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002036 // structure.
2037 llvm::FoldingSetNodeID ID;
2038 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002039
Steve Naroffec33ed92008-08-27 16:04:49 +00002040 void *InsertPos = 0;
2041 if (BlockPointerType *PT =
2042 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2043 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002044
2045 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002046 // type either so fill in the canonical type field.
2047 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002048 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002049 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002050
Steve Naroffec33ed92008-08-27 16:04:49 +00002051 // Get the new insert position for the node we care about.
2052 BlockPointerType *NewIP =
2053 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002054 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002055 }
John McCall90d1c2d2009-09-24 23:30:46 +00002056 BlockPointerType *New
2057 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002058 Types.push_back(New);
2059 BlockPointerTypes.InsertNode(New, InsertPos);
2060 return QualType(New, 0);
2061}
2062
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002063/// getLValueReferenceType - Return the uniqued reference to the type for an
2064/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002065QualType
2066ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002067 assert(getCanonicalType(T) != OverloadTy &&
2068 "Unresolved overloaded function type");
2069
Bill Wendling3708c182007-05-27 10:15:43 +00002070 // Unique pointers, to guarantee there is only one pointer of a particular
2071 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002072 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002073 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002074
2075 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002076 if (LValueReferenceType *RT =
2077 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002078 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002079
John McCallfc93cf92009-10-22 22:37:11 +00002080 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2081
Bill Wendling3708c182007-05-27 10:15:43 +00002082 // If the referencee type isn't canonical, this won't be a canonical type
2083 // either, so fill in the canonical type field.
2084 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002085 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2086 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2087 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002088
Bill Wendling3708c182007-05-27 10:15:43 +00002089 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002090 LValueReferenceType *NewIP =
2091 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002092 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002093 }
2094
John McCall90d1c2d2009-09-24 23:30:46 +00002095 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002096 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2097 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002098 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002099 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002100
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002101 return QualType(New, 0);
2102}
2103
2104/// getRValueReferenceType - Return the uniqued reference to the type for an
2105/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002106QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002107 // Unique pointers, to guarantee there is only one pointer of a particular
2108 // structure.
2109 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002110 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002111
2112 void *InsertPos = 0;
2113 if (RValueReferenceType *RT =
2114 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2115 return QualType(RT, 0);
2116
John McCallfc93cf92009-10-22 22:37:11 +00002117 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2118
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002119 // If the referencee type isn't canonical, this won't be a canonical type
2120 // either, so fill in the canonical type field.
2121 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002122 if (InnerRef || !T.isCanonical()) {
2123 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2124 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002125
2126 // Get the new insert position for the node we care about.
2127 RValueReferenceType *NewIP =
2128 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002129 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002130 }
2131
John McCall90d1c2d2009-09-24 23:30:46 +00002132 RValueReferenceType *New
2133 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002134 Types.push_back(New);
2135 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002136 return QualType(New, 0);
2137}
2138
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002139/// getMemberPointerType - Return the uniqued reference to the type for a
2140/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002141QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002142 // Unique pointers, to guarantee there is only one pointer of a particular
2143 // structure.
2144 llvm::FoldingSetNodeID ID;
2145 MemberPointerType::Profile(ID, T, Cls);
2146
2147 void *InsertPos = 0;
2148 if (MemberPointerType *PT =
2149 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2150 return QualType(PT, 0);
2151
2152 // If the pointee or class type isn't canonical, this won't be a canonical
2153 // type either, so fill in the canonical type field.
2154 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002155 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002156 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2157
2158 // Get the new insert position for the node we care about.
2159 MemberPointerType *NewIP =
2160 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002161 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002162 }
John McCall90d1c2d2009-09-24 23:30:46 +00002163 MemberPointerType *New
2164 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002165 Types.push_back(New);
2166 MemberPointerTypes.InsertNode(New, InsertPos);
2167 return QualType(New, 0);
2168}
2169
Mike Stump11289f42009-09-09 15:08:12 +00002170/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002171/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002172QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002173 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002174 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002175 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002176 assert((EltTy->isDependentType() ||
2177 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002178 "Constant array of VLAs is illegal!");
2179
Chris Lattnere2df3f92009-05-13 04:12:56 +00002180 // Convert the array size into a canonical width matching the pointer size for
2181 // the target.
2182 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002183 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002184 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002185
Chris Lattner23b7eb62007-06-15 23:05:46 +00002186 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002187 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002188
Chris Lattner36f8e652007-01-27 08:31:04 +00002189 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002190 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002191 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002192 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002193
John McCall33ddac02011-01-19 10:06:00 +00002194 // If the element type isn't canonical or has qualifiers, this won't
2195 // be a canonical type either, so fill in the canonical type field.
2196 QualType Canon;
2197 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2198 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002199 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002200 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002201 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002202
Chris Lattner36f8e652007-01-27 08:31:04 +00002203 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002204 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002205 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002206 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002207 }
Mike Stump11289f42009-09-09 15:08:12 +00002208
John McCall90d1c2d2009-09-24 23:30:46 +00002209 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002210 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002211 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002212 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002213 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002214}
2215
John McCall06549462011-01-18 08:40:38 +00002216/// getVariableArrayDecayedType - Turns the given type, which may be
2217/// variably-modified, into the corresponding type with all the known
2218/// sizes replaced with [*].
2219QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2220 // Vastly most common case.
2221 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002222
John McCall06549462011-01-18 08:40:38 +00002223 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002224
John McCall06549462011-01-18 08:40:38 +00002225 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002226 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002227 switch (ty->getTypeClass()) {
2228#define TYPE(Class, Base)
2229#define ABSTRACT_TYPE(Class, Base)
2230#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2231#include "clang/AST/TypeNodes.def"
2232 llvm_unreachable("didn't desugar past all non-canonical types?");
2233
2234 // These types should never be variably-modified.
2235 case Type::Builtin:
2236 case Type::Complex:
2237 case Type::Vector:
2238 case Type::ExtVector:
2239 case Type::DependentSizedExtVector:
2240 case Type::ObjCObject:
2241 case Type::ObjCInterface:
2242 case Type::ObjCObjectPointer:
2243 case Type::Record:
2244 case Type::Enum:
2245 case Type::UnresolvedUsing:
2246 case Type::TypeOfExpr:
2247 case Type::TypeOf:
2248 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002249 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002250 case Type::DependentName:
2251 case Type::InjectedClassName:
2252 case Type::TemplateSpecialization:
2253 case Type::DependentTemplateSpecialization:
2254 case Type::TemplateTypeParm:
2255 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002256 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002257 case Type::PackExpansion:
2258 llvm_unreachable("type should never be variably-modified");
2259
2260 // These types can be variably-modified but should never need to
2261 // further decay.
2262 case Type::FunctionNoProto:
2263 case Type::FunctionProto:
2264 case Type::BlockPointer:
2265 case Type::MemberPointer:
2266 return type;
2267
2268 // These types can be variably-modified. All these modifications
2269 // preserve structure except as noted by comments.
2270 // TODO: if we ever care about optimizing VLAs, there are no-op
2271 // optimizations available here.
2272 case Type::Pointer:
2273 result = getPointerType(getVariableArrayDecayedType(
2274 cast<PointerType>(ty)->getPointeeType()));
2275 break;
2276
2277 case Type::LValueReference: {
2278 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2279 result = getLValueReferenceType(
2280 getVariableArrayDecayedType(lv->getPointeeType()),
2281 lv->isSpelledAsLValue());
2282 break;
2283 }
2284
2285 case Type::RValueReference: {
2286 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2287 result = getRValueReferenceType(
2288 getVariableArrayDecayedType(lv->getPointeeType()));
2289 break;
2290 }
2291
Eli Friedman0dfb8892011-10-06 23:00:33 +00002292 case Type::Atomic: {
2293 const AtomicType *at = cast<AtomicType>(ty);
2294 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2295 break;
2296 }
2297
John McCall06549462011-01-18 08:40:38 +00002298 case Type::ConstantArray: {
2299 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2300 result = getConstantArrayType(
2301 getVariableArrayDecayedType(cat->getElementType()),
2302 cat->getSize(),
2303 cat->getSizeModifier(),
2304 cat->getIndexTypeCVRQualifiers());
2305 break;
2306 }
2307
2308 case Type::DependentSizedArray: {
2309 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2310 result = getDependentSizedArrayType(
2311 getVariableArrayDecayedType(dat->getElementType()),
2312 dat->getSizeExpr(),
2313 dat->getSizeModifier(),
2314 dat->getIndexTypeCVRQualifiers(),
2315 dat->getBracketsRange());
2316 break;
2317 }
2318
2319 // Turn incomplete types into [*] types.
2320 case Type::IncompleteArray: {
2321 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2322 result = getVariableArrayType(
2323 getVariableArrayDecayedType(iat->getElementType()),
2324 /*size*/ 0,
2325 ArrayType::Normal,
2326 iat->getIndexTypeCVRQualifiers(),
2327 SourceRange());
2328 break;
2329 }
2330
2331 // Turn VLA types into [*] types.
2332 case Type::VariableArray: {
2333 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2334 result = getVariableArrayType(
2335 getVariableArrayDecayedType(vat->getElementType()),
2336 /*size*/ 0,
2337 ArrayType::Star,
2338 vat->getIndexTypeCVRQualifiers(),
2339 vat->getBracketsRange());
2340 break;
2341 }
2342 }
2343
2344 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002345 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002346}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002347
Steve Naroffcadebd02007-08-30 18:14:25 +00002348/// getVariableArrayType - Returns a non-unique reference to the type for a
2349/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002350QualType ASTContext::getVariableArrayType(QualType EltTy,
2351 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002352 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002353 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002354 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002355 // Since we don't unique expressions, it isn't possible to unique VLA's
2356 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002357 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002358
John McCall33ddac02011-01-19 10:06:00 +00002359 // Be sure to pull qualifiers off the element type.
2360 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2361 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002362 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002363 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002364 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002365 }
2366
John McCall90d1c2d2009-09-24 23:30:46 +00002367 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002368 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002369
2370 VariableArrayTypes.push_back(New);
2371 Types.push_back(New);
2372 return QualType(New, 0);
2373}
2374
Douglas Gregor4619e432008-12-05 23:32:09 +00002375/// getDependentSizedArrayType - Returns a non-unique reference to
2376/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002377/// type.
John McCall33ddac02011-01-19 10:06:00 +00002378QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2379 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002380 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002381 unsigned elementTypeQuals,
2382 SourceRange brackets) const {
2383 assert((!numElements || numElements->isTypeDependent() ||
2384 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002385 "Size must be type- or value-dependent!");
2386
John McCall33ddac02011-01-19 10:06:00 +00002387 // Dependently-sized array types that do not have a specified number
2388 // of elements will have their sizes deduced from a dependent
2389 // initializer. We do no canonicalization here at all, which is okay
2390 // because they can't be used in most locations.
2391 if (!numElements) {
2392 DependentSizedArrayType *newType
2393 = new (*this, TypeAlignment)
2394 DependentSizedArrayType(*this, elementType, QualType(),
2395 numElements, ASM, elementTypeQuals,
2396 brackets);
2397 Types.push_back(newType);
2398 return QualType(newType, 0);
2399 }
2400
2401 // Otherwise, we actually build a new type every time, but we
2402 // also build a canonical type.
2403
2404 SplitQualType canonElementType = getCanonicalType(elementType).split();
2405
2406 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002407 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002408 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002409 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002410 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002411
John McCall33ddac02011-01-19 10:06:00 +00002412 // Look for an existing type with these properties.
2413 DependentSizedArrayType *canonTy =
2414 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002415
John McCall33ddac02011-01-19 10:06:00 +00002416 // If we don't have one, build one.
2417 if (!canonTy) {
2418 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002419 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002420 QualType(), numElements, ASM, elementTypeQuals,
2421 brackets);
2422 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2423 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002424 }
2425
John McCall33ddac02011-01-19 10:06:00 +00002426 // Apply qualifiers from the element type to the array.
2427 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002428 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002429
John McCall33ddac02011-01-19 10:06:00 +00002430 // If we didn't need extra canonicalization for the element type,
2431 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00002432 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00002433 return canon;
2434
2435 // Otherwise, we need to build a type which follows the spelling
2436 // of the element type.
2437 DependentSizedArrayType *sugaredType
2438 = new (*this, TypeAlignment)
2439 DependentSizedArrayType(*this, elementType, canon, numElements,
2440 ASM, elementTypeQuals, brackets);
2441 Types.push_back(sugaredType);
2442 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002443}
2444
John McCall33ddac02011-01-19 10:06:00 +00002445QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002446 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002447 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002448 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002449 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002450
John McCall33ddac02011-01-19 10:06:00 +00002451 void *insertPos = 0;
2452 if (IncompleteArrayType *iat =
2453 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2454 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002455
2456 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002457 // either, so fill in the canonical type field. We also have to pull
2458 // qualifiers off the element type.
2459 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002460
John McCall33ddac02011-01-19 10:06:00 +00002461 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2462 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002463 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002464 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002465 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002466
2467 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002468 IncompleteArrayType *existing =
2469 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2470 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002471 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002472
John McCall33ddac02011-01-19 10:06:00 +00002473 IncompleteArrayType *newType = new (*this, TypeAlignment)
2474 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002475
John McCall33ddac02011-01-19 10:06:00 +00002476 IncompleteArrayTypes.InsertNode(newType, insertPos);
2477 Types.push_back(newType);
2478 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002479}
2480
Steve Naroff91fcddb2007-07-18 18:00:27 +00002481/// getVectorType - Return the unique reference to a vector type of
2482/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002483QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002484 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002485 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002486
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002487 // Check if we've already instantiated a vector of this type.
2488 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002489 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002490
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002491 void *InsertPos = 0;
2492 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2493 return QualType(VTP, 0);
2494
2495 // If the element type isn't canonical, this won't be a canonical type either,
2496 // so fill in the canonical type field.
2497 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002498 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002499 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002500
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002501 // Get the new insert position for the node we care about.
2502 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002503 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002504 }
John McCall90d1c2d2009-09-24 23:30:46 +00002505 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002506 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002507 VectorTypes.InsertNode(New, InsertPos);
2508 Types.push_back(New);
2509 return QualType(New, 0);
2510}
2511
Nate Begemance4d7fc2008-04-18 23:10:10 +00002512/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002513/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002514QualType
2515ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002516 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002517
Steve Naroff91fcddb2007-07-18 18:00:27 +00002518 // Check if we've already instantiated a vector of this type.
2519 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002520 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002521 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002522 void *InsertPos = 0;
2523 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2524 return QualType(VTP, 0);
2525
2526 // If the element type isn't canonical, this won't be a canonical type either,
2527 // so fill in the canonical type field.
2528 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002529 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002530 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002531
Steve Naroff91fcddb2007-07-18 18:00:27 +00002532 // Get the new insert position for the node we care about.
2533 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002534 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002535 }
John McCall90d1c2d2009-09-24 23:30:46 +00002536 ExtVectorType *New = new (*this, TypeAlignment)
2537 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002538 VectorTypes.InsertNode(New, InsertPos);
2539 Types.push_back(New);
2540 return QualType(New, 0);
2541}
2542
Jay Foad39c79802011-01-12 09:06:06 +00002543QualType
2544ASTContext::getDependentSizedExtVectorType(QualType vecType,
2545 Expr *SizeExpr,
2546 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002547 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002548 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002549 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002550
Douglas Gregor352169a2009-07-31 03:54:25 +00002551 void *InsertPos = 0;
2552 DependentSizedExtVectorType *Canon
2553 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2554 DependentSizedExtVectorType *New;
2555 if (Canon) {
2556 // We already have a canonical version of this array type; use it as
2557 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002558 New = new (*this, TypeAlignment)
2559 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2560 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002561 } else {
2562 QualType CanonVecTy = getCanonicalType(vecType);
2563 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002564 New = new (*this, TypeAlignment)
2565 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2566 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002567
2568 DependentSizedExtVectorType *CanonCheck
2569 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2570 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2571 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002572 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2573 } else {
2574 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2575 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002576 New = new (*this, TypeAlignment)
2577 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002578 }
2579 }
Mike Stump11289f42009-09-09 15:08:12 +00002580
Douglas Gregor758a8692009-06-17 21:51:59 +00002581 Types.push_back(New);
2582 return QualType(New, 0);
2583}
2584
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002585/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002586///
Jay Foad39c79802011-01-12 09:06:06 +00002587QualType
2588ASTContext::getFunctionNoProtoType(QualType ResultTy,
2589 const FunctionType::ExtInfo &Info) const {
Roman Divacky65b88cd2011-03-01 17:40:53 +00002590 const CallingConv DefaultCC = Info.getCC();
2591 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2592 CC_X86StdCall : DefaultCC;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002593 // Unique functions, to guarantee there is only one function of a particular
2594 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002595 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002596 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002597
Chris Lattner47955de2007-01-27 08:37:20 +00002598 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002599 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002600 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002601 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002602
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002603 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00002604 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00002605 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002606 Canonical =
2607 getFunctionNoProtoType(getCanonicalType(ResultTy),
2608 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00002609
Chris Lattner47955de2007-01-27 08:37:20 +00002610 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002611 FunctionNoProtoType *NewIP =
2612 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002613 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002614 }
Mike Stump11289f42009-09-09 15:08:12 +00002615
Roman Divacky65b88cd2011-03-01 17:40:53 +00002616 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002617 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002618 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002619 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002620 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002621 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002622}
2623
Douglas Gregorcd780372013-01-17 23:36:45 +00002624/// \brief Determine whether \p T is canonical as the result type of a function.
2625static bool isCanonicalResultType(QualType T) {
2626 return T.isCanonical() &&
2627 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2628 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2629}
2630
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002631/// getFunctionType - Return a normal function type with a typed argument
2632/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00002633QualType
2634ASTContext::getFunctionType(QualType ResultTy,
2635 const QualType *ArgArray, unsigned NumArgs,
2636 const FunctionProtoType::ExtProtoInfo &EPI) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002637 // Unique functions, to guarantee there is only one function of a particular
2638 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002639 llvm::FoldingSetNodeID ID;
Sebastian Redl31ad7542011-03-13 17:09:40 +00002640 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002641
2642 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002643 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002644 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002645 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002646
2647 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002648 bool isCanonical =
Douglas Gregorcd780372013-01-17 23:36:45 +00002649 EPI.ExceptionSpecType == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smith5e580292012-02-10 09:58:53 +00002650 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002651 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002652 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002653 isCanonical = false;
2654
Roman Divacky65b88cd2011-03-01 17:40:53 +00002655 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2656 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2657 CC_X86StdCall : DefaultCC;
John McCalldb40c7f2010-12-14 08:05:40 +00002658
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002659 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002660 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002661 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00002662 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002663 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002664 CanonicalArgs.reserve(NumArgs);
2665 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002666 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002667
John McCalldb40c7f2010-12-14 08:05:40 +00002668 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002669 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002670 CanonicalEPI.ExceptionSpecType = EST_None;
2671 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002672 CanonicalEPI.ExtInfo
2673 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2674
Douglas Gregorcd780372013-01-17 23:36:45 +00002675 // Result types do not have ARC lifetime qualifiers.
2676 QualType CanResultTy = getCanonicalType(ResultTy);
2677 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2678 Qualifiers Qs = CanResultTy.getQualifiers();
2679 Qs.removeObjCLifetime();
2680 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2681 }
2682
2683 Canonical = getFunctionType(CanResultTy,
Jay Foad7d0479f2009-05-21 09:52:38 +00002684 CanonicalArgs.data(), NumArgs,
John McCalldb40c7f2010-12-14 08:05:40 +00002685 CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002686
Chris Lattnerfd4de792007-01-27 01:15:32 +00002687 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002688 FunctionProtoType *NewIP =
2689 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002690 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002691 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002692
John McCall31168b02011-06-15 23:02:42 +00002693 // FunctionProtoType objects are allocated with extra bytes after
2694 // them for three variable size arrays at the end:
2695 // - parameter types
2696 // - exception types
2697 // - consumed-arguments flags
2698 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00002699 // expression, or information used to resolve the exception
2700 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00002701 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002702 NumArgs * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002703 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002704 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002705 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002706 Size += sizeof(Expr*);
Richard Smithf623c962012-04-17 00:58:00 +00002707 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00002708 Size += 2 * sizeof(FunctionDecl*);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002709 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2710 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002711 }
John McCall31168b02011-06-15 23:02:42 +00002712 if (EPI.ConsumedArguments)
2713 Size += NumArgs * sizeof(bool);
2714
John McCalldb40c7f2010-12-14 08:05:40 +00002715 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002716 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2717 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl31ad7542011-03-13 17:09:40 +00002718 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002719 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002720 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002721 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002722}
Chris Lattneref51c202006-11-10 07:17:23 +00002723
John McCalle78aac42010-03-10 03:28:59 +00002724#ifndef NDEBUG
2725static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2726 if (!isa<CXXRecordDecl>(D)) return false;
2727 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2728 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2729 return true;
2730 if (RD->getDescribedClassTemplate() &&
2731 !isa<ClassTemplateSpecializationDecl>(RD))
2732 return true;
2733 return false;
2734}
2735#endif
2736
2737/// getInjectedClassNameType - Return the unique reference to the
2738/// injected class name type for the specified templated declaration.
2739QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002740 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002741 assert(NeedsInjectedClassNameType(Decl));
2742 if (Decl->TypeForDecl) {
2743 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00002744 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00002745 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2746 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2747 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2748 } else {
John McCall424cec92011-01-19 06:33:43 +00002749 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002750 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002751 Decl->TypeForDecl = newType;
2752 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002753 }
2754 return QualType(Decl->TypeForDecl, 0);
2755}
2756
Douglas Gregor83a586e2008-04-13 21:07:44 +00002757/// getTypeDeclType - Return the unique reference to the type for the
2758/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002759QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002760 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002761 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002762
Richard Smithdda56e42011-04-15 14:24:37 +00002763 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002764 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002765
John McCall96f0b5f2010-03-10 06:48:02 +00002766 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2767 "Template type parameter types are always available.");
2768
John McCall81e38502010-02-16 03:57:14 +00002769 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002770 assert(!Record->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002771 "struct/union has previous declaration");
2772 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002773 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002774 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002775 assert(!Enum->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002776 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002777 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002778 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002779 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002780 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2781 Decl->TypeForDecl = newType;
2782 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002783 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002784 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002785
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002786 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002787}
2788
Chris Lattner32d920b2007-01-26 02:01:53 +00002789/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002790/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002791QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002792ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2793 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002794 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002795
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002796 if (Canonical.isNull())
2797 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002798 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002799 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002800 Decl->TypeForDecl = newType;
2801 Types.push_back(newType);
2802 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002803}
2804
Jay Foad39c79802011-01-12 09:06:06 +00002805QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002806 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2807
Douglas Gregorec9fd132012-01-14 16:38:05 +00002808 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002809 if (PrevDecl->TypeForDecl)
2810 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2811
John McCall424cec92011-01-19 06:33:43 +00002812 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2813 Decl->TypeForDecl = newType;
2814 Types.push_back(newType);
2815 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002816}
2817
Jay Foad39c79802011-01-12 09:06:06 +00002818QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002819 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2820
Douglas Gregorec9fd132012-01-14 16:38:05 +00002821 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002822 if (PrevDecl->TypeForDecl)
2823 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2824
John McCall424cec92011-01-19 06:33:43 +00002825 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2826 Decl->TypeForDecl = newType;
2827 Types.push_back(newType);
2828 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002829}
2830
John McCall81904512011-01-06 01:58:22 +00002831QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2832 QualType modifiedType,
2833 QualType equivalentType) {
2834 llvm::FoldingSetNodeID id;
2835 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2836
2837 void *insertPos = 0;
2838 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2839 if (type) return QualType(type, 0);
2840
2841 QualType canon = getCanonicalType(equivalentType);
2842 type = new (*this, TypeAlignment)
2843 AttributedType(canon, attrKind, modifiedType, equivalentType);
2844
2845 Types.push_back(type);
2846 AttributedTypes.InsertNode(type, insertPos);
2847
2848 return QualType(type, 0);
2849}
2850
2851
John McCallcebee162009-10-18 09:09:24 +00002852/// \brief Retrieve a substitution-result type.
2853QualType
2854ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00002855 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00002856 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00002857 && "replacement types must always be canonical");
2858
2859 llvm::FoldingSetNodeID ID;
2860 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2861 void *InsertPos = 0;
2862 SubstTemplateTypeParmType *SubstParm
2863 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2864
2865 if (!SubstParm) {
2866 SubstParm = new (*this, TypeAlignment)
2867 SubstTemplateTypeParmType(Parm, Replacement);
2868 Types.push_back(SubstParm);
2869 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2870 }
2871
2872 return QualType(SubstParm, 0);
2873}
2874
Douglas Gregorada4b792011-01-14 02:55:32 +00002875/// \brief Retrieve a
2876QualType ASTContext::getSubstTemplateTypeParmPackType(
2877 const TemplateTypeParmType *Parm,
2878 const TemplateArgument &ArgPack) {
2879#ifndef NDEBUG
2880 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2881 PEnd = ArgPack.pack_end();
2882 P != PEnd; ++P) {
2883 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2884 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2885 }
2886#endif
2887
2888 llvm::FoldingSetNodeID ID;
2889 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2890 void *InsertPos = 0;
2891 if (SubstTemplateTypeParmPackType *SubstParm
2892 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2893 return QualType(SubstParm, 0);
2894
2895 QualType Canon;
2896 if (!Parm->isCanonicalUnqualified()) {
2897 Canon = getCanonicalType(QualType(Parm, 0));
2898 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2899 ArgPack);
2900 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2901 }
2902
2903 SubstTemplateTypeParmPackType *SubstParm
2904 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2905 ArgPack);
2906 Types.push_back(SubstParm);
2907 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2908 return QualType(SubstParm, 0);
2909}
2910
Douglas Gregoreff93e02009-02-05 23:33:38 +00002911/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00002912/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00002913/// name.
Mike Stump11289f42009-09-09 15:08:12 +00002914QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00002915 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00002916 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00002917 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00002918 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002919 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002920 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00002921 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2922
2923 if (TypeParm)
2924 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002925
Chandler Carruth08836322011-05-01 00:51:33 +00002926 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00002927 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00002928 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002929
2930 TemplateTypeParmType *TypeCheck
2931 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2932 assert(!TypeCheck && "Template type parameter canonical type broken");
2933 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002934 } else
John McCall90d1c2d2009-09-24 23:30:46 +00002935 TypeParm = new (*this, TypeAlignment)
2936 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002937
2938 Types.push_back(TypeParm);
2939 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2940
2941 return QualType(TypeParm, 0);
2942}
2943
John McCalle78aac42010-03-10 03:28:59 +00002944TypeSourceInfo *
2945ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2946 SourceLocation NameLoc,
2947 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002948 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002949 assert(!Name.getAsDependentTemplateName() &&
2950 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002951 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00002952
2953 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2954 TemplateSpecializationTypeLoc TL
2955 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002956 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00002957 TL.setTemplateNameLoc(NameLoc);
2958 TL.setLAngleLoc(Args.getLAngleLoc());
2959 TL.setRAngleLoc(Args.getRAngleLoc());
2960 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2961 TL.setArgLocInfo(i, Args[i].getLocInfo());
2962 return DI;
2963}
2964
Mike Stump11289f42009-09-09 15:08:12 +00002965QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002966ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002967 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002968 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002969 assert(!Template.getAsDependentTemplateName() &&
2970 "No dependent template names here!");
2971
John McCall6b51f282009-11-23 01:53:49 +00002972 unsigned NumArgs = Args.size();
2973
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002974 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00002975 ArgVec.reserve(NumArgs);
2976 for (unsigned i = 0; i != NumArgs; ++i)
2977 ArgVec.push_back(Args[i].getArgument());
2978
John McCall2408e322010-04-27 00:57:59 +00002979 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002980 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00002981}
2982
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002983#ifndef NDEBUG
2984static bool hasAnyPackExpansions(const TemplateArgument *Args,
2985 unsigned NumArgs) {
2986 for (unsigned I = 0; I != NumArgs; ++I)
2987 if (Args[I].isPackExpansion())
2988 return true;
2989
2990 return true;
2991}
2992#endif
2993
John McCall0ad16662009-10-29 08:12:44 +00002994QualType
2995ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002996 const TemplateArgument *Args,
2997 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002998 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002999 assert(!Template.getAsDependentTemplateName() &&
3000 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003001 // Look through qualified template names.
3002 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3003 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003004
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003005 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003006 Template.getAsTemplateDecl() &&
3007 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003008 QualType CanonType;
3009 if (!Underlying.isNull())
3010 CanonType = getCanonicalType(Underlying);
3011 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003012 // We can get here with an alias template when the specialization contains
3013 // a pack expansion that does not match up with a parameter pack.
3014 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3015 "Caller must compute aliased type");
3016 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003017 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3018 NumArgs);
3019 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003020
Douglas Gregora8e02e72009-07-28 23:00:59 +00003021 // Allocate the (non-canonical) template specialization type, but don't
3022 // try to unique it: these types typically have location information that
3023 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003024 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3025 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003026 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003027 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003028 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003029 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3030 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003031
Douglas Gregor8bf42052009-02-09 18:46:07 +00003032 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003033 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003034}
3035
Mike Stump11289f42009-09-09 15:08:12 +00003036QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003037ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3038 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00003039 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003040 assert(!Template.getAsDependentTemplateName() &&
3041 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003042
Douglas Gregore29139c2011-03-03 17:04:51 +00003043 // Look through qualified template names.
3044 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3045 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003046
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003047 // Build the canonical template specialization type.
3048 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003049 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003050 CanonArgs.reserve(NumArgs);
3051 for (unsigned I = 0; I != NumArgs; ++I)
3052 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3053
3054 // Determine whether this canonical template specialization type already
3055 // exists.
3056 llvm::FoldingSetNodeID ID;
3057 TemplateSpecializationType::Profile(ID, CanonTemplate,
3058 CanonArgs.data(), NumArgs, *this);
3059
3060 void *InsertPos = 0;
3061 TemplateSpecializationType *Spec
3062 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3063
3064 if (!Spec) {
3065 // Allocate a new canonical template specialization type.
3066 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3067 sizeof(TemplateArgument) * NumArgs),
3068 TypeAlignment);
3069 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3070 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003071 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003072 Types.push_back(Spec);
3073 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3074 }
3075
3076 assert(Spec->isDependentType() &&
3077 "Non-dependent template-id type must have a canonical type");
3078 return QualType(Spec, 0);
3079}
3080
3081QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003082ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3083 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003084 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003085 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003086 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003087
3088 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003089 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003090 if (T)
3091 return QualType(T, 0);
3092
Douglas Gregorc42075a2010-02-04 18:10:26 +00003093 QualType Canon = NamedType;
3094 if (!Canon.isCanonical()) {
3095 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003096 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3097 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003098 (void)CheckT;
3099 }
3100
Abramo Bagnara6150c882010-05-11 21:36:43 +00003101 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003102 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003103 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003104 return QualType(T, 0);
3105}
3106
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003107QualType
Jay Foad39c79802011-01-12 09:06:06 +00003108ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003109 llvm::FoldingSetNodeID ID;
3110 ParenType::Profile(ID, InnerType);
3111
3112 void *InsertPos = 0;
3113 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3114 if (T)
3115 return QualType(T, 0);
3116
3117 QualType Canon = InnerType;
3118 if (!Canon.isCanonical()) {
3119 Canon = getCanonicalType(InnerType);
3120 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3121 assert(!CheckT && "Paren canonical type broken");
3122 (void)CheckT;
3123 }
3124
3125 T = new (*this) ParenType(InnerType, Canon);
3126 Types.push_back(T);
3127 ParenTypes.InsertNode(T, InsertPos);
3128 return QualType(T, 0);
3129}
3130
Douglas Gregor02085352010-03-31 20:19:30 +00003131QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3132 NestedNameSpecifier *NNS,
3133 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003134 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003135 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
3136
3137 if (Canon.isNull()) {
3138 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00003139 ElaboratedTypeKeyword CanonKeyword = Keyword;
3140 if (Keyword == ETK_None)
3141 CanonKeyword = ETK_Typename;
3142
3143 if (CanonNNS != NNS || CanonKeyword != Keyword)
3144 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003145 }
3146
3147 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003148 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003149
3150 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003151 DependentNameType *T
3152 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003153 if (T)
3154 return QualType(T, 0);
3155
Douglas Gregor02085352010-03-31 20:19:30 +00003156 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003157 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003158 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003159 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003160}
3161
Mike Stump11289f42009-09-09 15:08:12 +00003162QualType
John McCallc392f372010-06-11 00:33:02 +00003163ASTContext::getDependentTemplateSpecializationType(
3164 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003165 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003166 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003167 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003168 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003169 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003170 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3171 ArgCopy.push_back(Args[I].getArgument());
3172 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3173 ArgCopy.size(),
3174 ArgCopy.data());
3175}
3176
3177QualType
3178ASTContext::getDependentTemplateSpecializationType(
3179 ElaboratedTypeKeyword Keyword,
3180 NestedNameSpecifier *NNS,
3181 const IdentifierInfo *Name,
3182 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00003183 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003184 assert((!NNS || NNS->isDependent()) &&
3185 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003186
Douglas Gregorc42075a2010-02-04 18:10:26 +00003187 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003188 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3189 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003190
3191 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00003192 DependentTemplateSpecializationType *T
3193 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003194 if (T)
3195 return QualType(T, 0);
3196
John McCallc392f372010-06-11 00:33:02 +00003197 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003198
John McCallc392f372010-06-11 00:33:02 +00003199 ElaboratedTypeKeyword CanonKeyword = Keyword;
3200 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3201
3202 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003203 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003204 for (unsigned I = 0; I != NumArgs; ++I) {
3205 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3206 if (!CanonArgs[I].structurallyEquals(Args[I]))
3207 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003208 }
3209
John McCallc392f372010-06-11 00:33:02 +00003210 QualType Canon;
3211 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3212 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3213 Name, NumArgs,
3214 CanonArgs.data());
3215
3216 // Find the insert position again.
3217 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3218 }
3219
3220 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3221 sizeof(TemplateArgument) * NumArgs),
3222 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003223 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00003224 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003225 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003226 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003227 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003228}
3229
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003230QualType ASTContext::getPackExpansionType(QualType Pattern,
3231 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003232 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003233 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003234
3235 assert(Pattern->containsUnexpandedParameterPack() &&
3236 "Pack expansions must expand one or more parameter packs");
3237 void *InsertPos = 0;
3238 PackExpansionType *T
3239 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3240 if (T)
3241 return QualType(T, 0);
3242
3243 QualType Canon;
3244 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003245 Canon = getCanonicalType(Pattern);
3246 // The canonical type might not contain an unexpanded parameter pack, if it
3247 // contains an alias template specialization which ignores one of its
3248 // parameters.
3249 if (Canon->containsUnexpandedParameterPack()) {
3250 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003251
Richard Smith68eea502012-07-16 00:20:35 +00003252 // Find the insert position again, in case we inserted an element into
3253 // PackExpansionTypes and invalidated our insert position.
3254 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3255 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003256 }
3257
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003258 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003259 Types.push_back(T);
3260 PackExpansionTypes.InsertNode(T, InsertPos);
3261 return QualType(T, 0);
3262}
3263
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003264/// CmpProtocolNames - Comparison predicate for sorting protocols
3265/// alphabetically.
3266static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3267 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00003268 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003269}
3270
John McCall8b07ec22010-05-15 11:32:37 +00003271static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00003272 unsigned NumProtocols) {
3273 if (NumProtocols == 0) return true;
3274
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003275 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3276 return false;
3277
John McCallfc93cf92009-10-22 22:37:11 +00003278 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003279 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3280 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003281 return false;
3282 return true;
3283}
3284
3285static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003286 unsigned &NumProtocols) {
3287 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00003288
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003289 // Sort protocols, keyed by name.
3290 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3291
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003292 // Canonicalize.
3293 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3294 Protocols[I] = Protocols[I]->getCanonicalDecl();
3295
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003296 // Remove duplicates.
3297 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3298 NumProtocols = ProtocolsEnd-Protocols;
3299}
3300
John McCall8b07ec22010-05-15 11:32:37 +00003301QualType ASTContext::getObjCObjectType(QualType BaseType,
3302 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003303 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00003304 // If the base type is an interface and there aren't any protocols
3305 // to add, then the interface type will do just fine.
3306 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3307 return BaseType;
3308
3309 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003310 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00003311 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00003312 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00003313 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3314 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003315
John McCall8b07ec22010-05-15 11:32:37 +00003316 // Build the canonical type, which has the canonical base type and
3317 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00003318 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00003319 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3320 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3321 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003322 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003323 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003324 unsigned UniqueCount = NumProtocols;
3325
John McCallfc93cf92009-10-22 22:37:11 +00003326 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00003327 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3328 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00003329 } else {
John McCall8b07ec22010-05-15 11:32:37 +00003330 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3331 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003332 }
3333
3334 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003335 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3336 }
3337
3338 unsigned Size = sizeof(ObjCObjectTypeImpl);
3339 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3340 void *Mem = Allocate(Size, TypeAlignment);
3341 ObjCObjectTypeImpl *T =
3342 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3343
3344 Types.push_back(T);
3345 ObjCObjectTypes.InsertNode(T, InsertPos);
3346 return QualType(T, 0);
3347}
3348
3349/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3350/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003351QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003352 llvm::FoldingSetNodeID ID;
3353 ObjCObjectPointerType::Profile(ID, ObjectT);
3354
3355 void *InsertPos = 0;
3356 if (ObjCObjectPointerType *QT =
3357 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3358 return QualType(QT, 0);
3359
3360 // Find the canonical object type.
3361 QualType Canonical;
3362 if (!ObjectT.isCanonical()) {
3363 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3364
3365 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003366 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3367 }
3368
Douglas Gregorf85bee62010-02-08 22:59:26 +00003369 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003370 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3371 ObjCObjectPointerType *QType =
3372 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003373
Steve Narofffb4330f2009-06-17 22:40:22 +00003374 Types.push_back(QType);
3375 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003376 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003377}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003378
Douglas Gregor1c283312010-08-11 12:19:30 +00003379/// getObjCInterfaceType - Return the unique reference to the type for the
3380/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003381QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3382 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003383 if (Decl->TypeForDecl)
3384 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003385
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003386 if (PrevDecl) {
3387 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3388 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3389 return QualType(PrevDecl->TypeForDecl, 0);
3390 }
3391
Douglas Gregor7671e532011-12-16 16:34:57 +00003392 // Prefer the definition, if there is one.
3393 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3394 Decl = Def;
3395
Douglas Gregor1c283312010-08-11 12:19:30 +00003396 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3397 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3398 Decl->TypeForDecl = T;
3399 Types.push_back(T);
3400 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003401}
3402
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003403/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3404/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003405/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003406/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003407/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003408QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003409 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003410 if (tofExpr->isTypeDependent()) {
3411 llvm::FoldingSetNodeID ID;
3412 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003413
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003414 void *InsertPos = 0;
3415 DependentTypeOfExprType *Canon
3416 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3417 if (Canon) {
3418 // We already have a "canonical" version of an identical, dependent
3419 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003420 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003421 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003422 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003423 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003424 Canon
3425 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003426 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3427 toe = Canon;
3428 }
3429 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003430 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003431 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003432 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003433 Types.push_back(toe);
3434 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003435}
3436
Steve Naroffa773cd52007-08-01 18:02:17 +00003437/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3438/// TypeOfType AST's. The only motivation to unique these nodes would be
3439/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003440/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003441/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003442QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003443 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003444 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003445 Types.push_back(tot);
3446 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003447}
3448
Anders Carlssonad6bd352009-06-24 21:24:56 +00003449
Anders Carlsson81df7b82009-06-24 19:06:50 +00003450/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3451/// DecltypeType AST's. The only motivation to unique these nodes would be
3452/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003453/// an issue. This doesn't effect the type checker, since it operates
David Blaikie876657b2011-11-06 22:28:03 +00003454/// on canonical types (which are always unique).
Douglas Gregor81495f32012-02-12 18:42:33 +00003455QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003456 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003457
3458 // C++0x [temp.type]p2:
3459 // If an expression e involves a template parameter, decltype(e) denotes a
3460 // unique dependent type. Two such decltype-specifiers refer to the same
3461 // type only if their expressions are equivalent (14.5.6.1).
3462 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003463 llvm::FoldingSetNodeID ID;
3464 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003465
Douglas Gregora21f6c32009-07-30 23:36:40 +00003466 void *InsertPos = 0;
3467 DependentDecltypeType *Canon
3468 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3469 if (Canon) {
3470 // We already have a "canonical" version of an equivalent, dependent
3471 // decltype type. Use that as our canonical type.
Richard Smithef8bf432012-08-13 20:08:14 +00003472 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
Douglas Gregora21f6c32009-07-30 23:36:40 +00003473 QualType((DecltypeType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003474 } else {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003475 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003476 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003477 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3478 dt = Canon;
3479 }
3480 } else {
Douglas Gregor81495f32012-02-12 18:42:33 +00003481 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3482 getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003483 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003484 Types.push_back(dt);
3485 return QualType(dt, 0);
3486}
3487
Alexis Hunte852b102011-05-24 22:41:36 +00003488/// getUnaryTransformationType - We don't unique these, since the memory
3489/// savings are minimal and these are rare.
3490QualType ASTContext::getUnaryTransformType(QualType BaseType,
3491 QualType UnderlyingType,
3492 UnaryTransformType::UTTKind Kind)
3493 const {
3494 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003495 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3496 Kind,
3497 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003498 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003499 Types.push_back(Ty);
3500 return QualType(Ty, 0);
3501}
3502
Richard Smithb2bc2e62011-02-21 20:05:19 +00003503/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00003504QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smithb2bc2e62011-02-21 20:05:19 +00003505 void *InsertPos = 0;
3506 if (!DeducedType.isNull()) {
3507 // Look in the folding set for an existing type.
3508 llvm::FoldingSetNodeID ID;
3509 AutoType::Profile(ID, DeducedType);
3510 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3511 return QualType(AT, 0);
3512 }
3513
3514 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
3515 Types.push_back(AT);
3516 if (InsertPos)
3517 AutoTypes.InsertNode(AT, InsertPos);
3518 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003519}
3520
Eli Friedman0dfb8892011-10-06 23:00:33 +00003521/// getAtomicType - Return the uniqued reference to the atomic type for
3522/// the given value type.
3523QualType ASTContext::getAtomicType(QualType T) const {
3524 // Unique pointers, to guarantee there is only one pointer of a particular
3525 // structure.
3526 llvm::FoldingSetNodeID ID;
3527 AtomicType::Profile(ID, T);
3528
3529 void *InsertPos = 0;
3530 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3531 return QualType(AT, 0);
3532
3533 // If the atomic value type isn't canonical, this won't be a canonical type
3534 // either, so fill in the canonical type field.
3535 QualType Canonical;
3536 if (!T.isCanonical()) {
3537 Canonical = getAtomicType(getCanonicalType(T));
3538
3539 // Get the new insert position for the node we care about.
3540 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3541 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3542 }
3543 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3544 Types.push_back(New);
3545 AtomicTypes.InsertNode(New, InsertPos);
3546 return QualType(New, 0);
3547}
3548
Richard Smith02e85f32011-04-14 22:09:26 +00003549/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3550QualType ASTContext::getAutoDeductType() const {
3551 if (AutoDeductTy.isNull())
3552 AutoDeductTy = getAutoType(QualType());
3553 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
3554 return AutoDeductTy;
3555}
3556
3557/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3558QualType ASTContext::getAutoRRefDeductType() const {
3559 if (AutoRRefDeductTy.isNull())
3560 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3561 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3562 return AutoRRefDeductTy;
3563}
3564
Chris Lattnerfb072462007-01-23 05:45:31 +00003565/// getTagDeclType - Return the unique reference to the type for the
3566/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003567QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003568 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003569 // FIXME: What is the design on getTagDeclType when it requires casting
3570 // away const? mutable?
3571 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003572}
3573
Mike Stump11289f42009-09-09 15:08:12 +00003574/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3575/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3576/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003577CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003578 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003579}
Chris Lattnerfb072462007-01-23 05:45:31 +00003580
Hans Wennborg27541db2011-10-27 08:29:09 +00003581/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3582CanQualType ASTContext::getIntMaxType() const {
3583 return getFromTargetType(Target->getIntMaxType());
3584}
3585
3586/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3587CanQualType ASTContext::getUIntMaxType() const {
3588 return getFromTargetType(Target->getUIntMaxType());
3589}
3590
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003591/// getSignedWCharType - Return the type of "signed wchar_t".
3592/// Used when in C++, as a GCC extension.
3593QualType ASTContext::getSignedWCharType() const {
3594 // FIXME: derive from "Target" ?
3595 return WCharTy;
3596}
3597
3598/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3599/// Used when in C++, as a GCC extension.
3600QualType ASTContext::getUnsignedWCharType() const {
3601 // FIXME: derive from "Target" ?
3602 return UnsignedIntTy;
3603}
3604
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00003605QualType ASTContext::getIntPtrType() const {
3606 return getFromTargetType(Target->getIntPtrType());
3607}
3608
3609QualType ASTContext::getUIntPtrType() const {
3610 return getCorrespondingUnsignedType(getIntPtrType());
3611}
3612
Hans Wennborg27541db2011-10-27 08:29:09 +00003613/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003614/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3615QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003616 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003617}
3618
Eli Friedman4e91899e2012-11-27 02:58:24 +00003619/// \brief Return the unique type for "pid_t" defined in
3620/// <sys/types.h>. We need this to compute the correct type for vfork().
3621QualType ASTContext::getProcessIDType() const {
3622 return getFromTargetType(Target->getProcessIDType());
3623}
3624
Chris Lattnera21ad802008-04-02 05:18:44 +00003625//===----------------------------------------------------------------------===//
3626// Type Operators
3627//===----------------------------------------------------------------------===//
3628
Jay Foad39c79802011-01-12 09:06:06 +00003629CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003630 // Push qualifiers into arrays, and then discard any remaining
3631 // qualifiers.
3632 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003633 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003634 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003635 QualType Result;
3636 if (isa<ArrayType>(Ty)) {
3637 Result = getArrayDecayedType(QualType(Ty,0));
3638 } else if (isa<FunctionType>(Ty)) {
3639 Result = getPointerType(QualType(Ty, 0));
3640 } else {
3641 Result = QualType(Ty, 0);
3642 }
3643
3644 return CanQualType::CreateUnsafe(Result);
3645}
3646
John McCall6c9dd522011-01-18 07:41:22 +00003647QualType ASTContext::getUnqualifiedArrayType(QualType type,
3648 Qualifiers &quals) {
3649 SplitQualType splitType = type.getSplitUnqualifiedType();
3650
3651 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3652 // the unqualified desugared type and then drops it on the floor.
3653 // We then have to strip that sugar back off with
3654 // getUnqualifiedDesugaredType(), which is silly.
3655 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003656 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003657
3658 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003659 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003660 quals = splitType.Quals;
3661 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003662 }
3663
John McCall6c9dd522011-01-18 07:41:22 +00003664 // Otherwise, recurse on the array's element type.
3665 QualType elementType = AT->getElementType();
3666 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3667
3668 // If that didn't change the element type, AT has no qualifiers, so we
3669 // can just use the results in splitType.
3670 if (elementType == unqualElementType) {
3671 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00003672 quals = splitType.Quals;
3673 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00003674 }
3675
3676 // Otherwise, add in the qualifiers from the outermost type, then
3677 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00003678 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003679
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003680 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003681 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003682 CAT->getSizeModifier(), 0);
3683 }
3684
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003685 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003686 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003687 }
3688
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003689 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003690 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003691 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003692 VAT->getSizeModifier(),
3693 VAT->getIndexTypeCVRQualifiers(),
3694 VAT->getBracketsRange());
3695 }
3696
3697 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003698 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003699 DSAT->getSizeModifier(), 0,
3700 SourceRange());
3701}
3702
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003703/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3704/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3705/// they point to and return true. If T1 and T2 aren't pointer types
3706/// or pointer-to-member types, or if they are not similar at this
3707/// level, returns false and leaves T1 and T2 unchanged. Top-level
3708/// qualifiers on T1 and T2 are ignored. This function will typically
3709/// be called in a loop that successively "unwraps" pointer and
3710/// pointer-to-member types to compare them at each level.
3711bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3712 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3713 *T2PtrType = T2->getAs<PointerType>();
3714 if (T1PtrType && T2PtrType) {
3715 T1 = T1PtrType->getPointeeType();
3716 T2 = T2PtrType->getPointeeType();
3717 return true;
3718 }
3719
3720 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3721 *T2MPType = T2->getAs<MemberPointerType>();
3722 if (T1MPType && T2MPType &&
3723 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3724 QualType(T2MPType->getClass(), 0))) {
3725 T1 = T1MPType->getPointeeType();
3726 T2 = T2MPType->getPointeeType();
3727 return true;
3728 }
3729
David Blaikiebbafb8a2012-03-11 07:00:24 +00003730 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003731 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3732 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3733 if (T1OPType && T2OPType) {
3734 T1 = T1OPType->getPointeeType();
3735 T2 = T2OPType->getPointeeType();
3736 return true;
3737 }
3738 }
3739
3740 // FIXME: Block pointers, too?
3741
3742 return false;
3743}
3744
Jay Foad39c79802011-01-12 09:06:06 +00003745DeclarationNameInfo
3746ASTContext::getNameForTemplate(TemplateName Name,
3747 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003748 switch (Name.getKind()) {
3749 case TemplateName::QualifiedTemplate:
3750 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003751 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00003752 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3753 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003754
John McCalld9dfe3a2011-06-30 08:33:18 +00003755 case TemplateName::OverloadedTemplate: {
3756 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3757 // DNInfo work in progress: CHECKME: what about DNLoc?
3758 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3759 }
3760
3761 case TemplateName::DependentTemplate: {
3762 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003763 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00003764 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003765 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3766 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00003767 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003768 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3769 // DNInfo work in progress: FIXME: source locations?
3770 DeclarationNameLoc DNLoc;
3771 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3772 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3773 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00003774 }
3775 }
3776
John McCalld9dfe3a2011-06-30 08:33:18 +00003777 case TemplateName::SubstTemplateTemplateParm: {
3778 SubstTemplateTemplateParmStorage *subst
3779 = Name.getAsSubstTemplateTemplateParm();
3780 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3781 NameLoc);
3782 }
3783
3784 case TemplateName::SubstTemplateTemplateParmPack: {
3785 SubstTemplateTemplateParmPackStorage *subst
3786 = Name.getAsSubstTemplateTemplateParmPack();
3787 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3788 NameLoc);
3789 }
3790 }
3791
3792 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00003793}
3794
Jay Foad39c79802011-01-12 09:06:06 +00003795TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003796 switch (Name.getKind()) {
3797 case TemplateName::QualifiedTemplate:
3798 case TemplateName::Template: {
3799 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003800 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00003801 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003802 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3803
3804 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00003805 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003806 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00003807
John McCalld9dfe3a2011-06-30 08:33:18 +00003808 case TemplateName::OverloadedTemplate:
3809 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00003810
John McCalld9dfe3a2011-06-30 08:33:18 +00003811 case TemplateName::DependentTemplate: {
3812 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3813 assert(DTN && "Non-dependent template names must refer to template decls.");
3814 return DTN->CanonicalTemplateName;
3815 }
3816
3817 case TemplateName::SubstTemplateTemplateParm: {
3818 SubstTemplateTemplateParmStorage *subst
3819 = Name.getAsSubstTemplateTemplateParm();
3820 return getCanonicalTemplateName(subst->getReplacement());
3821 }
3822
3823 case TemplateName::SubstTemplateTemplateParmPack: {
3824 SubstTemplateTemplateParmPackStorage *subst
3825 = Name.getAsSubstTemplateTemplateParmPack();
3826 TemplateTemplateParmDecl *canonParameter
3827 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3828 TemplateArgument canonArgPack
3829 = getCanonicalTemplateArgument(subst->getArgumentPack());
3830 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3831 }
3832 }
3833
3834 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00003835}
3836
Douglas Gregoradee3e32009-11-11 23:06:43 +00003837bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3838 X = getCanonicalTemplateName(X);
3839 Y = getCanonicalTemplateName(Y);
3840 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3841}
3842
Mike Stump11289f42009-09-09 15:08:12 +00003843TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00003844ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00003845 switch (Arg.getKind()) {
3846 case TemplateArgument::Null:
3847 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003848
Douglas Gregora8e02e72009-07-28 23:00:59 +00003849 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00003850 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003851
Douglas Gregor31f55dc2012-04-06 22:40:38 +00003852 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00003853 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
3854 return TemplateArgument(D, Arg.isDeclForReferenceParam());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00003855 }
Mike Stump11289f42009-09-09 15:08:12 +00003856
Eli Friedmanb826a002012-09-26 02:36:12 +00003857 case TemplateArgument::NullPtr:
3858 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
3859 /*isNullPtr*/true);
3860
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003861 case TemplateArgument::Template:
3862 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003863
3864 case TemplateArgument::TemplateExpansion:
3865 return TemplateArgument(getCanonicalTemplateName(
3866 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00003867 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003868
Douglas Gregora8e02e72009-07-28 23:00:59 +00003869 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00003870 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00003871
Douglas Gregora8e02e72009-07-28 23:00:59 +00003872 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00003873 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00003874
Douglas Gregora8e02e72009-07-28 23:00:59 +00003875 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00003876 if (Arg.pack_size() == 0)
3877 return Arg;
3878
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003879 TemplateArgument *CanonArgs
3880 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00003881 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003882 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003883 AEnd = Arg.pack_end();
3884 A != AEnd; (void)++A, ++Idx)
3885 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00003886
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003887 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00003888 }
3889 }
3890
3891 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00003892 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00003893}
3894
Douglas Gregor333489b2009-03-27 23:10:48 +00003895NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00003896ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00003897 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00003898 return 0;
3899
3900 switch (NNS->getKind()) {
3901 case NestedNameSpecifier::Identifier:
3902 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00003903 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00003904 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3905 NNS->getAsIdentifier());
3906
3907 case NestedNameSpecifier::Namespace:
3908 // A namespace is canonical; build a nested-name-specifier with
3909 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00003910 return NestedNameSpecifier::Create(*this, 0,
3911 NNS->getAsNamespace()->getOriginalNamespace());
3912
3913 case NestedNameSpecifier::NamespaceAlias:
3914 // A namespace is canonical; build a nested-name-specifier with
3915 // this namespace and no prefix.
3916 return NestedNameSpecifier::Create(*this, 0,
3917 NNS->getAsNamespaceAlias()->getNamespace()
3918 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00003919
3920 case NestedNameSpecifier::TypeSpec:
3921 case NestedNameSpecifier::TypeSpecWithTemplate: {
3922 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003923
3924 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3925 // break it apart into its prefix and identifier, then reconsititute those
3926 // as the canonical nested-name-specifier. This is required to canonicalize
3927 // a dependent nested-name-specifier involving typedefs of dependent-name
3928 // types, e.g.,
3929 // typedef typename T::type T1;
3930 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00003931 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
3932 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00003933 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003934
Eli Friedman5358a0a2012-03-03 04:09:56 +00003935 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
3936 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
3937 // first place?
John McCall33ddac02011-01-19 10:06:00 +00003938 return NestedNameSpecifier::Create(*this, 0, false,
3939 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00003940 }
3941
3942 case NestedNameSpecifier::Global:
3943 // The global specifier is canonical and unique.
3944 return NNS;
3945 }
3946
David Blaikie8a40f702012-01-17 06:56:22 +00003947 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00003948}
3949
Chris Lattner7adf0762008-08-04 07:31:14 +00003950
Jay Foad39c79802011-01-12 09:06:06 +00003951const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003952 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003953 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003954 // Handle the common positive case fast.
3955 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3956 return AT;
3957 }
Mike Stump11289f42009-09-09 15:08:12 +00003958
John McCall8ccfcb52009-09-24 19:53:00 +00003959 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00003960 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00003961 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003962
John McCall8ccfcb52009-09-24 19:53:00 +00003963 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00003964 // implements C99 6.7.3p8: "If the specification of an array type includes
3965 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00003966
Chris Lattner7adf0762008-08-04 07:31:14 +00003967 // If we get here, we either have type qualifiers on the type, or we have
3968 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00003969 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00003970
John McCall33ddac02011-01-19 10:06:00 +00003971 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003972 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00003973
Chris Lattner7adf0762008-08-04 07:31:14 +00003974 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00003975 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall33ddac02011-01-19 10:06:00 +00003976 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00003977 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00003978
Chris Lattner7adf0762008-08-04 07:31:14 +00003979 // Otherwise, we have an array and we have qualifiers on it. Push the
3980 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00003981 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00003982
Chris Lattner7adf0762008-08-04 07:31:14 +00003983 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3984 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3985 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003986 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00003987 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3988 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3989 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003990 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00003991
Mike Stump11289f42009-09-09 15:08:12 +00003992 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00003993 = dyn_cast<DependentSizedArrayType>(ATy))
3994 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00003995 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003996 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00003997 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003998 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003999 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00004000
Chris Lattner7adf0762008-08-04 07:31:14 +00004001 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00004002 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004003 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00004004 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004005 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004006 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00004007}
4008
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004009QualType ASTContext::getAdjustedParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004010 // C99 6.7.5.3p7:
4011 // A declaration of a parameter as "array of type" shall be
4012 // adjusted to "qualified pointer to type", where the type
4013 // qualifiers (if any) are those specified within the [ and ] of
4014 // the array type derivation.
4015 if (T->isArrayType())
4016 return getArrayDecayedType(T);
4017
4018 // C99 6.7.5.3p8:
4019 // A declaration of a parameter as "function returning type"
4020 // shall be adjusted to "pointer to function returning type", as
4021 // in 6.3.2.1.
4022 if (T->isFunctionType())
4023 return getPointerType(T);
4024
4025 return T;
4026}
4027
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004028QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004029 T = getVariableArrayDecayedType(T);
4030 T = getAdjustedParameterType(T);
4031 return T.getUnqualifiedType();
4032}
4033
Chris Lattnera21ad802008-04-02 05:18:44 +00004034/// getArrayDecayedType - Return the properly qualified result of decaying the
4035/// specified array type to a pointer. This operation is non-trivial when
4036/// handling typedefs etc. The canonical type of "T" must be an array type,
4037/// this returns a pointer to a properly qualified element of the array.
4038///
4039/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004040QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004041 // Get the element type with 'getAsArrayType' so that we don't lose any
4042 // typedefs in the element type of the array. This also handles propagation
4043 // of type qualifiers from the array type into the element type if present
4044 // (C99 6.7.3p8).
4045 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4046 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004047
Chris Lattner7adf0762008-08-04 07:31:14 +00004048 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004049
4050 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00004051 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00004052}
4053
John McCall33ddac02011-01-19 10:06:00 +00004054QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4055 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00004056}
4057
John McCall33ddac02011-01-19 10:06:00 +00004058QualType ASTContext::getBaseElementType(QualType type) const {
4059 Qualifiers qs;
4060 while (true) {
4061 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004062 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00004063 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00004064
John McCall33ddac02011-01-19 10:06:00 +00004065 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00004066 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00004067 }
Mike Stump11289f42009-09-09 15:08:12 +00004068
John McCall33ddac02011-01-19 10:06:00 +00004069 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00004070}
4071
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004072/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00004073uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004074ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4075 uint64_t ElementCount = 1;
4076 do {
4077 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00004078 CA = dyn_cast_or_null<ConstantArrayType>(
4079 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004080 } while (CA);
4081 return ElementCount;
4082}
4083
Steve Naroff0af91202007-04-27 21:51:21 +00004084/// getFloatingRank - Return a relative rank for floating point types.
4085/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00004086static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00004087 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00004088 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00004089
John McCall9dd450b2009-09-21 23:43:11 +00004090 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4091 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004092 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004093 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00004094 case BuiltinType::Float: return FloatRank;
4095 case BuiltinType::Double: return DoubleRank;
4096 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00004097 }
4098}
4099
Mike Stump11289f42009-09-09 15:08:12 +00004100/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4101/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00004102/// 'typeDomain' is a real floating point or complex type.
4103/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004104QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4105 QualType Domain) const {
4106 FloatingRank EltRank = getFloatingRank(Size);
4107 if (Domain->isComplexType()) {
4108 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004109 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00004110 case FloatRank: return FloatComplexTy;
4111 case DoubleRank: return DoubleComplexTy;
4112 case LongDoubleRank: return LongDoubleComplexTy;
4113 }
Steve Naroff0af91202007-04-27 21:51:21 +00004114 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004115
4116 assert(Domain->isRealFloatingType() && "Unknown domain!");
4117 switch (EltRank) {
Joey Goulydd7f4562013-01-23 11:56:20 +00004118 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004119 case FloatRank: return FloatTy;
4120 case DoubleRank: return DoubleTy;
4121 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00004122 }
David Blaikief47fa302012-01-17 02:30:50 +00004123 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00004124}
4125
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004126/// getFloatingTypeOrder - Compare the rank of the two specified floating
4127/// point types, ignoring the domain of the type (i.e. 'double' ==
4128/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004129/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004130int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00004131 FloatingRank LHSR = getFloatingRank(LHS);
4132 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004133
Chris Lattnerb90739d2008-04-06 23:38:49 +00004134 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004135 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00004136 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004137 return 1;
4138 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00004139}
4140
Chris Lattner76a00cf2008-04-06 22:59:24 +00004141/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4142/// routine will assert if passed a built-in type that isn't an integer or enum,
4143/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00004144unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00004145 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004146
Chris Lattner76a00cf2008-04-06 22:59:24 +00004147 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004148 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004149 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004150 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004151 case BuiltinType::Char_S:
4152 case BuiltinType::Char_U:
4153 case BuiltinType::SChar:
4154 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004155 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004156 case BuiltinType::Short:
4157 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004158 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004159 case BuiltinType::Int:
4160 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004161 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004162 case BuiltinType::Long:
4163 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004164 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004165 case BuiltinType::LongLong:
4166 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004167 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00004168 case BuiltinType::Int128:
4169 case BuiltinType::UInt128:
4170 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00004171 }
4172}
4173
Eli Friedman629ffb92009-08-20 04:21:42 +00004174/// \brief Whether this is a promotable bitfield reference according
4175/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4176///
4177/// \returns the type this bit-field will promote to, or NULL if no
4178/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004179QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004180 if (E->isTypeDependent() || E->isValueDependent())
4181 return QualType();
4182
Eli Friedman629ffb92009-08-20 04:21:42 +00004183 FieldDecl *Field = E->getBitField();
4184 if (!Field)
4185 return QualType();
4186
4187 QualType FT = Field->getType();
4188
Richard Smithcaf33902011-10-10 18:28:20 +00004189 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004190 uint64_t IntSize = getTypeSize(IntTy);
4191 // GCC extension compatibility: if the bit-field size is less than or equal
4192 // to the size of int, it gets promoted no matter what its type is.
4193 // For instance, unsigned long bf : 4 gets promoted to signed int.
4194 if (BitWidth < IntSize)
4195 return IntTy;
4196
4197 if (BitWidth == IntSize)
4198 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4199
4200 // Types bigger than int are not subject to promotions, and therefore act
4201 // like the base type.
4202 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4203 // is ridiculous.
4204 return QualType();
4205}
4206
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004207/// getPromotedIntegerType - Returns the type that Promotable will
4208/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4209/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004210QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004211 assert(!Promotable.isNull());
4212 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004213 if (const EnumType *ET = Promotable->getAs<EnumType>())
4214 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004215
4216 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4217 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4218 // (3.9.1) can be converted to a prvalue of the first of the following
4219 // types that can represent all the values of its underlying type:
4220 // int, unsigned int, long int, unsigned long int, long long int, or
4221 // unsigned long long int [...]
4222 // FIXME: Is there some better way to compute this?
4223 if (BT->getKind() == BuiltinType::WChar_S ||
4224 BT->getKind() == BuiltinType::WChar_U ||
4225 BT->getKind() == BuiltinType::Char16 ||
4226 BT->getKind() == BuiltinType::Char32) {
4227 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4228 uint64_t FromSize = getTypeSize(BT);
4229 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4230 LongLongTy, UnsignedLongLongTy };
4231 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4232 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4233 if (FromSize < ToSize ||
4234 (FromSize == ToSize &&
4235 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4236 return PromoteTypes[Idx];
4237 }
4238 llvm_unreachable("char type should fit into long long");
4239 }
4240 }
4241
4242 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004243 if (Promotable->isSignedIntegerType())
4244 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00004245 uint64_t PromotableSize = getIntWidth(Promotable);
4246 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004247 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4248 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4249}
4250
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004251/// \brief Recurses in pointer/array types until it finds an objc retainable
4252/// type and returns its ownership.
4253Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4254 while (!T.isNull()) {
4255 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4256 return T.getObjCLifetime();
4257 if (T->isArrayType())
4258 T = getBaseElementType(T);
4259 else if (const PointerType *PT = T->getAs<PointerType>())
4260 T = PT->getPointeeType();
4261 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004262 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004263 else
4264 break;
4265 }
4266
4267 return Qualifiers::OCL_None;
4268}
4269
Mike Stump11289f42009-09-09 15:08:12 +00004270/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004271/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004272/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004273int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004274 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4275 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004276 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004277
Chris Lattner76a00cf2008-04-06 22:59:24 +00004278 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4279 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004280
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004281 unsigned LHSRank = getIntegerRank(LHSC);
4282 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004283
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004284 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4285 if (LHSRank == RHSRank) return 0;
4286 return LHSRank > RHSRank ? 1 : -1;
4287 }
Mike Stump11289f42009-09-09 15:08:12 +00004288
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004289 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4290 if (LHSUnsigned) {
4291 // If the unsigned [LHS] type is larger, return it.
4292 if (LHSRank >= RHSRank)
4293 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004294
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004295 // If the signed type can represent all values of the unsigned type, it
4296 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004297 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004298 return -1;
4299 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004300
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004301 // If the unsigned [RHS] type is larger, return it.
4302 if (RHSRank >= LHSRank)
4303 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004304
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004305 // If the signed type can represent all values of the unsigned type, it
4306 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004307 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004308 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004309}
Anders Carlsson98f07902007-08-17 05:31:46 +00004310
Anders Carlsson6d417272009-11-14 21:45:58 +00004311static RecordDecl *
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004312CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
4313 DeclContext *DC, IdentifierInfo *Id) {
4314 SourceLocation Loc;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004315 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004316 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00004317 else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004318 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00004319}
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004320
Mike Stump11289f42009-09-09 15:08:12 +00004321// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00004322QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004323 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00004324 CFConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004325 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004326 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00004327 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004328
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004329 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00004330
Anders Carlsson98f07902007-08-17 05:31:46 +00004331 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004332 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004333 // int flags;
4334 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00004335 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004336 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00004337 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004338 FieldTypes[3] = LongTy;
4339
Anders Carlsson98f07902007-08-17 05:31:46 +00004340 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004341 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00004342 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004343 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00004344 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00004345 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00004346 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004347 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004348 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004349 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004350 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004351 }
4352
Douglas Gregord5058122010-02-11 01:19:42 +00004353 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00004354 }
Mike Stump11289f42009-09-09 15:08:12 +00004355
Anders Carlsson98f07902007-08-17 05:31:46 +00004356 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00004357}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004358
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004359QualType ASTContext::getObjCSuperType() const {
4360 if (ObjCSuperType.isNull()) {
4361 RecordDecl *ObjCSuperTypeDecl =
4362 CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get("objc_super"));
4363 TUDecl->addDecl(ObjCSuperTypeDecl);
4364 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4365 }
4366 return ObjCSuperType;
4367}
4368
Douglas Gregor512b0772009-04-23 22:29:11 +00004369void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004370 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00004371 assert(Rec && "Invalid CFConstantStringType");
4372 CFConstantStringTypeDecl = Rec->getDecl();
4373}
4374
Jay Foad39c79802011-01-12 09:06:06 +00004375QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004376 if (BlockDescriptorType)
4377 return getTagDeclType(BlockDescriptorType);
4378
4379 RecordDecl *T;
4380 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004381 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004382 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00004383 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004384
4385 QualType FieldTypes[] = {
4386 UnsignedLongTy,
4387 UnsignedLongTy,
4388 };
4389
4390 const char *FieldNames[] = {
4391 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004392 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004393 };
4394
4395 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004396 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00004397 SourceLocation(),
4398 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004399 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00004400 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004401 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004402 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004403 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00004404 T->addDecl(Field);
4405 }
4406
Douglas Gregord5058122010-02-11 01:19:42 +00004407 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004408
4409 BlockDescriptorType = T;
4410
4411 return getTagDeclType(BlockDescriptorType);
4412}
4413
Jay Foad39c79802011-01-12 09:06:06 +00004414QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004415 if (BlockDescriptorExtendedType)
4416 return getTagDeclType(BlockDescriptorExtendedType);
4417
4418 RecordDecl *T;
4419 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004420 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004421 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00004422 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004423
4424 QualType FieldTypes[] = {
4425 UnsignedLongTy,
4426 UnsignedLongTy,
4427 getPointerType(VoidPtrTy),
4428 getPointerType(VoidPtrTy)
4429 };
4430
4431 const char *FieldNames[] = {
4432 "reserved",
4433 "Size",
4434 "CopyFuncPtr",
4435 "DestroyFuncPtr"
4436 };
4437
4438 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004439 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004440 SourceLocation(),
4441 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004442 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004443 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004444 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004445 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004446 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004447 T->addDecl(Field);
4448 }
4449
Douglas Gregord5058122010-02-11 01:19:42 +00004450 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004451
4452 BlockDescriptorExtendedType = T;
4453
4454 return getTagDeclType(BlockDescriptorExtendedType);
4455}
4456
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004457/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4458/// requires copy/dispose. Note that this must match the logic
4459/// in buildByrefHelpers.
4460bool ASTContext::BlockRequiresCopying(QualType Ty,
4461 const VarDecl *D) {
4462 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4463 const Expr *copyExpr = getBlockVarCopyInits(D);
4464 if (!copyExpr && record->hasTrivialDestructor()) return false;
4465
Mike Stump94967902009-10-21 18:16:27 +00004466 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004467 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004468
4469 if (!Ty->isObjCRetainableType()) return false;
4470
4471 Qualifiers qs = Ty.getQualifiers();
4472
4473 // If we have lifetime, that dominates.
4474 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4475 assert(getLangOpts().ObjCAutoRefCount);
4476
4477 switch (lifetime) {
4478 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4479
4480 // These are just bits as far as the runtime is concerned.
4481 case Qualifiers::OCL_ExplicitNone:
4482 case Qualifiers::OCL_Autoreleasing:
4483 return false;
4484
4485 // Tell the runtime that this is ARC __weak, called by the
4486 // byref routines.
4487 case Qualifiers::OCL_Weak:
4488 // ARC __strong __block variables need to be retained.
4489 case Qualifiers::OCL_Strong:
4490 return true;
4491 }
4492 llvm_unreachable("fell out of lifetime switch!");
4493 }
4494 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4495 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00004496}
4497
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004498bool ASTContext::getByrefLifetime(QualType Ty,
4499 Qualifiers::ObjCLifetime &LifeTime,
4500 bool &HasByrefExtendedLayout) const {
4501
4502 if (!getLangOpts().ObjC1 ||
4503 getLangOpts().getGC() != LangOptions::NonGC)
4504 return false;
4505
4506 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00004507 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004508 HasByrefExtendedLayout = true;
4509 LifeTime = Qualifiers::OCL_None;
4510 }
4511 else if (getLangOpts().ObjCAutoRefCount)
4512 LifeTime = Ty.getObjCLifetime();
4513 // MRR.
4514 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4515 LifeTime = Qualifiers::OCL_ExplicitNone;
4516 else
4517 LifeTime = Qualifiers::OCL_None;
4518 return true;
4519}
4520
Douglas Gregorbab8a962011-09-08 01:46:34 +00004521TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4522 if (!ObjCInstanceTypeDecl)
4523 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4524 getTranslationUnitDecl(),
4525 SourceLocation(),
4526 SourceLocation(),
4527 &Idents.get("instancetype"),
4528 getTrivialTypeSourceInfo(getObjCIdType()));
4529 return ObjCInstanceTypeDecl;
4530}
4531
Anders Carlsson18acd442007-10-29 06:33:42 +00004532// This returns true if a type has been typedefed to BOOL:
4533// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004534static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004535 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004536 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4537 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004538
Anders Carlssond8499822007-10-29 05:01:08 +00004539 return false;
4540}
4541
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004542/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004543/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004544CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004545 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4546 return CharUnits::Zero();
4547
Ken Dyck40775002010-01-11 17:06:35 +00004548 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004549
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004550 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004551 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004552 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004553 // Treat arrays as pointers, since that's how they're passed in.
4554 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004555 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004556 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004557}
4558
4559static inline
4560std::string charUnitsToString(const CharUnits &CU) {
4561 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004562}
4563
John McCall351762c2011-02-07 10:33:21 +00004564/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004565/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004566std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4567 std::string S;
4568
David Chisnall950a9512009-11-17 19:33:30 +00004569 const BlockDecl *Decl = Expr->getBlockDecl();
4570 QualType BlockTy =
4571 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4572 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004573 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004574 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None,
4575 BlockTy->getAs<FunctionType>()->getResultType(),
4576 S, true /*Extended*/);
4577 else
4578 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(),
4579 S);
David Chisnall950a9512009-11-17 19:33:30 +00004580 // Compute size of all parameters.
4581 // Start with computing size of a pointer in number of bytes.
4582 // FIXME: There might(should) be a better way of doing this computation!
4583 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004584 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4585 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00004586 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00004587 E = Decl->param_end(); PI != E; ++PI) {
4588 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004589 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00004590 if (sz.isZero())
4591 continue;
Ken Dyck40775002010-01-11 17:06:35 +00004592 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004593 ParmOffset += sz;
4594 }
4595 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004596 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004597 // Block pointer and offset.
4598 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004599
4600 // Argument types.
4601 ParmOffset = PtrSize;
4602 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4603 Decl->param_end(); PI != E; ++PI) {
4604 ParmVarDecl *PVDecl = *PI;
4605 QualType PType = PVDecl->getOriginalType();
4606 if (const ArrayType *AT =
4607 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4608 // Use array's original type only if it has known number of
4609 // elements.
4610 if (!isa<ConstantArrayType>(AT))
4611 PType = PVDecl->getType();
4612 } else if (PType->isFunctionType())
4613 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004614 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004615 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4616 S, true /*Extended*/);
4617 else
4618 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004619 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004620 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004621 }
John McCall351762c2011-02-07 10:33:21 +00004622
4623 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004624}
4625
Douglas Gregora9d84932011-05-27 01:19:52 +00004626bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004627 std::string& S) {
4628 // Encode result type.
4629 getObjCEncodingForType(Decl->getResultType(), S);
4630 CharUnits ParmOffset;
4631 // Compute size of all parameters.
4632 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4633 E = Decl->param_end(); PI != E; ++PI) {
4634 QualType PType = (*PI)->getType();
4635 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004636 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004637 continue;
4638
David Chisnall50e4eba2010-12-30 14:05:53 +00004639 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004640 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004641 ParmOffset += sz;
4642 }
4643 S += charUnitsToString(ParmOffset);
4644 ParmOffset = CharUnits::Zero();
4645
4646 // Argument types.
4647 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4648 E = Decl->param_end(); PI != E; ++PI) {
4649 ParmVarDecl *PVDecl = *PI;
4650 QualType PType = PVDecl->getOriginalType();
4651 if (const ArrayType *AT =
4652 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4653 // Use array's original type only if it has known number of
4654 // elements.
4655 if (!isa<ConstantArrayType>(AT))
4656 PType = PVDecl->getType();
4657 } else if (PType->isFunctionType())
4658 PType = PVDecl->getType();
4659 getObjCEncodingForType(PType, S);
4660 S += charUnitsToString(ParmOffset);
4661 ParmOffset += getObjCEncodingTypeSize(PType);
4662 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004663
4664 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004665}
4666
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004667/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4668/// method parameter or return type. If Extended, include class names and
4669/// block object types.
4670void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4671 QualType T, std::string& S,
4672 bool Extended) const {
4673 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4674 getObjCEncodingForTypeQualifier(QT, S);
4675 // Encode parameter type.
4676 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4677 true /*OutermostType*/,
4678 false /*EncodingProperty*/,
4679 false /*StructField*/,
4680 Extended /*EncodeBlockParameters*/,
4681 Extended /*EncodeClassNames*/);
4682}
4683
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004684/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004685/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004686bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004687 std::string& S,
4688 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004689 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004690 // Encode return type.
4691 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4692 Decl->getResultType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004693 // Compute size of all parameters.
4694 // Start with computing size of a pointer in number of bytes.
4695 // FIXME: There might(should) be a better way of doing this computation!
4696 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004697 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004698 // The first two arguments (self and _cmd) are pointers; account for
4699 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004700 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004701 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004702 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004703 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004704 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004705 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004706 continue;
4707
Ken Dyck40775002010-01-11 17:06:35 +00004708 assert (sz.isPositive() &&
4709 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004710 ParmOffset += sz;
4711 }
Ken Dyck40775002010-01-11 17:06:35 +00004712 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004713 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004714 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004715
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004716 // Argument types.
4717 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004718 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004719 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004720 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004721 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004722 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004723 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4724 // Use array's original type only if it has known number of
4725 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004726 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004727 PType = PVDecl->getType();
4728 } else if (PType->isFunctionType())
4729 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004730 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4731 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00004732 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004733 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004734 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004735
4736 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004737}
4738
Daniel Dunbar4932b362008-08-28 04:38:10 +00004739/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004740/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004741/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4742/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004743/// Property attributes are stored as a comma-delimited C string. The simple
4744/// attributes readonly and bycopy are encoded as single characters. The
4745/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4746/// encoded as single characters, followed by an identifier. Property types
4747/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004748/// these attributes are defined by the following enumeration:
4749/// @code
4750/// enum PropertyAttributes {
4751/// kPropertyReadOnly = 'R', // property is read-only.
4752/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4753/// kPropertyByref = '&', // property is a reference to the value last assigned
4754/// kPropertyDynamic = 'D', // property is dynamic
4755/// kPropertyGetter = 'G', // followed by getter selector name
4756/// kPropertySetter = 'S', // followed by setter selector name
4757/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00004758/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004759/// kPropertyWeak = 'W' // 'weak' property
4760/// kPropertyStrong = 'P' // property GC'able
4761/// kPropertyNonAtomic = 'N' // property non-atomic
4762/// };
4763/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00004764void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00004765 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00004766 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004767 // Collect information from the property implementation decl(s).
4768 bool Dynamic = false;
4769 ObjCPropertyImplDecl *SynthesizePID = 0;
4770
4771 // FIXME: Duplicated code due to poor abstraction.
4772 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00004773 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00004774 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4775 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004776 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004777 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004778 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004779 if (PID->getPropertyDecl() == PD) {
4780 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4781 Dynamic = true;
4782 } else {
4783 SynthesizePID = PID;
4784 }
4785 }
4786 }
4787 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00004788 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004789 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004790 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004791 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004792 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004793 if (PID->getPropertyDecl() == PD) {
4794 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4795 Dynamic = true;
4796 } else {
4797 SynthesizePID = PID;
4798 }
4799 }
Mike Stump11289f42009-09-09 15:08:12 +00004800 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00004801 }
4802 }
4803
4804 // FIXME: This is not very efficient.
4805 S = "T";
4806
4807 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004808 // GCC has some special rules regarding encoding of properties which
4809 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00004810 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004811 true /* outermost type */,
4812 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004813
4814 if (PD->isReadOnly()) {
4815 S += ",R";
4816 } else {
4817 switch (PD->getSetterKind()) {
4818 case ObjCPropertyDecl::Assign: break;
4819 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00004820 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00004821 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004822 }
4823 }
4824
4825 // It really isn't clear at all what this means, since properties
4826 // are "dynamic by default".
4827 if (Dynamic)
4828 S += ",D";
4829
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004830 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4831 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00004832
Daniel Dunbar4932b362008-08-28 04:38:10 +00004833 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4834 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00004835 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004836 }
4837
4838 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4839 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00004840 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004841 }
4842
4843 if (SynthesizePID) {
4844 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4845 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00004846 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004847 }
4848
4849 // FIXME: OBJCGC: weak & strong
4850}
4851
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004852/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00004853/// Another legacy compatibility encoding: 32-bit longs are encoded as
4854/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004855/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4856///
4857void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00004858 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00004859 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00004860 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004861 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00004862 else
Jay Foad39c79802011-01-12 09:06:06 +00004863 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004864 PointeeTy = IntTy;
4865 }
4866 }
4867}
4868
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004869void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00004870 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004871 // We follow the behavior of gcc, expanding structures which are
4872 // directly pointed to, and expanding embedded structures. Note that
4873 // these rules are sufficient to prevent recursive encoding of the
4874 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00004875 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00004876 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004877}
4878
John McCall393a78d2012-12-20 02:45:14 +00004879static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
4880 BuiltinType::Kind kind) {
4881 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00004882 case BuiltinType::Void: return 'v';
4883 case BuiltinType::Bool: return 'B';
4884 case BuiltinType::Char_U:
4885 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00004886 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00004887 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00004888 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00004889 case BuiltinType::UInt: return 'I';
4890 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00004891 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004892 case BuiltinType::UInt128: return 'T';
4893 case BuiltinType::ULongLong: return 'Q';
4894 case BuiltinType::Char_S:
4895 case BuiltinType::SChar: return 'c';
4896 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00004897 case BuiltinType::WChar_S:
4898 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00004899 case BuiltinType::Int: return 'i';
4900 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00004901 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004902 case BuiltinType::LongLong: return 'q';
4903 case BuiltinType::Int128: return 't';
4904 case BuiltinType::Float: return 'f';
4905 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00004906 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00004907 case BuiltinType::NullPtr: return '*'; // like char*
4908
4909 case BuiltinType::Half:
4910 // FIXME: potentially need @encodes for these!
4911 return ' ';
4912
4913 case BuiltinType::ObjCId:
4914 case BuiltinType::ObjCClass:
4915 case BuiltinType::ObjCSel:
4916 llvm_unreachable("@encoding ObjC primitive type");
4917
4918 // OpenCL and placeholder types don't need @encodings.
4919 case BuiltinType::OCLImage1d:
4920 case BuiltinType::OCLImage1dArray:
4921 case BuiltinType::OCLImage1dBuffer:
4922 case BuiltinType::OCLImage2d:
4923 case BuiltinType::OCLImage2dArray:
4924 case BuiltinType::OCLImage3d:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00004925 case BuiltinType::OCLEvent:
John McCall393a78d2012-12-20 02:45:14 +00004926 case BuiltinType::Dependent:
4927#define BUILTIN_TYPE(KIND, ID)
4928#define PLACEHOLDER_TYPE(KIND, ID) \
4929 case BuiltinType::KIND:
4930#include "clang/AST/BuiltinTypes.def"
4931 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00004932 }
David Blaikie5a6a0202013-01-09 17:48:41 +00004933 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00004934}
4935
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004936static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4937 EnumDecl *Enum = ET->getDecl();
4938
4939 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4940 if (!Enum->isFixed())
4941 return 'i';
4942
4943 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00004944 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
4945 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004946}
4947
Jay Foad39c79802011-01-12 09:06:06 +00004948static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00004949 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00004950 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004951 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00004952 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4953 // The GNU runtime requires more information; bitfields are encoded as b,
4954 // then the offset (in bits) of the first element, then the type of the
4955 // bitfield, then the size in bits. For example, in this structure:
4956 //
4957 // struct
4958 // {
4959 // int integer;
4960 // int flags:2;
4961 // };
4962 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4963 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4964 // information is not especially sensible, but we're stuck with it for
4965 // compatibility with GCC, although providing it breaks anything that
4966 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00004967 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00004968 const RecordDecl *RD = FD->getParent();
4969 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00004970 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004971 if (const EnumType *ET = T->getAs<EnumType>())
4972 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00004973 else {
4974 const BuiltinType *BT = T->castAs<BuiltinType>();
4975 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
4976 }
David Chisnallb190a2c2010-06-04 01:10:52 +00004977 }
Richard Smithcaf33902011-10-10 18:28:20 +00004978 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004979}
4980
Daniel Dunbar07d07852009-10-18 21:17:35 +00004981// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004982void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4983 bool ExpandPointedToStructures,
4984 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00004985 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004986 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004987 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004988 bool StructField,
4989 bool EncodeBlockParameters,
4990 bool EncodeClassNames) const {
John McCall393a78d2012-12-20 02:45:14 +00004991 CanQualType CT = getCanonicalType(T);
4992 switch (CT->getTypeClass()) {
4993 case Type::Builtin:
4994 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00004995 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004996 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00004997 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
4998 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
4999 else
5000 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00005001 return;
Mike Stump11289f42009-09-09 15:08:12 +00005002
John McCall393a78d2012-12-20 02:45:14 +00005003 case Type::Complex: {
5004 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00005005 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00005006 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00005007 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005008 return;
5009 }
John McCall393a78d2012-12-20 02:45:14 +00005010
5011 case Type::Atomic: {
5012 const AtomicType *AT = T->castAs<AtomicType>();
5013 S += 'A';
5014 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, 0,
5015 false, false);
5016 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00005017 }
John McCall393a78d2012-12-20 02:45:14 +00005018
5019 // encoding for pointer or reference types.
5020 case Type::Pointer:
5021 case Type::LValueReference:
5022 case Type::RValueReference: {
5023 QualType PointeeTy;
5024 if (isa<PointerType>(CT)) {
5025 const PointerType *PT = T->castAs<PointerType>();
5026 if (PT->isObjCSelType()) {
5027 S += ':';
5028 return;
5029 }
5030 PointeeTy = PT->getPointeeType();
5031 } else {
5032 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5033 }
5034
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005035 bool isReadOnly = false;
5036 // For historical/compatibility reasons, the read-only qualifier of the
5037 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5038 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00005039 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00005040 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005041 if (OutermostType && T.isConstQualified()) {
5042 isReadOnly = true;
5043 S += 'r';
5044 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00005045 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005046 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005047 while (P->getAs<PointerType>())
5048 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005049 if (P.isConstQualified()) {
5050 isReadOnly = true;
5051 S += 'r';
5052 }
5053 }
5054 if (isReadOnly) {
5055 // Another legacy compatibility encoding. Some ObjC qualifier and type
5056 // combinations need to be rearranged.
5057 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005058 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00005059 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005060 }
Mike Stump11289f42009-09-09 15:08:12 +00005061
Anders Carlssond8499822007-10-29 05:01:08 +00005062 if (PointeeTy->isCharType()) {
5063 // char pointer types should be encoded as '*' unless it is a
5064 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00005065 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00005066 S += '*';
5067 return;
5068 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005069 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00005070 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5071 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5072 S += '#';
5073 return;
5074 }
5075 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5076 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5077 S += '@';
5078 return;
5079 }
5080 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00005081 }
Anders Carlssond8499822007-10-29 05:01:08 +00005082 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005083 getLegacyIntegralTypeEncoding(PointeeTy);
5084
Mike Stump11289f42009-09-09 15:08:12 +00005085 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005086 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005087 return;
5088 }
John McCall393a78d2012-12-20 02:45:14 +00005089
5090 case Type::ConstantArray:
5091 case Type::IncompleteArray:
5092 case Type::VariableArray: {
5093 const ArrayType *AT = cast<ArrayType>(CT);
5094
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005095 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005096 // Incomplete arrays are encoded as a pointer to the array element.
5097 S += '^';
5098
Mike Stump11289f42009-09-09 15:08:12 +00005099 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005100 false, ExpandStructures, FD);
5101 } else {
5102 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00005103
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005104 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
5105 if (getTypeSize(CAT->getElementType()) == 0)
5106 S += '0';
5107 else
5108 S += llvm::utostr(CAT->getSize().getZExtValue());
5109 } else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005110 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005111 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5112 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00005113 S += '0';
5114 }
Mike Stump11289f42009-09-09 15:08:12 +00005115
5116 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005117 false, ExpandStructures, FD);
5118 S += ']';
5119 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005120 return;
5121 }
Mike Stump11289f42009-09-09 15:08:12 +00005122
John McCall393a78d2012-12-20 02:45:14 +00005123 case Type::FunctionNoProto:
5124 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00005125 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005126 return;
Mike Stump11289f42009-09-09 15:08:12 +00005127
John McCall393a78d2012-12-20 02:45:14 +00005128 case Type::Record: {
5129 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005130 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00005131 // Anonymous structures print as '?'
5132 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5133 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005134 if (ClassTemplateSpecializationDecl *Spec
5135 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5136 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
5137 std::string TemplateArgsStr
5138 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005139 TemplateArgs.data(),
5140 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00005141 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005142
5143 S += TemplateArgsStr;
5144 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00005145 } else {
5146 S += '?';
5147 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00005148 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005149 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005150 if (!RDecl->isUnion()) {
5151 getObjCEncodingForStructureImpl(RDecl, S, FD);
5152 } else {
5153 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5154 FieldEnd = RDecl->field_end();
5155 Field != FieldEnd; ++Field) {
5156 if (FD) {
5157 S += '"';
5158 S += Field->getNameAsString();
5159 S += '"';
5160 }
Mike Stump11289f42009-09-09 15:08:12 +00005161
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005162 // Special case bit-fields.
5163 if (Field->isBitField()) {
5164 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie40ed2972012-06-06 20:45:41 +00005165 *Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005166 } else {
5167 QualType qt = Field->getType();
5168 getLegacyIntegralTypeEncoding(qt);
5169 getObjCEncodingForTypeImpl(qt, S, false, true,
5170 FD, /*OutermostType*/false,
5171 /*EncodingProperty*/false,
5172 /*StructField*/true);
5173 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005174 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005175 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00005176 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005177 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005178 return;
5179 }
Mike Stump11289f42009-09-09 15:08:12 +00005180
John McCall393a78d2012-12-20 02:45:14 +00005181 case Type::BlockPointer: {
5182 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00005183 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005184 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00005185 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005186
5187 S += '<';
5188 // Block return type
5189 getObjCEncodingForTypeImpl(FT->getResultType(), S,
5190 ExpandPointedToStructures, ExpandStructures,
5191 FD,
5192 false /* OutermostType */,
5193 EncodingProperty,
5194 false /* StructField */,
5195 EncodeBlockParameters,
5196 EncodeClassNames);
5197 // Block self
5198 S += "@?";
5199 // Block parameters
5200 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
5201 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
5202 E = FPT->arg_type_end(); I && (I != E); ++I) {
5203 getObjCEncodingForTypeImpl(*I, S,
5204 ExpandPointedToStructures,
5205 ExpandStructures,
5206 FD,
5207 false /* OutermostType */,
5208 EncodingProperty,
5209 false /* StructField */,
5210 EncodeBlockParameters,
5211 EncodeClassNames);
5212 }
5213 }
5214 S += '>';
5215 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005216 return;
5217 }
Mike Stump11289f42009-09-09 15:08:12 +00005218
John McCall393a78d2012-12-20 02:45:14 +00005219 case Type::ObjCObject:
5220 case Type::ObjCInterface: {
5221 // Ignore protocol qualifiers when mangling at this level.
5222 T = T->castAs<ObjCObjectType>()->getBaseType();
John McCall8b07ec22010-05-15 11:32:37 +00005223
John McCall393a78d2012-12-20 02:45:14 +00005224 // The assumption seems to be that this assert will succeed
5225 // because nested levels will have filtered out 'id' and 'Class'.
5226 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005227 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00005228 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005229 S += '{';
5230 const IdentifierInfo *II = OI->getIdentifier();
5231 S += II->getName();
5232 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005233 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005234 DeepCollectObjCIvars(OI, true, Ivars);
5235 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005236 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005237 if (Field->isBitField())
5238 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005239 else
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005240 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005241 }
5242 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005243 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005244 }
Mike Stump11289f42009-09-09 15:08:12 +00005245
John McCall393a78d2012-12-20 02:45:14 +00005246 case Type::ObjCObjectPointer: {
5247 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005248 if (OPT->isObjCIdType()) {
5249 S += '@';
5250 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005251 }
Mike Stump11289f42009-09-09 15:08:12 +00005252
Steve Narofff0c86112009-10-28 22:03:49 +00005253 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5254 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5255 // Since this is a binary compatibility issue, need to consult with runtime
5256 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005257 S += '#';
5258 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005259 }
Mike Stump11289f42009-09-09 15:08:12 +00005260
Chris Lattnere7cabb92009-07-13 00:10:46 +00005261 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005262 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005263 ExpandPointedToStructures,
5264 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005265 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005266 // Note that we do extended encoding of protocol qualifer list
5267 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005268 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00005269 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5270 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005271 S += '<';
5272 S += (*I)->getNameAsString();
5273 S += '>';
5274 }
5275 S += '"';
5276 }
5277 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005278 }
Mike Stump11289f42009-09-09 15:08:12 +00005279
Chris Lattnere7cabb92009-07-13 00:10:46 +00005280 QualType PointeeTy = OPT->getPointeeType();
5281 if (!EncodingProperty &&
5282 isa<TypedefType>(PointeeTy.getTypePtr())) {
5283 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005284 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005285 // {...};
5286 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00005287 getObjCEncodingForTypeImpl(PointeeTy, S,
5288 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00005289 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005290 return;
5291 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005292
5293 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005294 if (OPT->getInterfaceDecl() &&
5295 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005296 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00005297 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00005298 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5299 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005300 S += '<';
5301 S += (*I)->getNameAsString();
5302 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005303 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005304 S += '"';
5305 }
5306 return;
5307 }
Mike Stump11289f42009-09-09 15:08:12 +00005308
John McCalla9e6e8d2010-05-17 23:56:34 +00005309 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00005310 // FIXME: we shoul do better than that. 'M' is available.
5311 case Type::MemberPointer:
John McCalla9e6e8d2010-05-17 23:56:34 +00005312 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005313
John McCall393a78d2012-12-20 02:45:14 +00005314 case Type::Vector:
5315 case Type::ExtVector:
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005316 // This matches gcc's encoding, even though technically it is
5317 // insufficient.
5318 // FIXME. We should do a better job than gcc.
5319 return;
John McCall393a78d2012-12-20 02:45:14 +00005320
5321#define ABSTRACT_TYPE(KIND, BASE)
5322#define TYPE(KIND, BASE)
5323#define DEPENDENT_TYPE(KIND, BASE) \
5324 case Type::KIND:
5325#define NON_CANONICAL_TYPE(KIND, BASE) \
5326 case Type::KIND:
5327#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5328 case Type::KIND:
5329#include "clang/AST/TypeNodes.def"
5330 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005331 }
John McCall393a78d2012-12-20 02:45:14 +00005332 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00005333}
5334
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005335void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5336 std::string &S,
5337 const FieldDecl *FD,
5338 bool includeVBases) const {
5339 assert(RDecl && "Expected non-null RecordDecl");
5340 assert(!RDecl->isUnion() && "Should not be called for unions");
5341 if (!RDecl->getDefinition())
5342 return;
5343
5344 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5345 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5346 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5347
5348 if (CXXRec) {
5349 for (CXXRecordDecl::base_class_iterator
5350 BI = CXXRec->bases_begin(),
5351 BE = CXXRec->bases_end(); BI != BE; ++BI) {
5352 if (!BI->isVirtual()) {
5353 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005354 if (base->isEmpty())
5355 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005356 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005357 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5358 std::make_pair(offs, base));
5359 }
5360 }
5361 }
5362
5363 unsigned i = 0;
5364 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5365 FieldEnd = RDecl->field_end();
5366 Field != FieldEnd; ++Field, ++i) {
5367 uint64_t offs = layout.getFieldOffset(i);
5368 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie40ed2972012-06-06 20:45:41 +00005369 std::make_pair(offs, *Field));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005370 }
5371
5372 if (CXXRec && includeVBases) {
5373 for (CXXRecordDecl::base_class_iterator
5374 BI = CXXRec->vbases_begin(),
5375 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
5376 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005377 if (base->isEmpty())
5378 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005379 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00005380 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
5381 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5382 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005383 }
5384 }
5385
5386 CharUnits size;
5387 if (CXXRec) {
5388 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5389 } else {
5390 size = layout.getSize();
5391 }
5392
5393 uint64_t CurOffs = 0;
5394 std::multimap<uint64_t, NamedDecl *>::iterator
5395 CurLayObj = FieldOrBaseOffsets.begin();
5396
Douglas Gregorf5d6c742012-04-27 22:30:01 +00005397 if (CXXRec && CXXRec->isDynamicClass() &&
5398 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005399 if (FD) {
5400 S += "\"_vptr$";
5401 std::string recname = CXXRec->getNameAsString();
5402 if (recname.empty()) recname = "?";
5403 S += recname;
5404 S += '"';
5405 }
5406 S += "^^?";
5407 CurOffs += getTypeSize(VoidPtrTy);
5408 }
5409
5410 if (!RDecl->hasFlexibleArrayMember()) {
5411 // Mark the end of the structure.
5412 uint64_t offs = toBits(size);
5413 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5414 std::make_pair(offs, (NamedDecl*)0));
5415 }
5416
5417 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5418 assert(CurOffs <= CurLayObj->first);
5419
5420 if (CurOffs < CurLayObj->first) {
5421 uint64_t padding = CurLayObj->first - CurOffs;
5422 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5423 // packing/alignment of members is different that normal, in which case
5424 // the encoding will be out-of-sync with the real layout.
5425 // If the runtime switches to just consider the size of types without
5426 // taking into account alignment, we could make padding explicit in the
5427 // encoding (e.g. using arrays of chars). The encoding strings would be
5428 // longer then though.
5429 CurOffs += padding;
5430 }
5431
5432 NamedDecl *dcl = CurLayObj->second;
5433 if (dcl == 0)
5434 break; // reached end of structure.
5435
5436 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5437 // We expand the bases without their virtual bases since those are going
5438 // in the initial structure. Note that this differs from gcc which
5439 // expands virtual bases each time one is encountered in the hierarchy,
5440 // making the encoding type bigger than it really is.
5441 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005442 assert(!base->isEmpty());
5443 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005444 } else {
5445 FieldDecl *field = cast<FieldDecl>(dcl);
5446 if (FD) {
5447 S += '"';
5448 S += field->getNameAsString();
5449 S += '"';
5450 }
5451
5452 if (field->isBitField()) {
5453 EncodeBitField(this, S, field->getType(), field);
Richard Smithcaf33902011-10-10 18:28:20 +00005454 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005455 } else {
5456 QualType qt = field->getType();
5457 getLegacyIntegralTypeEncoding(qt);
5458 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5459 /*OutermostType*/false,
5460 /*EncodingProperty*/false,
5461 /*StructField*/true);
5462 CurOffs += getTypeSize(field->getType());
5463 }
5464 }
5465 }
5466}
5467
Mike Stump11289f42009-09-09 15:08:12 +00005468void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005469 std::string& S) const {
5470 if (QT & Decl::OBJC_TQ_In)
5471 S += 'n';
5472 if (QT & Decl::OBJC_TQ_Inout)
5473 S += 'N';
5474 if (QT & Decl::OBJC_TQ_Out)
5475 S += 'o';
5476 if (QT & Decl::OBJC_TQ_Bycopy)
5477 S += 'O';
5478 if (QT & Decl::OBJC_TQ_Byref)
5479 S += 'R';
5480 if (QT & Decl::OBJC_TQ_Oneway)
5481 S += 'V';
5482}
5483
Douglas Gregor3ea72692011-08-12 05:46:01 +00005484TypedefDecl *ASTContext::getObjCIdDecl() const {
5485 if (!ObjCIdDecl) {
5486 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5487 T = getObjCObjectPointerType(T);
5488 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
5489 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5490 getTranslationUnitDecl(),
5491 SourceLocation(), SourceLocation(),
5492 &Idents.get("id"), IdInfo);
5493 }
5494
5495 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00005496}
5497
Douglas Gregor52e02802011-08-12 06:17:30 +00005498TypedefDecl *ASTContext::getObjCSelDecl() const {
5499 if (!ObjCSelDecl) {
5500 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5501 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5502 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5503 getTranslationUnitDecl(),
5504 SourceLocation(), SourceLocation(),
5505 &Idents.get("SEL"), SelInfo);
5506 }
5507 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00005508}
5509
Douglas Gregor0a586182011-08-12 05:59:41 +00005510TypedefDecl *ASTContext::getObjCClassDecl() const {
5511 if (!ObjCClassDecl) {
5512 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5513 T = getObjCObjectPointerType(T);
5514 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5515 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5516 getTranslationUnitDecl(),
5517 SourceLocation(), SourceLocation(),
5518 &Idents.get("Class"), ClassInfo);
5519 }
5520
5521 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00005522}
5523
Douglas Gregord53ae832012-01-17 18:09:05 +00005524ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5525 if (!ObjCProtocolClassDecl) {
5526 ObjCProtocolClassDecl
5527 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5528 SourceLocation(),
5529 &Idents.get("Protocol"),
5530 /*PrevDecl=*/0,
5531 SourceLocation(), true);
5532 }
5533
5534 return ObjCProtocolClassDecl;
5535}
5536
Meador Inge5d3fb222012-06-16 03:34:49 +00005537//===----------------------------------------------------------------------===//
5538// __builtin_va_list Construction Functions
5539//===----------------------------------------------------------------------===//
5540
5541static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5542 // typedef char* __builtin_va_list;
5543 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5544 TypeSourceInfo *TInfo
5545 = Context->getTrivialTypeSourceInfo(CharPtrType);
5546
5547 TypedefDecl *VaListTypeDecl
5548 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5549 Context->getTranslationUnitDecl(),
5550 SourceLocation(), SourceLocation(),
5551 &Context->Idents.get("__builtin_va_list"),
5552 TInfo);
5553 return VaListTypeDecl;
5554}
5555
5556static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5557 // typedef void* __builtin_va_list;
5558 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5559 TypeSourceInfo *TInfo
5560 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5561
5562 TypedefDecl *VaListTypeDecl
5563 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5564 Context->getTranslationUnitDecl(),
5565 SourceLocation(), SourceLocation(),
5566 &Context->Idents.get("__builtin_va_list"),
5567 TInfo);
5568 return VaListTypeDecl;
5569}
5570
Tim Northover9bb857a2013-01-31 12:13:10 +00005571static TypedefDecl *
5572CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
5573 RecordDecl *VaListTagDecl;
5574 if (Context->getLangOpts().CPlusPlus) {
5575 // namespace std { struct __va_list {
5576 NamespaceDecl *NS;
5577 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5578 Context->getTranslationUnitDecl(),
5579 /*Inline*/false, SourceLocation(),
5580 SourceLocation(), &Context->Idents.get("std"),
5581 /*PrevDecl*/0);
5582
5583 VaListTagDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5584 Context->getTranslationUnitDecl(),
5585 SourceLocation(), SourceLocation(),
5586 &Context->Idents.get("__va_list"));
5587 VaListTagDecl->setDeclContext(NS);
5588 } else {
5589 // struct __va_list
5590 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5591 Context->getTranslationUnitDecl(),
5592 &Context->Idents.get("__va_list"));
5593 }
5594
5595 VaListTagDecl->startDefinition();
5596
5597 const size_t NumFields = 5;
5598 QualType FieldTypes[NumFields];
5599 const char *FieldNames[NumFields];
5600
5601 // void *__stack;
5602 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
5603 FieldNames[0] = "__stack";
5604
5605 // void *__gr_top;
5606 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
5607 FieldNames[1] = "__gr_top";
5608
5609 // void *__vr_top;
5610 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5611 FieldNames[2] = "__vr_top";
5612
5613 // int __gr_offs;
5614 FieldTypes[3] = Context->IntTy;
5615 FieldNames[3] = "__gr_offs";
5616
5617 // int __vr_offs;
5618 FieldTypes[4] = Context->IntTy;
5619 FieldNames[4] = "__vr_offs";
5620
5621 // Create fields
5622 for (unsigned i = 0; i < NumFields; ++i) {
5623 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5624 VaListTagDecl,
5625 SourceLocation(),
5626 SourceLocation(),
5627 &Context->Idents.get(FieldNames[i]),
5628 FieldTypes[i], /*TInfo=*/0,
5629 /*BitWidth=*/0,
5630 /*Mutable=*/false,
5631 ICIS_NoInit);
5632 Field->setAccess(AS_public);
5633 VaListTagDecl->addDecl(Field);
5634 }
5635 VaListTagDecl->completeDefinition();
5636 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5637 Context->VaListTagTy = VaListTagType;
5638
5639 // } __builtin_va_list;
5640 TypedefDecl *VaListTypedefDecl
5641 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5642 Context->getTranslationUnitDecl(),
5643 SourceLocation(), SourceLocation(),
5644 &Context->Idents.get("__builtin_va_list"),
5645 Context->getTrivialTypeSourceInfo(VaListTagType));
5646
5647 return VaListTypedefDecl;
5648}
5649
Meador Inge5d3fb222012-06-16 03:34:49 +00005650static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5651 // typedef struct __va_list_tag {
5652 RecordDecl *VaListTagDecl;
5653
5654 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5655 Context->getTranslationUnitDecl(),
5656 &Context->Idents.get("__va_list_tag"));
5657 VaListTagDecl->startDefinition();
5658
5659 const size_t NumFields = 5;
5660 QualType FieldTypes[NumFields];
5661 const char *FieldNames[NumFields];
5662
5663 // unsigned char gpr;
5664 FieldTypes[0] = Context->UnsignedCharTy;
5665 FieldNames[0] = "gpr";
5666
5667 // unsigned char fpr;
5668 FieldTypes[1] = Context->UnsignedCharTy;
5669 FieldNames[1] = "fpr";
5670
5671 // unsigned short reserved;
5672 FieldTypes[2] = Context->UnsignedShortTy;
5673 FieldNames[2] = "reserved";
5674
5675 // void* overflow_arg_area;
5676 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5677 FieldNames[3] = "overflow_arg_area";
5678
5679 // void* reg_save_area;
5680 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5681 FieldNames[4] = "reg_save_area";
5682
5683 // Create fields
5684 for (unsigned i = 0; i < NumFields; ++i) {
5685 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5686 SourceLocation(),
5687 SourceLocation(),
5688 &Context->Idents.get(FieldNames[i]),
5689 FieldTypes[i], /*TInfo=*/0,
5690 /*BitWidth=*/0,
5691 /*Mutable=*/false,
5692 ICIS_NoInit);
5693 Field->setAccess(AS_public);
5694 VaListTagDecl->addDecl(Field);
5695 }
5696 VaListTagDecl->completeDefinition();
5697 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005698 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005699
5700 // } __va_list_tag;
5701 TypedefDecl *VaListTagTypedefDecl
5702 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5703 Context->getTranslationUnitDecl(),
5704 SourceLocation(), SourceLocation(),
5705 &Context->Idents.get("__va_list_tag"),
5706 Context->getTrivialTypeSourceInfo(VaListTagType));
5707 QualType VaListTagTypedefType =
5708 Context->getTypedefType(VaListTagTypedefDecl);
5709
5710 // typedef __va_list_tag __builtin_va_list[1];
5711 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5712 QualType VaListTagArrayType
5713 = Context->getConstantArrayType(VaListTagTypedefType,
5714 Size, ArrayType::Normal, 0);
5715 TypeSourceInfo *TInfo
5716 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5717 TypedefDecl *VaListTypedefDecl
5718 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5719 Context->getTranslationUnitDecl(),
5720 SourceLocation(), SourceLocation(),
5721 &Context->Idents.get("__builtin_va_list"),
5722 TInfo);
5723
5724 return VaListTypedefDecl;
5725}
5726
5727static TypedefDecl *
5728CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5729 // typedef struct __va_list_tag {
5730 RecordDecl *VaListTagDecl;
5731 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5732 Context->getTranslationUnitDecl(),
5733 &Context->Idents.get("__va_list_tag"));
5734 VaListTagDecl->startDefinition();
5735
5736 const size_t NumFields = 4;
5737 QualType FieldTypes[NumFields];
5738 const char *FieldNames[NumFields];
5739
5740 // unsigned gp_offset;
5741 FieldTypes[0] = Context->UnsignedIntTy;
5742 FieldNames[0] = "gp_offset";
5743
5744 // unsigned fp_offset;
5745 FieldTypes[1] = Context->UnsignedIntTy;
5746 FieldNames[1] = "fp_offset";
5747
5748 // void* overflow_arg_area;
5749 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5750 FieldNames[2] = "overflow_arg_area";
5751
5752 // void* reg_save_area;
5753 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5754 FieldNames[3] = "reg_save_area";
5755
5756 // Create fields
5757 for (unsigned i = 0; i < NumFields; ++i) {
5758 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5759 VaListTagDecl,
5760 SourceLocation(),
5761 SourceLocation(),
5762 &Context->Idents.get(FieldNames[i]),
5763 FieldTypes[i], /*TInfo=*/0,
5764 /*BitWidth=*/0,
5765 /*Mutable=*/false,
5766 ICIS_NoInit);
5767 Field->setAccess(AS_public);
5768 VaListTagDecl->addDecl(Field);
5769 }
5770 VaListTagDecl->completeDefinition();
5771 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005772 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005773
5774 // } __va_list_tag;
5775 TypedefDecl *VaListTagTypedefDecl
5776 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5777 Context->getTranslationUnitDecl(),
5778 SourceLocation(), SourceLocation(),
5779 &Context->Idents.get("__va_list_tag"),
5780 Context->getTrivialTypeSourceInfo(VaListTagType));
5781 QualType VaListTagTypedefType =
5782 Context->getTypedefType(VaListTagTypedefDecl);
5783
5784 // typedef __va_list_tag __builtin_va_list[1];
5785 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5786 QualType VaListTagArrayType
5787 = Context->getConstantArrayType(VaListTagTypedefType,
5788 Size, ArrayType::Normal,0);
5789 TypeSourceInfo *TInfo
5790 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5791 TypedefDecl *VaListTypedefDecl
5792 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5793 Context->getTranslationUnitDecl(),
5794 SourceLocation(), SourceLocation(),
5795 &Context->Idents.get("__builtin_va_list"),
5796 TInfo);
5797
5798 return VaListTypedefDecl;
5799}
5800
5801static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5802 // typedef int __builtin_va_list[4];
5803 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5804 QualType IntArrayType
5805 = Context->getConstantArrayType(Context->IntTy,
5806 Size, ArrayType::Normal, 0);
5807 TypedefDecl *VaListTypedefDecl
5808 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5809 Context->getTranslationUnitDecl(),
5810 SourceLocation(), SourceLocation(),
5811 &Context->Idents.get("__builtin_va_list"),
5812 Context->getTrivialTypeSourceInfo(IntArrayType));
5813
5814 return VaListTypedefDecl;
5815}
5816
Logan Chien57086ce2012-10-10 06:56:20 +00005817static TypedefDecl *
5818CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
5819 RecordDecl *VaListDecl;
5820 if (Context->getLangOpts().CPlusPlus) {
5821 // namespace std { struct __va_list {
5822 NamespaceDecl *NS;
5823 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5824 Context->getTranslationUnitDecl(),
5825 /*Inline*/false, SourceLocation(),
5826 SourceLocation(), &Context->Idents.get("std"),
5827 /*PrevDecl*/0);
5828
5829 VaListDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5830 Context->getTranslationUnitDecl(),
5831 SourceLocation(), SourceLocation(),
5832 &Context->Idents.get("__va_list"));
5833
5834 VaListDecl->setDeclContext(NS);
5835
5836 } else {
5837 // struct __va_list {
5838 VaListDecl = CreateRecordDecl(*Context, TTK_Struct,
5839 Context->getTranslationUnitDecl(),
5840 &Context->Idents.get("__va_list"));
5841 }
5842
5843 VaListDecl->startDefinition();
5844
5845 // void * __ap;
5846 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5847 VaListDecl,
5848 SourceLocation(),
5849 SourceLocation(),
5850 &Context->Idents.get("__ap"),
5851 Context->getPointerType(Context->VoidTy),
5852 /*TInfo=*/0,
5853 /*BitWidth=*/0,
5854 /*Mutable=*/false,
5855 ICIS_NoInit);
5856 Field->setAccess(AS_public);
5857 VaListDecl->addDecl(Field);
5858
5859 // };
5860 VaListDecl->completeDefinition();
5861
5862 // typedef struct __va_list __builtin_va_list;
5863 TypeSourceInfo *TInfo
5864 = Context->getTrivialTypeSourceInfo(Context->getRecordType(VaListDecl));
5865
5866 TypedefDecl *VaListTypeDecl
5867 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5868 Context->getTranslationUnitDecl(),
5869 SourceLocation(), SourceLocation(),
5870 &Context->Idents.get("__builtin_va_list"),
5871 TInfo);
5872
5873 return VaListTypeDecl;
5874}
5875
Meador Inge5d3fb222012-06-16 03:34:49 +00005876static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
5877 TargetInfo::BuiltinVaListKind Kind) {
5878 switch (Kind) {
5879 case TargetInfo::CharPtrBuiltinVaList:
5880 return CreateCharPtrBuiltinVaListDecl(Context);
5881 case TargetInfo::VoidPtrBuiltinVaList:
5882 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00005883 case TargetInfo::AArch64ABIBuiltinVaList:
5884 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00005885 case TargetInfo::PowerABIBuiltinVaList:
5886 return CreatePowerABIBuiltinVaListDecl(Context);
5887 case TargetInfo::X86_64ABIBuiltinVaList:
5888 return CreateX86_64ABIBuiltinVaListDecl(Context);
5889 case TargetInfo::PNaClABIBuiltinVaList:
5890 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00005891 case TargetInfo::AAPCSABIBuiltinVaList:
5892 return CreateAAPCSABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00005893 }
5894
5895 llvm_unreachable("Unhandled __builtin_va_list type kind");
5896}
5897
5898TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
5899 if (!BuiltinVaListDecl)
5900 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
5901
5902 return BuiltinVaListDecl;
5903}
5904
Meador Ingecfb60902012-07-01 15:57:25 +00005905QualType ASTContext::getVaListTagType() const {
5906 // Force the creation of VaListTagTy by building the __builtin_va_list
5907 // declaration.
5908 if (VaListTagTy.isNull())
5909 (void) getBuiltinVaListDecl();
5910
5911 return VaListTagTy;
5912}
5913
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005914void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00005915 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00005916 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00005917
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005918 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00005919}
5920
John McCalld28ae272009-12-02 08:04:21 +00005921/// \brief Retrieve the template name that corresponds to a non-empty
5922/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00005923TemplateName
5924ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
5925 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00005926 unsigned size = End - Begin;
5927 assert(size > 1 && "set is not overloaded!");
5928
5929 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
5930 size * sizeof(FunctionTemplateDecl*));
5931 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
5932
5933 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00005934 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00005935 NamedDecl *D = *I;
5936 assert(isa<FunctionTemplateDecl>(D) ||
5937 (isa<UsingShadowDecl>(D) &&
5938 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
5939 *Storage++ = D;
5940 }
5941
5942 return TemplateName(OT);
5943}
5944
Douglas Gregordc572a32009-03-30 22:58:21 +00005945/// \brief Retrieve the template name that represents a qualified
5946/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00005947TemplateName
5948ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
5949 bool TemplateKeyword,
5950 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00005951 assert(NNS && "Missing nested-name-specifier in qualified template name");
5952
Douglas Gregorc42075a2010-02-04 18:10:26 +00005953 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00005954 llvm::FoldingSetNodeID ID;
5955 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
5956
5957 void *InsertPos = 0;
5958 QualifiedTemplateName *QTN =
5959 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5960 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00005961 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
5962 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00005963 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
5964 }
5965
5966 return TemplateName(QTN);
5967}
5968
5969/// \brief Retrieve the template name that represents a dependent
5970/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00005971TemplateName
5972ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
5973 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00005974 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00005975 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00005976
5977 llvm::FoldingSetNodeID ID;
5978 DependentTemplateName::Profile(ID, NNS, Name);
5979
5980 void *InsertPos = 0;
5981 DependentTemplateName *QTN =
5982 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5983
5984 if (QTN)
5985 return TemplateName(QTN);
5986
5987 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5988 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00005989 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5990 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00005991 } else {
5992 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00005993 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
5994 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00005995 DependentTemplateName *CheckQTN =
5996 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5997 assert(!CheckQTN && "Dependent type name canonicalization broken");
5998 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00005999 }
6000
6001 DependentTemplateNames.InsertNode(QTN, InsertPos);
6002 return TemplateName(QTN);
6003}
6004
Douglas Gregor71395fa2009-11-04 00:56:37 +00006005/// \brief Retrieve the template name that represents a dependent
6006/// template name such as \c MetaFun::template operator+.
6007TemplateName
6008ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00006009 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00006010 assert((!NNS || NNS->isDependent()) &&
6011 "Nested name specifier must be dependent");
6012
6013 llvm::FoldingSetNodeID ID;
6014 DependentTemplateName::Profile(ID, NNS, Operator);
6015
6016 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00006017 DependentTemplateName *QTN
6018 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006019
6020 if (QTN)
6021 return TemplateName(QTN);
6022
6023 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6024 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006025 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6026 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006027 } else {
6028 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00006029 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6030 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006031
6032 DependentTemplateName *CheckQTN
6033 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6034 assert(!CheckQTN && "Dependent template name canonicalization broken");
6035 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00006036 }
6037
6038 DependentTemplateNames.InsertNode(QTN, InsertPos);
6039 return TemplateName(QTN);
6040}
6041
Douglas Gregor5590be02011-01-15 06:45:20 +00006042TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00006043ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6044 TemplateName replacement) const {
6045 llvm::FoldingSetNodeID ID;
6046 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
6047
6048 void *insertPos = 0;
6049 SubstTemplateTemplateParmStorage *subst
6050 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6051
6052 if (!subst) {
6053 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6054 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6055 }
6056
6057 return TemplateName(subst);
6058}
6059
6060TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00006061ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6062 const TemplateArgument &ArgPack) const {
6063 ASTContext &Self = const_cast<ASTContext &>(*this);
6064 llvm::FoldingSetNodeID ID;
6065 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
6066
6067 void *InsertPos = 0;
6068 SubstTemplateTemplateParmPackStorage *Subst
6069 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6070
6071 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00006072 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00006073 ArgPack.pack_size(),
6074 ArgPack.pack_begin());
6075 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6076 }
6077
6078 return TemplateName(Subst);
6079}
6080
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006081/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00006082/// TargetInfo, produce the corresponding type. The unsigned @p Type
6083/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00006084CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006085 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00006086 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006087 case TargetInfo::SignedShort: return ShortTy;
6088 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6089 case TargetInfo::SignedInt: return IntTy;
6090 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6091 case TargetInfo::SignedLong: return LongTy;
6092 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6093 case TargetInfo::SignedLongLong: return LongLongTy;
6094 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6095 }
6096
David Blaikie83d382b2011-09-23 05:06:16 +00006097 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006098}
Ted Kremenek77c51b22008-07-24 23:58:27 +00006099
6100//===----------------------------------------------------------------------===//
6101// Type Predicates.
6102//===----------------------------------------------------------------------===//
6103
Fariborz Jahanian96207692009-02-18 21:49:28 +00006104/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6105/// garbage collection attribute.
6106///
John McCall553d45a2011-01-12 00:34:59 +00006107Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006108 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00006109 return Qualifiers::GCNone;
6110
David Blaikiebbafb8a2012-03-11 07:00:24 +00006111 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00006112 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6113
6114 // Default behaviour under objective-C's gc is for ObjC pointers
6115 // (or pointers to them) be treated as though they were declared
6116 // as __strong.
6117 if (GCAttrs == Qualifiers::GCNone) {
6118 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6119 return Qualifiers::Strong;
6120 else if (Ty->isPointerType())
6121 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6122 } else {
6123 // It's not valid to set GC attributes on anything that isn't a
6124 // pointer.
6125#ifndef NDEBUG
6126 QualType CT = Ty->getCanonicalTypeInternal();
6127 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6128 CT = AT->getElementType();
6129 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6130#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00006131 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00006132 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00006133}
6134
Chris Lattner49af6a42008-04-07 06:51:04 +00006135//===----------------------------------------------------------------------===//
6136// Type Compatibility Testing
6137//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00006138
Mike Stump11289f42009-09-09 15:08:12 +00006139/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006140/// compatible.
6141static bool areCompatVectorTypes(const VectorType *LHS,
6142 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00006143 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00006144 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00006145 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00006146}
6147
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006148bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6149 QualType SecondVec) {
6150 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6151 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6152
6153 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6154 return true;
6155
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006156 // Treat Neon vector types and most AltiVec vector types as if they are the
6157 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006158 const VectorType *First = FirstVec->getAs<VectorType>();
6159 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006160 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006161 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006162 First->getVectorKind() != VectorType::AltiVecPixel &&
6163 First->getVectorKind() != VectorType::AltiVecBool &&
6164 Second->getVectorKind() != VectorType::AltiVecPixel &&
6165 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006166 return true;
6167
6168 return false;
6169}
6170
Steve Naroff8e6aee52009-07-23 01:01:38 +00006171//===----------------------------------------------------------------------===//
6172// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6173//===----------------------------------------------------------------------===//
6174
6175/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6176/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00006177bool
6178ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6179 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00006180 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006181 return true;
6182 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
6183 E = rProto->protocol_end(); PI != E; ++PI)
6184 if (ProtocolCompatibleWithProtocol(lProto, *PI))
6185 return true;
6186 return false;
6187}
6188
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006189/// QualifiedIdConformsQualifiedId - compare id<pr,...> with id<pr1,...>
Steve Naroff8e6aee52009-07-23 01:01:38 +00006190/// return true if lhs's protocols conform to rhs's protocol; false
6191/// otherwise.
6192bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
6193 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
6194 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
6195 return false;
6196}
6197
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006198/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6199/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006200bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6201 QualType rhs) {
6202 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6203 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6204 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6205
6206 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6207 E = lhsQID->qual_end(); I != E; ++I) {
6208 bool match = false;
6209 ObjCProtocolDecl *lhsProto = *I;
6210 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6211 E = rhsOPT->qual_end(); J != E; ++J) {
6212 ObjCProtocolDecl *rhsProto = *J;
6213 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6214 match = true;
6215 break;
6216 }
6217 }
6218 if (!match)
6219 return false;
6220 }
6221 return true;
6222}
6223
Steve Naroff8e6aee52009-07-23 01:01:38 +00006224/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6225/// ObjCQualifiedIDType.
6226bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6227 bool compare) {
6228 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00006229 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006230 lhs->isObjCIdType() || lhs->isObjCClassType())
6231 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006232 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006233 rhs->isObjCIdType() || rhs->isObjCClassType())
6234 return true;
6235
6236 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00006237 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006238
Steve Naroff8e6aee52009-07-23 01:01:38 +00006239 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00006240
Steve Naroff8e6aee52009-07-23 01:01:38 +00006241 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00006242 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006243 // make sure we check the class hierarchy.
6244 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6245 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6246 E = lhsQID->qual_end(); I != E; ++I) {
6247 // when comparing an id<P> on lhs with a static type on rhs,
6248 // see if static class implements all of id's protocols, directly or
6249 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00006250 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006251 return false;
6252 }
6253 }
6254 // If there are no qualifiers and no interface, we have an 'id'.
6255 return true;
6256 }
Mike Stump11289f42009-09-09 15:08:12 +00006257 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006258 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6259 E = lhsQID->qual_end(); I != E; ++I) {
6260 ObjCProtocolDecl *lhsProto = *I;
6261 bool match = false;
6262
6263 // when comparing an id<P> on lhs with a static type on rhs,
6264 // see if static class implements all of id's protocols, directly or
6265 // through its super class and categories.
6266 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6267 E = rhsOPT->qual_end(); J != E; ++J) {
6268 ObjCProtocolDecl *rhsProto = *J;
6269 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6270 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6271 match = true;
6272 break;
6273 }
6274 }
Mike Stump11289f42009-09-09 15:08:12 +00006275 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006276 // make sure we check the class hierarchy.
6277 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6278 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6279 E = lhsQID->qual_end(); I != E; ++I) {
6280 // when comparing an id<P> on lhs with a static type on rhs,
6281 // see if static class implements all of id's protocols, directly or
6282 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00006283 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006284 match = true;
6285 break;
6286 }
6287 }
6288 }
6289 if (!match)
6290 return false;
6291 }
Mike Stump11289f42009-09-09 15:08:12 +00006292
Steve Naroff8e6aee52009-07-23 01:01:38 +00006293 return true;
6294 }
Mike Stump11289f42009-09-09 15:08:12 +00006295
Steve Naroff8e6aee52009-07-23 01:01:38 +00006296 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6297 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6298
Mike Stump11289f42009-09-09 15:08:12 +00006299 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00006300 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006301 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006302 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
6303 E = lhsOPT->qual_end(); I != E; ++I) {
6304 ObjCProtocolDecl *lhsProto = *I;
6305 bool match = false;
6306
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006307 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00006308 // see if static class implements all of id's protocols, directly or
6309 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006310 // First, lhs protocols in the qualifier list must be found, direct
6311 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006312 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6313 E = rhsQID->qual_end(); J != E; ++J) {
6314 ObjCProtocolDecl *rhsProto = *J;
6315 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6316 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6317 match = true;
6318 break;
6319 }
6320 }
6321 if (!match)
6322 return false;
6323 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006324
6325 // Static class's protocols, or its super class or category protocols
6326 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6327 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6328 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6329 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6330 // This is rather dubious but matches gcc's behavior. If lhs has
6331 // no type qualifier and its class has no static protocol(s)
6332 // assume that it is mismatch.
6333 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6334 return false;
6335 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6336 LHSInheritedProtocols.begin(),
6337 E = LHSInheritedProtocols.end(); I != E; ++I) {
6338 bool match = false;
6339 ObjCProtocolDecl *lhsProto = (*I);
6340 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6341 E = rhsQID->qual_end(); J != E; ++J) {
6342 ObjCProtocolDecl *rhsProto = *J;
6343 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6344 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6345 match = true;
6346 break;
6347 }
6348 }
6349 if (!match)
6350 return false;
6351 }
6352 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00006353 return true;
6354 }
6355 return false;
6356}
6357
Eli Friedman47f77112008-08-22 00:56:42 +00006358/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006359/// compatible for assignment from RHS to LHS. This handles validation of any
6360/// protocol qualifiers on the LHS or RHS.
6361///
Steve Naroff7cae42b2009-07-10 23:34:53 +00006362bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6363 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00006364 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6365 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6366
Steve Naroff1329fa02009-07-15 18:40:39 +00006367 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00006368 if (LHS->isObjCUnqualifiedIdOrClass() ||
6369 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00006370 return true;
6371
John McCall8b07ec22010-05-15 11:32:37 +00006372 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00006373 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6374 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00006375 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006376
6377 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6378 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6379 QualType(RHSOPT,0));
6380
John McCall8b07ec22010-05-15 11:32:37 +00006381 // If we have 2 user-defined types, fall into that path.
6382 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00006383 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006384
Steve Naroff8e6aee52009-07-23 01:01:38 +00006385 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006386}
6387
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006388/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00006389/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006390/// arguments in block literals. When passed as arguments, passing 'A*' where
6391/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6392/// not OK. For the return type, the opposite is not OK.
6393bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6394 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006395 const ObjCObjectPointerType *RHSOPT,
6396 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006397 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006398 return true;
6399
6400 if (LHSOPT->isObjCBuiltinType()) {
6401 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6402 }
6403
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006404 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006405 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6406 QualType(RHSOPT,0),
6407 false);
6408
6409 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6410 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6411 if (LHS && RHS) { // We have 2 user-defined types.
6412 if (LHS != RHS) {
6413 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006414 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006415 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006416 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006417 }
6418 else
6419 return true;
6420 }
6421 return false;
6422}
6423
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006424/// getIntersectionOfProtocols - This routine finds the intersection of set
6425/// of protocols inherited from two distinct objective-c pointer objects.
6426/// It is used to build composite qualifier list of the composite type of
6427/// the conditional expression involving two objective-c pointer objects.
6428static
6429void getIntersectionOfProtocols(ASTContext &Context,
6430 const ObjCObjectPointerType *LHSOPT,
6431 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006432 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006433
John McCall8b07ec22010-05-15 11:32:37 +00006434 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6435 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6436 assert(LHS->getInterface() && "LHS must have an interface base");
6437 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006438
6439 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6440 unsigned LHSNumProtocols = LHS->getNumProtocols();
6441 if (LHSNumProtocols > 0)
6442 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6443 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006444 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006445 Context.CollectInheritedProtocols(LHS->getInterface(),
6446 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006447 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6448 LHSInheritedProtocols.end());
6449 }
6450
6451 unsigned RHSNumProtocols = RHS->getNumProtocols();
6452 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00006453 ObjCProtocolDecl **RHSProtocols =
6454 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006455 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6456 if (InheritedProtocolSet.count(RHSProtocols[i]))
6457 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00006458 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006459 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006460 Context.CollectInheritedProtocols(RHS->getInterface(),
6461 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006462 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6463 RHSInheritedProtocols.begin(),
6464 E = RHSInheritedProtocols.end(); I != E; ++I)
6465 if (InheritedProtocolSet.count((*I)))
6466 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006467 }
6468}
6469
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006470/// areCommonBaseCompatible - Returns common base class of the two classes if
6471/// one found. Note that this is O'2 algorithm. But it will be called as the
6472/// last type comparison in a ?-exp of ObjC pointer types before a
6473/// warning is issued. So, its invokation is extremely rare.
6474QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00006475 const ObjCObjectPointerType *Lptr,
6476 const ObjCObjectPointerType *Rptr) {
6477 const ObjCObjectType *LHS = Lptr->getObjectType();
6478 const ObjCObjectType *RHS = Rptr->getObjectType();
6479 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6480 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00006481 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006482 return QualType();
6483
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006484 do {
John McCall8b07ec22010-05-15 11:32:37 +00006485 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006486 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006487 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00006488 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6489
6490 QualType Result = QualType(LHS, 0);
6491 if (!Protocols.empty())
6492 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6493 Result = getObjCObjectPointerType(Result);
6494 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006495 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006496 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006497
6498 return QualType();
6499}
6500
John McCall8b07ec22010-05-15 11:32:37 +00006501bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6502 const ObjCObjectType *RHS) {
6503 assert(LHS->getInterface() && "LHS is not an interface type");
6504 assert(RHS->getInterface() && "RHS is not an interface type");
6505
Chris Lattner49af6a42008-04-07 06:51:04 +00006506 // Verify that the base decls are compatible: the RHS must be a subclass of
6507 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00006508 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00006509 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006510
Chris Lattner49af6a42008-04-07 06:51:04 +00006511 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6512 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00006513 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00006514 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006515
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006516 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6517 // more detailed analysis is required.
6518 if (RHS->getNumProtocols() == 0) {
6519 // OK, if LHS is a superclass of RHS *and*
6520 // this superclass is assignment compatible with LHS.
6521 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006522 bool IsSuperClass =
6523 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6524 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006525 // OK if conversion of LHS to SuperClass results in narrowing of types
6526 // ; i.e., SuperClass may implement at least one of the protocols
6527 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6528 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6529 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006530 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006531 // If super class has no protocols, it is not a match.
6532 if (SuperClassInheritedProtocols.empty())
6533 return false;
6534
6535 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6536 LHSPE = LHS->qual_end();
6537 LHSPI != LHSPE; LHSPI++) {
6538 bool SuperImplementsProtocol = false;
6539 ObjCProtocolDecl *LHSProto = (*LHSPI);
6540
6541 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6542 SuperClassInheritedProtocols.begin(),
6543 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6544 ObjCProtocolDecl *SuperClassProto = (*I);
6545 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6546 SuperImplementsProtocol = true;
6547 break;
6548 }
6549 }
6550 if (!SuperImplementsProtocol)
6551 return false;
6552 }
6553 return true;
6554 }
6555 return false;
6556 }
Mike Stump11289f42009-09-09 15:08:12 +00006557
John McCall8b07ec22010-05-15 11:32:37 +00006558 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6559 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00006560 LHSPI != LHSPE; LHSPI++) {
6561 bool RHSImplementsProtocol = false;
6562
6563 // If the RHS doesn't implement the protocol on the left, the types
6564 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00006565 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6566 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00006567 RHSPI != RHSPE; RHSPI++) {
6568 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00006569 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00006570 break;
6571 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006572 }
6573 // FIXME: For better diagnostics, consider passing back the protocol name.
6574 if (!RHSImplementsProtocol)
6575 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00006576 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006577 // The RHS implements all protocols listed on the LHS.
6578 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00006579}
6580
Steve Naroffb7605152009-02-12 17:52:19 +00006581bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6582 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00006583 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6584 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006585
Steve Naroff7cae42b2009-07-10 23:34:53 +00006586 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00006587 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006588
6589 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6590 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00006591}
6592
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006593bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6594 return canAssignObjCInterfaces(
6595 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6596 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6597}
6598
Mike Stump11289f42009-09-09 15:08:12 +00006599/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00006600/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00006601/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00006602/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006603bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6604 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006605 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00006606 return hasSameType(LHS, RHS);
6607
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006608 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00006609}
6610
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006611bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00006612 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006613}
6614
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006615bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6616 return !mergeTypes(LHS, RHS, true).isNull();
6617}
6618
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006619/// mergeTransparentUnionType - if T is a transparent union type and a member
6620/// of T is compatible with SubType, return the merged type, else return
6621/// QualType()
6622QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6623 bool OfBlockPointer,
6624 bool Unqualified) {
6625 if (const RecordType *UT = T->getAsUnionType()) {
6626 RecordDecl *UD = UT->getDecl();
6627 if (UD->hasAttr<TransparentUnionAttr>()) {
6628 for (RecordDecl::field_iterator it = UD->field_begin(),
6629 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00006630 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006631 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6632 if (!MT.isNull())
6633 return MT;
6634 }
6635 }
6636 }
6637
6638 return QualType();
6639}
6640
6641/// mergeFunctionArgumentTypes - merge two types which appear as function
6642/// argument types
6643QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
6644 bool OfBlockPointer,
6645 bool Unqualified) {
6646 // GNU extension: two types are compatible if they appear as a function
6647 // argument, one of the types is a transparent union type and the other
6648 // type is compatible with a union member
6649 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6650 Unqualified);
6651 if (!lmerge.isNull())
6652 return lmerge;
6653
6654 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6655 Unqualified);
6656 if (!rmerge.isNull())
6657 return rmerge;
6658
6659 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6660}
6661
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006662QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006663 bool OfBlockPointer,
6664 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00006665 const FunctionType *lbase = lhs->getAs<FunctionType>();
6666 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006667 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6668 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00006669 bool allLTypes = true;
6670 bool allRTypes = true;
6671
6672 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006673 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00006674 if (OfBlockPointer) {
6675 QualType RHS = rbase->getResultType();
6676 QualType LHS = lbase->getResultType();
6677 bool UnqualifiedResult = Unqualified;
6678 if (!UnqualifiedResult)
6679 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006680 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00006681 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006682 else
John McCall8c6b56f2010-12-15 01:06:38 +00006683 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6684 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006685 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006686
6687 if (Unqualified)
6688 retType = retType.getUnqualifiedType();
6689
6690 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6691 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6692 if (Unqualified) {
6693 LRetType = LRetType.getUnqualifiedType();
6694 RRetType = RRetType.getUnqualifiedType();
6695 }
6696
6697 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006698 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006699 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006700 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006701
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00006702 // FIXME: double check this
6703 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6704 // rbase->getRegParmAttr() != 0 &&
6705 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00006706 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6707 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00006708
Douglas Gregor8c940862010-01-18 17:14:39 +00006709 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00006710 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00006711 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006712
John McCall8c6b56f2010-12-15 01:06:38 +00006713 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00006714 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6715 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00006716 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6717 return QualType();
6718
John McCall31168b02011-06-15 23:02:42 +00006719 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6720 return QualType();
6721
John McCall8c6b56f2010-12-15 01:06:38 +00006722 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6723 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00006724
Rafael Espindola8778c282012-11-29 16:09:03 +00006725 if (lbaseInfo.getNoReturn() != NoReturn)
6726 allLTypes = false;
6727 if (rbaseInfo.getNoReturn() != NoReturn)
6728 allRTypes = false;
6729
John McCall31168b02011-06-15 23:02:42 +00006730 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00006731
Eli Friedman47f77112008-08-22 00:56:42 +00006732 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006733 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6734 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006735 unsigned lproto_nargs = lproto->getNumArgs();
6736 unsigned rproto_nargs = rproto->getNumArgs();
6737
6738 // Compatible functions must have the same number of arguments
6739 if (lproto_nargs != rproto_nargs)
6740 return QualType();
6741
6742 // Variadic and non-variadic functions aren't compatible
6743 if (lproto->isVariadic() != rproto->isVariadic())
6744 return QualType();
6745
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00006746 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6747 return QualType();
6748
Fariborz Jahanian97676972011-09-28 21:52:05 +00006749 if (LangOpts.ObjCAutoRefCount &&
6750 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6751 return QualType();
6752
Eli Friedman47f77112008-08-22 00:56:42 +00006753 // Check argument compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006754 SmallVector<QualType, 10> types;
Eli Friedman47f77112008-08-22 00:56:42 +00006755 for (unsigned i = 0; i < lproto_nargs; i++) {
6756 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
6757 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006758 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
6759 OfBlockPointer,
6760 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006761 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006762
6763 if (Unqualified)
6764 argtype = argtype.getUnqualifiedType();
6765
Eli Friedman47f77112008-08-22 00:56:42 +00006766 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006767 if (Unqualified) {
6768 largtype = largtype.getUnqualifiedType();
6769 rargtype = rargtype.getUnqualifiedType();
6770 }
6771
Chris Lattner465fa322008-10-05 17:34:18 +00006772 if (getCanonicalType(argtype) != getCanonicalType(largtype))
6773 allLTypes = false;
6774 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
6775 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00006776 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00006777
Eli Friedman47f77112008-08-22 00:56:42 +00006778 if (allLTypes) return lhs;
6779 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006780
6781 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
6782 EPI.ExtInfo = einfo;
6783 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006784 }
6785
6786 if (lproto) allRTypes = false;
6787 if (rproto) allLTypes = false;
6788
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006789 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00006790 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006791 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006792 if (proto->isVariadic()) return QualType();
6793 // Check that the types are compatible with the types that
6794 // would result from default argument promotions (C99 6.7.5.3p15).
6795 // The only types actually affected are promotable integer
6796 // types and floats, which would be passed as a different
6797 // type depending on whether the prototype is visible.
6798 unsigned proto_nargs = proto->getNumArgs();
6799 for (unsigned i = 0; i < proto_nargs; ++i) {
6800 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00006801
Eli Friedman448ce402012-08-30 00:44:15 +00006802 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00006803 // to pass enum values.
Eli Friedman448ce402012-08-30 00:44:15 +00006804 if (const EnumType *Enum = argTy->getAs<EnumType>()) {
6805 argTy = Enum->getDecl()->getIntegerType();
6806 if (argTy.isNull())
6807 return QualType();
6808 }
Douglas Gregor2973d402010-02-03 19:27:29 +00006809
Eli Friedman47f77112008-08-22 00:56:42 +00006810 if (argTy->isPromotableIntegerType() ||
6811 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
6812 return QualType();
6813 }
6814
6815 if (allLTypes) return lhs;
6816 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006817
6818 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
6819 EPI.ExtInfo = einfo;
Eli Friedman47f77112008-08-22 00:56:42 +00006820 return getFunctionType(retType, proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00006821 proto->getNumArgs(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006822 }
6823
6824 if (allLTypes) return lhs;
6825 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00006826 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00006827}
6828
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006829QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006830 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006831 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00006832 // C++ [expr]: If an expression initially has the type "reference to T", the
6833 // type is adjusted to "T" prior to any further analysis, the expression
6834 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006835 // expression is an lvalue unless the reference is an rvalue reference and
6836 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00006837 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
6838 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006839
6840 if (Unqualified) {
6841 LHS = LHS.getUnqualifiedType();
6842 RHS = RHS.getUnqualifiedType();
6843 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00006844
Eli Friedman47f77112008-08-22 00:56:42 +00006845 QualType LHSCan = getCanonicalType(LHS),
6846 RHSCan = getCanonicalType(RHS);
6847
6848 // If two types are identical, they are compatible.
6849 if (LHSCan == RHSCan)
6850 return LHS;
6851
John McCall8ccfcb52009-09-24 19:53:00 +00006852 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006853 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6854 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00006855 if (LQuals != RQuals) {
6856 // If any of these qualifiers are different, we have a type
6857 // mismatch.
6858 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00006859 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
6860 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00006861 return QualType();
6862
6863 // Exactly one GC qualifier difference is allowed: __strong is
6864 // okay if the other type has no GC qualifier but is an Objective
6865 // C object pointer (i.e. implicitly strong by default). We fix
6866 // this by pretending that the unqualified type was actually
6867 // qualified __strong.
6868 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6869 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6870 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6871
6872 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6873 return QualType();
6874
6875 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
6876 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
6877 }
6878 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
6879 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
6880 }
Eli Friedman47f77112008-08-22 00:56:42 +00006881 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00006882 }
6883
6884 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00006885
Eli Friedmandcca6332009-06-01 01:22:52 +00006886 Type::TypeClass LHSClass = LHSCan->getTypeClass();
6887 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00006888
Chris Lattnerfd652912008-01-14 05:45:46 +00006889 // We want to consider the two function types to be the same for these
6890 // comparisons, just force one to the other.
6891 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
6892 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00006893
6894 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00006895 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
6896 LHSClass = Type::ConstantArray;
6897 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
6898 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00006899
John McCall8b07ec22010-05-15 11:32:37 +00006900 // ObjCInterfaces are just specialized ObjCObjects.
6901 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
6902 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
6903
Nate Begemance4d7fc2008-04-18 23:10:10 +00006904 // Canonicalize ExtVector -> Vector.
6905 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
6906 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00006907
Chris Lattner95554662008-04-07 05:43:21 +00006908 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00006909 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00006910 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00006911 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00006912 // Compatibility is based on the underlying type, not the promotion
6913 // type.
John McCall9dd450b2009-09-21 23:43:11 +00006914 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00006915 QualType TINT = ETy->getDecl()->getIntegerType();
6916 if (!TINT.isNull() && hasSameType(TINT, RHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00006917 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00006918 }
John McCall9dd450b2009-09-21 23:43:11 +00006919 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00006920 QualType TINT = ETy->getDecl()->getIntegerType();
6921 if (!TINT.isNull() && hasSameType(TINT, LHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00006922 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00006923 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00006924 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00006925 if (OfBlockPointer && !BlockReturnType) {
6926 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
6927 return LHS;
6928 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
6929 return RHS;
6930 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00006931
Eli Friedman47f77112008-08-22 00:56:42 +00006932 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00006933 }
Eli Friedman47f77112008-08-22 00:56:42 +00006934
Steve Naroffc6edcbd2008-01-09 22:43:08 +00006935 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00006936 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006937#define TYPE(Class, Base)
6938#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00006939#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006940#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
6941#define DEPENDENT_TYPE(Class, Base) case Type::Class:
6942#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00006943 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006944
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006945 case Type::LValueReference:
6946 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006947 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00006948 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006949
John McCall8b07ec22010-05-15 11:32:37 +00006950 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006951 case Type::IncompleteArray:
6952 case Type::VariableArray:
6953 case Type::FunctionProto:
6954 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00006955 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006956
Chris Lattnerfd652912008-01-14 05:45:46 +00006957 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00006958 {
6959 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006960 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
6961 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006962 if (Unqualified) {
6963 LHSPointee = LHSPointee.getUnqualifiedType();
6964 RHSPointee = RHSPointee.getUnqualifiedType();
6965 }
6966 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
6967 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006968 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00006969 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00006970 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00006971 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00006972 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00006973 return getPointerType(ResultType);
6974 }
Steve Naroff68e167d2008-12-10 17:49:55 +00006975 case Type::BlockPointer:
6976 {
6977 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006978 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
6979 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006980 if (Unqualified) {
6981 LHSPointee = LHSPointee.getUnqualifiedType();
6982 RHSPointee = RHSPointee.getUnqualifiedType();
6983 }
6984 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
6985 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00006986 if (ResultType.isNull()) return QualType();
6987 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
6988 return LHS;
6989 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
6990 return RHS;
6991 return getBlockPointerType(ResultType);
6992 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00006993 case Type::Atomic:
6994 {
6995 // Merge two pointer types, while trying to preserve typedef info
6996 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
6997 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
6998 if (Unqualified) {
6999 LHSValue = LHSValue.getUnqualifiedType();
7000 RHSValue = RHSValue.getUnqualifiedType();
7001 }
7002 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7003 Unqualified);
7004 if (ResultType.isNull()) return QualType();
7005 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7006 return LHS;
7007 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7008 return RHS;
7009 return getAtomicType(ResultType);
7010 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007011 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00007012 {
7013 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7014 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7015 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7016 return QualType();
7017
7018 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7019 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007020 if (Unqualified) {
7021 LHSElem = LHSElem.getUnqualifiedType();
7022 RHSElem = RHSElem.getUnqualifiedType();
7023 }
7024
7025 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007026 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00007027 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7028 return LHS;
7029 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7030 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00007031 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7032 ArrayType::ArraySizeModifier(), 0);
7033 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7034 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007035 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7036 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00007037 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7038 return LHS;
7039 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7040 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007041 if (LVAT) {
7042 // FIXME: This isn't correct! But tricky to implement because
7043 // the array's size has to be the size of LHS, but the type
7044 // has to be different.
7045 return LHS;
7046 }
7047 if (RVAT) {
7048 // FIXME: This isn't correct! But tricky to implement because
7049 // the array's size has to be the size of RHS, but the type
7050 // has to be different.
7051 return RHS;
7052 }
Eli Friedman3e62c212008-08-22 01:48:21 +00007053 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7054 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00007055 return getIncompleteArrayType(ResultType,
7056 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007057 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007058 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007059 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007060 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007061 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00007062 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00007063 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007064 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00007065 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00007066 case Type::Complex:
7067 // Distinct complex types are incompatible.
7068 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007069 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00007070 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00007071 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7072 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00007073 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00007074 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00007075 case Type::ObjCObject: {
7076 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00007077 // FIXME: This should be type compatibility, e.g. whether
7078 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00007079 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7080 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7081 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00007082 return LHS;
7083
Eli Friedman47f77112008-08-22 00:56:42 +00007084 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00007085 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007086 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007087 if (OfBlockPointer) {
7088 if (canAssignObjCInterfacesInBlockPointer(
7089 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007090 RHS->getAs<ObjCObjectPointerType>(),
7091 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00007092 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007093 return QualType();
7094 }
John McCall9dd450b2009-09-21 23:43:11 +00007095 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7096 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007097 return LHS;
7098
Steve Naroffc68cfcf2008-12-10 22:14:21 +00007099 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00007100 }
Steve Naroff32e44c02007-10-15 20:41:53 +00007101 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007102
David Blaikie8a40f702012-01-17 06:56:22 +00007103 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00007104}
Ted Kremenekfc581a92007-10-31 17:10:13 +00007105
Fariborz Jahanian97676972011-09-28 21:52:05 +00007106bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7107 const FunctionProtoType *FromFunctionType,
7108 const FunctionProtoType *ToFunctionType) {
7109 if (FromFunctionType->hasAnyConsumedArgs() !=
7110 ToFunctionType->hasAnyConsumedArgs())
7111 return false;
7112 FunctionProtoType::ExtProtoInfo FromEPI =
7113 FromFunctionType->getExtProtoInfo();
7114 FunctionProtoType::ExtProtoInfo ToEPI =
7115 ToFunctionType->getExtProtoInfo();
7116 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
7117 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
7118 ArgIdx != NumArgs; ++ArgIdx) {
7119 if (FromEPI.ConsumedArguments[ArgIdx] !=
7120 ToEPI.ConsumedArguments[ArgIdx])
7121 return false;
7122 }
7123 return true;
7124}
7125
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007126/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7127/// 'RHS' attributes and returns the merged version; including for function
7128/// return types.
7129QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7130 QualType LHSCan = getCanonicalType(LHS),
7131 RHSCan = getCanonicalType(RHS);
7132 // If two types are identical, they are compatible.
7133 if (LHSCan == RHSCan)
7134 return LHS;
7135 if (RHSCan->isFunctionType()) {
7136 if (!LHSCan->isFunctionType())
7137 return QualType();
7138 QualType OldReturnType =
7139 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
7140 QualType NewReturnType =
7141 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
7142 QualType ResReturnType =
7143 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7144 if (ResReturnType.isNull())
7145 return QualType();
7146 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7147 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7148 // In either case, use OldReturnType to build the new function type.
7149 const FunctionType *F = LHS->getAs<FunctionType>();
7150 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00007151 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7152 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007153 QualType ResultType
7154 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00007155 FPT->getNumArgs(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007156 return ResultType;
7157 }
7158 }
7159 return QualType();
7160 }
7161
7162 // If the qualifiers are different, the types can still be merged.
7163 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7164 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7165 if (LQuals != RQuals) {
7166 // If any of these qualifiers are different, we have a type mismatch.
7167 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7168 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7169 return QualType();
7170
7171 // Exactly one GC qualifier difference is allowed: __strong is
7172 // okay if the other type has no GC qualifier but is an Objective
7173 // C object pointer (i.e. implicitly strong by default). We fix
7174 // this by pretending that the unqualified type was actually
7175 // qualified __strong.
7176 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7177 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7178 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7179
7180 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7181 return QualType();
7182
7183 if (GC_L == Qualifiers::Strong)
7184 return LHS;
7185 if (GC_R == Qualifiers::Strong)
7186 return RHS;
7187 return QualType();
7188 }
7189
7190 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7191 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7192 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7193 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7194 if (ResQT == LHSBaseQT)
7195 return LHS;
7196 if (ResQT == RHSBaseQT)
7197 return RHS;
7198 }
7199 return QualType();
7200}
7201
Chris Lattner4ba0cef2008-04-07 07:01:58 +00007202//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007203// Integer Predicates
7204//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00007205
Jay Foad39c79802011-01-12 09:06:06 +00007206unsigned ASTContext::getIntWidth(QualType T) const {
John McCall424cec92011-01-19 06:33:43 +00007207 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00007208 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00007209 if (T->isBooleanType())
7210 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00007211 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007212 return (unsigned)getTypeSize(T);
7213}
7214
Abramo Bagnara13640492012-09-09 10:21:24 +00007215QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007216 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00007217
7218 // Turn <4 x signed int> -> <4 x unsigned int>
7219 if (const VectorType *VTy = T->getAs<VectorType>())
7220 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00007221 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00007222
7223 // For enums, we return the unsigned version of the base type.
7224 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007225 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00007226
7227 const BuiltinType *BTy = T->getAs<BuiltinType>();
7228 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007229 switch (BTy->getKind()) {
7230 case BuiltinType::Char_S:
7231 case BuiltinType::SChar:
7232 return UnsignedCharTy;
7233 case BuiltinType::Short:
7234 return UnsignedShortTy;
7235 case BuiltinType::Int:
7236 return UnsignedIntTy;
7237 case BuiltinType::Long:
7238 return UnsignedLongTy;
7239 case BuiltinType::LongLong:
7240 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00007241 case BuiltinType::Int128:
7242 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007243 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007244 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007245 }
7246}
7247
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00007248ASTMutationListener::~ASTMutationListener() { }
7249
Chris Lattnerecd79c62009-06-14 00:45:47 +00007250
7251//===----------------------------------------------------------------------===//
7252// Builtin Type Computation
7253//===----------------------------------------------------------------------===//
7254
7255/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00007256/// pointer over the consumed characters. This returns the resultant type. If
7257/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7258/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7259/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007260///
7261/// RequiresICE is filled in on return to indicate whether the value is required
7262/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00007263static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00007264 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007265 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00007266 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00007267 // Modifiers.
7268 int HowLong = 0;
7269 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007270 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00007271
Chris Lattnerdc226c22010-10-01 22:42:38 +00007272 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00007273 bool Done = false;
7274 while (!Done) {
7275 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00007276 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00007277 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007278 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00007279 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007280 case 'S':
7281 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7282 assert(!Signed && "Can't use 'S' modifier multiple times!");
7283 Signed = true;
7284 break;
7285 case 'U':
7286 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7287 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7288 Unsigned = true;
7289 break;
7290 case 'L':
7291 assert(HowLong <= 2 && "Can't have LLLL modifier");
7292 ++HowLong;
7293 break;
7294 }
7295 }
7296
7297 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00007298
Chris Lattnerecd79c62009-06-14 00:45:47 +00007299 // Read the base type.
7300 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00007301 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007302 case 'v':
7303 assert(HowLong == 0 && !Signed && !Unsigned &&
7304 "Bad modifiers used with 'v'!");
7305 Type = Context.VoidTy;
7306 break;
7307 case 'f':
7308 assert(HowLong == 0 && !Signed && !Unsigned &&
7309 "Bad modifiers used with 'f'!");
7310 Type = Context.FloatTy;
7311 break;
7312 case 'd':
7313 assert(HowLong < 2 && !Signed && !Unsigned &&
7314 "Bad modifiers used with 'd'!");
7315 if (HowLong)
7316 Type = Context.LongDoubleTy;
7317 else
7318 Type = Context.DoubleTy;
7319 break;
7320 case 's':
7321 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7322 if (Unsigned)
7323 Type = Context.UnsignedShortTy;
7324 else
7325 Type = Context.ShortTy;
7326 break;
7327 case 'i':
7328 if (HowLong == 3)
7329 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7330 else if (HowLong == 2)
7331 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7332 else if (HowLong == 1)
7333 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7334 else
7335 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7336 break;
7337 case 'c':
7338 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7339 if (Signed)
7340 Type = Context.SignedCharTy;
7341 else if (Unsigned)
7342 Type = Context.UnsignedCharTy;
7343 else
7344 Type = Context.CharTy;
7345 break;
7346 case 'b': // boolean
7347 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7348 Type = Context.BoolTy;
7349 break;
7350 case 'z': // size_t.
7351 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7352 Type = Context.getSizeType();
7353 break;
7354 case 'F':
7355 Type = Context.getCFConstantStringType();
7356 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00007357 case 'G':
7358 Type = Context.getObjCIdType();
7359 break;
7360 case 'H':
7361 Type = Context.getObjCSelType();
7362 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00007363 case 'M':
7364 Type = Context.getObjCSuperType();
7365 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007366 case 'a':
7367 Type = Context.getBuiltinVaListType();
7368 assert(!Type.isNull() && "builtin va list type not initialized!");
7369 break;
7370 case 'A':
7371 // This is a "reference" to a va_list; however, what exactly
7372 // this means depends on how va_list is defined. There are two
7373 // different kinds of va_list: ones passed by value, and ones
7374 // passed by reference. An example of a by-value va_list is
7375 // x86, where va_list is a char*. An example of by-ref va_list
7376 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7377 // we want this argument to be a char*&; for x86-64, we want
7378 // it to be a __va_list_tag*.
7379 Type = Context.getBuiltinVaListType();
7380 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007381 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00007382 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007383 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00007384 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007385 break;
7386 case 'V': {
7387 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007388 unsigned NumElements = strtoul(Str, &End, 10);
7389 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007390 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00007391
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007392 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7393 RequiresICE, false);
7394 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00007395
7396 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00007397 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00007398 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007399 break;
7400 }
Douglas Gregorfed66992012-06-07 18:08:25 +00007401 case 'E': {
7402 char *End;
7403
7404 unsigned NumElements = strtoul(Str, &End, 10);
7405 assert(End != Str && "Missing vector size");
7406
7407 Str = End;
7408
7409 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7410 false);
7411 Type = Context.getExtVectorType(ElementType, NumElements);
7412 break;
7413 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007414 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007415 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7416 false);
7417 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007418 Type = Context.getComplexType(ElementType);
7419 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00007420 }
7421 case 'Y' : {
7422 Type = Context.getPointerDiffType();
7423 break;
7424 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00007425 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00007426 Type = Context.getFILEType();
7427 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007428 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007429 return QualType();
7430 }
Mike Stump2adb4da2009-07-28 23:47:15 +00007431 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00007432 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00007433 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00007434 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00007435 else
7436 Type = Context.getjmp_bufType();
7437
Mike Stump2adb4da2009-07-28 23:47:15 +00007438 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007439 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00007440 return QualType();
7441 }
7442 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00007443 case 'K':
7444 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7445 Type = Context.getucontext_tType();
7446
7447 if (Type.isNull()) {
7448 Error = ASTContext::GE_Missing_ucontext;
7449 return QualType();
7450 }
7451 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00007452 case 'p':
7453 Type = Context.getProcessIDType();
7454 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00007455 }
Mike Stump11289f42009-09-09 15:08:12 +00007456
Chris Lattnerdc226c22010-10-01 22:42:38 +00007457 // If there are modifiers and if we're allowed to parse them, go for it.
7458 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007459 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00007460 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007461 default: Done = true; --Str; break;
7462 case '*':
7463 case '&': {
7464 // Both pointers and references can have their pointee types
7465 // qualified with an address space.
7466 char *End;
7467 unsigned AddrSpace = strtoul(Str, &End, 10);
7468 if (End != Str && AddrSpace != 0) {
7469 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7470 Str = End;
7471 }
7472 if (c == '*')
7473 Type = Context.getPointerType(Type);
7474 else
7475 Type = Context.getLValueReferenceType(Type);
7476 break;
7477 }
7478 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7479 case 'C':
7480 Type = Type.withConst();
7481 break;
7482 case 'D':
7483 Type = Context.getVolatileType(Type);
7484 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00007485 case 'R':
7486 Type = Type.withRestrict();
7487 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007488 }
7489 }
Chris Lattner84733392010-10-01 07:13:18 +00007490
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007491 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00007492 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00007493
Chris Lattnerecd79c62009-06-14 00:45:47 +00007494 return Type;
7495}
7496
7497/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00007498QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007499 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00007500 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007501 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00007502
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007503 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00007504
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007505 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007506 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007507 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7508 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007509 if (Error != GE_None)
7510 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007511
7512 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7513
Chris Lattnerecd79c62009-06-14 00:45:47 +00007514 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007515 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007516 if (Error != GE_None)
7517 return QualType();
7518
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007519 // If this argument is required to be an IntegerConstantExpression and the
7520 // caller cares, fill in the bitmask we return.
7521 if (RequiresICE && IntegerConstantArgs)
7522 *IntegerConstantArgs |= 1 << ArgTypes.size();
7523
Chris Lattnerecd79c62009-06-14 00:45:47 +00007524 // Do array -> pointer decay. The builtin should use the decayed type.
7525 if (Ty->isArrayType())
7526 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00007527
Chris Lattnerecd79c62009-06-14 00:45:47 +00007528 ArgTypes.push_back(Ty);
7529 }
7530
7531 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7532 "'.' should only occur at end of builtin type list!");
7533
John McCall991eb4b2010-12-21 00:44:39 +00007534 FunctionType::ExtInfo EI;
7535 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7536
7537 bool Variadic = (TypeStr[0] == '.');
7538
7539 // We really shouldn't be making a no-proto type here, especially in C++.
7540 if (ArgTypes.empty() && Variadic)
7541 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00007542
John McCalldb40c7f2010-12-14 08:05:40 +00007543 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00007544 EPI.ExtInfo = EI;
7545 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00007546
7547 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007548}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00007549
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007550GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
7551 GVALinkage External = GVA_StrongExternal;
7552
7553 Linkage L = FD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007554 switch (L) {
7555 case NoLinkage:
7556 case InternalLinkage:
7557 case UniqueExternalLinkage:
7558 return GVA_Internal;
7559
7560 case ExternalLinkage:
7561 switch (FD->getTemplateSpecializationKind()) {
7562 case TSK_Undeclared:
7563 case TSK_ExplicitSpecialization:
7564 External = GVA_StrongExternal;
7565 break;
7566
7567 case TSK_ExplicitInstantiationDefinition:
7568 return GVA_ExplicitTemplateInstantiation;
7569
7570 case TSK_ExplicitInstantiationDeclaration:
7571 case TSK_ImplicitInstantiation:
7572 External = GVA_TemplateInstantiation;
7573 break;
7574 }
7575 }
7576
7577 if (!FD->isInlined())
7578 return External;
7579
David Blaikiebbafb8a2012-03-11 07:00:24 +00007580 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007581 // GNU or C99 inline semantics. Determine whether this symbol should be
7582 // externally visible.
7583 if (FD->isInlineDefinitionExternallyVisible())
7584 return External;
7585
7586 // C99 inline semantics, where the symbol is not externally visible.
7587 return GVA_C99Inline;
7588 }
7589
7590 // C++0x [temp.explicit]p9:
7591 // [ Note: The intent is that an inline function that is the subject of
7592 // an explicit instantiation declaration will still be implicitly
7593 // instantiated when used so that the body can be considered for
7594 // inlining, but that no out-of-line copy of the inline function would be
7595 // generated in the translation unit. -- end note ]
7596 if (FD->getTemplateSpecializationKind()
7597 == TSK_ExplicitInstantiationDeclaration)
7598 return GVA_C99Inline;
7599
7600 return GVA_CXXInline;
7601}
7602
7603GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
7604 // If this is a static data member, compute the kind of template
7605 // specialization. Otherwise, this variable is not part of a
7606 // template.
7607 TemplateSpecializationKind TSK = TSK_Undeclared;
7608 if (VD->isStaticDataMember())
7609 TSK = VD->getTemplateSpecializationKind();
7610
7611 Linkage L = VD->getLinkage();
Rafael Espindola6525f962013-01-02 04:19:07 +00007612 assert (!(L == ExternalLinkage && getLangOpts().CPlusPlus &&
7613 VD->getType()->getLinkage() == UniqueExternalLinkage));
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007614
7615 switch (L) {
7616 case NoLinkage:
7617 case InternalLinkage:
7618 case UniqueExternalLinkage:
7619 return GVA_Internal;
7620
7621 case ExternalLinkage:
7622 switch (TSK) {
7623 case TSK_Undeclared:
7624 case TSK_ExplicitSpecialization:
7625 return GVA_StrongExternal;
7626
7627 case TSK_ExplicitInstantiationDeclaration:
7628 llvm_unreachable("Variable should not be instantiated");
7629 // Fall through to treat this like any other instantiation.
7630
7631 case TSK_ExplicitInstantiationDefinition:
7632 return GVA_ExplicitTemplateInstantiation;
7633
7634 case TSK_ImplicitInstantiation:
7635 return GVA_TemplateInstantiation;
7636 }
7637 }
7638
David Blaikie8a40f702012-01-17 06:56:22 +00007639 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007640}
7641
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00007642bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007643 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7644 if (!VD->isFileVarDecl())
7645 return false;
Argyrios Kyrtzidisa98e8612011-09-13 21:35:00 +00007646 } else if (!isa<FunctionDecl>(D))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007647 return false;
7648
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007649 // Weak references don't produce any output by themselves.
7650 if (D->hasAttr<WeakRefAttr>())
7651 return false;
7652
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007653 // Aliases and used decls are required.
7654 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7655 return true;
7656
7657 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7658 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00007659 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00007660 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007661
7662 // Constructors and destructors are required.
7663 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7664 return true;
7665
John McCall6bd2a892013-01-25 22:31:03 +00007666 // The key function for a class is required. This rule only comes
7667 // into play when inline functions can be key functions, though.
7668 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7669 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7670 const CXXRecordDecl *RD = MD->getParent();
7671 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7672 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
7673 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7674 return true;
7675 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007676 }
7677 }
7678
7679 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7680
7681 // static, static inline, always_inline, and extern inline functions can
7682 // always be deferred. Normal inline functions can be deferred in C99/C++.
7683 // Implicit template instantiations can also be deferred in C++.
7684 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev79de4d42012-02-02 06:06:34 +00007685 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007686 return false;
7687 return true;
7688 }
Douglas Gregor87d81242011-09-10 00:22:34 +00007689
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007690 const VarDecl *VD = cast<VarDecl>(D);
7691 assert(VD->isFileVarDecl() && "Expected file scoped var");
7692
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007693 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7694 return false;
7695
Richard Smitha0e5e542012-11-12 21:38:00 +00007696 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007697 GVALinkage L = GetGVALinkageForVariable(VD);
Richard Smitha0e5e542012-11-12 21:38:00 +00007698 if (L != GVA_Internal && L != GVA_TemplateInstantiation)
7699 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007700
Richard Smitha0e5e542012-11-12 21:38:00 +00007701 // Variables that have destruction with side-effects are required.
7702 if (VD->getType().isDestructedType())
7703 return true;
7704
7705 // Variables that have initialization with side-effects are required.
7706 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
7707 return true;
7708
7709 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007710}
Charles Davis53c59df2010-08-16 03:33:14 +00007711
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007712CallingConv ASTContext::getDefaultCXXMethodCallConv(bool isVariadic) {
Charles Davis99202b32010-11-09 18:04:24 +00007713 // Pass through to the C++ ABI object
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007714 return ABI->getDefaultMethodCallConv(isVariadic);
7715}
7716
7717CallingConv ASTContext::getCanonicalCallConv(CallingConv CC) const {
John McCall359b8852013-01-25 22:30:49 +00007718 if (CC == CC_C && !LangOpts.MRTD &&
7719 getTargetInfo().getCXXABI().isMemberFunctionCCDefault())
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007720 return CC_Default;
7721 return CC;
Charles Davis99202b32010-11-09 18:04:24 +00007722}
7723
Jay Foad39c79802011-01-12 09:06:06 +00007724bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00007725 // Pass through to the C++ ABI object
7726 return ABI->isNearlyEmpty(RD);
7727}
7728
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007729MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00007730 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00007731 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00007732 case TargetCXXABI::GenericItanium:
7733 case TargetCXXABI::GenericARM:
7734 case TargetCXXABI::iOS:
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007735 return createItaniumMangleContext(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00007736 case TargetCXXABI::Microsoft:
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007737 return createMicrosoftMangleContext(*this, getDiagnostics());
7738 }
David Blaikie83d382b2011-09-23 05:06:16 +00007739 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007740}
7741
Charles Davis53c59df2010-08-16 03:33:14 +00007742CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007743
7744size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek7d39c9a2011-07-27 18:41:12 +00007745 return ASTRecordLayouts.getMemorySize()
7746 + llvm::capacity_in_bytes(ObjCLayouts)
7747 + llvm::capacity_in_bytes(KeyFunctions)
7748 + llvm::capacity_in_bytes(ObjCImpls)
7749 + llvm::capacity_in_bytes(BlockVarCopyInits)
7750 + llvm::capacity_in_bytes(DeclAttrs)
7751 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
7752 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
7753 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
7754 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
7755 + llvm::capacity_in_bytes(OverriddenMethods)
7756 + llvm::capacity_in_bytes(Types)
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007757 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet57928252011-08-14 14:28:49 +00007758 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007759}
Ted Kremenek540017e2011-10-06 05:00:56 +00007760
David Blaikie095deba2012-11-14 01:52:05 +00007761void ASTContext::addUnnamedTag(const TagDecl *Tag) {
7762 // FIXME: This mangling should be applied to function local classes too
7763 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl() ||
7764 !isa<CXXRecordDecl>(Tag->getParent()) || Tag->getLinkage() != ExternalLinkage)
7765 return;
7766
7767 std::pair<llvm::DenseMap<const DeclContext *, unsigned>::iterator, bool> P =
7768 UnnamedMangleContexts.insert(std::make_pair(Tag->getParent(), 0));
7769 UnnamedMangleNumbers.insert(std::make_pair(Tag, P.first->second++));
7770}
7771
7772int ASTContext::getUnnamedTagManglingNumber(const TagDecl *Tag) const {
7773 llvm::DenseMap<const TagDecl *, unsigned>::const_iterator I =
7774 UnnamedMangleNumbers.find(Tag);
7775 return I != UnnamedMangleNumbers.end() ? I->second : -1;
7776}
7777
Douglas Gregor63798542012-02-20 19:44:39 +00007778unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
7779 CXXRecordDecl *Lambda = CallOperator->getParent();
7780 return LambdaMangleContexts[Lambda->getDeclContext()]
7781 .getManglingNumber(CallOperator);
7782}
7783
7784
Ted Kremenek540017e2011-10-06 05:00:56 +00007785void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
7786 ParamIndices[D] = index;
7787}
7788
7789unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
7790 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
7791 assert(I != ParamIndices.end() &&
7792 "ParmIndices lacks entry set by ParmVarDecl");
7793 return I->second;
7794}