blob: e6dfd445adf29b2eaf51044dce2bf21a398342b8 [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 }
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000100 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
101 // When tag declaration (but not definition!) is part of the
102 // decl-specifier-seq of some other declaration, it doesn't get comment
103 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
104 return NULL;
105 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000106 // TODO: handle comments for function parameters properly.
107 if (isa<ParmVarDecl>(D))
108 return NULL;
109
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000110 // TODO: we could look up template parameter documentation in the template
111 // documentation.
112 if (isa<TemplateTypeParmDecl>(D) ||
113 isa<NonTypeTemplateParmDecl>(D) ||
114 isa<TemplateTemplateParmDecl>(D))
115 return NULL;
116
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000117 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000118
119 // If there are no comments anywhere, we won't find anything.
120 if (RawComments.empty())
121 return NULL;
122
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000123 // Find declaration location.
124 // For Objective-C declarations we generally don't expect to have multiple
125 // declarators, thus use declaration starting location as the "declaration
126 // location".
127 // For all other declarations multiple declarators are used quite frequently,
128 // so we use the location of the identifier as the "declaration location".
129 SourceLocation DeclLoc;
130 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000131 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +0000132 isa<RedeclarableTemplateDecl>(D) ||
133 isa<ClassTemplateSpecializationDecl>(D))
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000134 DeclLoc = D->getLocStart();
135 else
136 DeclLoc = D->getLocation();
137
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000138 // If the declaration doesn't map directly to a location in a file, we
139 // can't find the comment.
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000140 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
141 return NULL;
142
143 // Find the comment that occurs just after this declaration.
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000144 ArrayRef<RawComment *>::iterator Comment;
145 {
146 // When searching for comments during parsing, the comment we are looking
147 // for is usually among the last two comments we parsed -- check them
148 // first.
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +0000149 RawComment CommentAtDeclLoc(
150 SourceMgr, SourceRange(DeclLoc), false,
151 LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000152 BeforeThanCompare<RawComment> Compare(SourceMgr);
153 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
154 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
155 if (!Found && RawComments.size() >= 2) {
156 MaybeBeforeDecl--;
157 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
158 }
159
160 if (Found) {
161 Comment = MaybeBeforeDecl + 1;
162 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
163 &CommentAtDeclLoc, Compare));
164 } else {
165 // Slow path.
166 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
167 &CommentAtDeclLoc, Compare);
168 }
169 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000170
171 // Decompose the location for the declaration and find the beginning of the
172 // file buffer.
173 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
174
175 // First check whether we have a trailing comment.
176 if (Comment != RawComments.end() &&
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000177 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
Dmitri Gribenko44cd7e62012-07-06 23:27:33 +0000178 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D))) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000179 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000180 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000181 // Check that Doxygen trailing comment comes after the declaration, starts
182 // on the same line and in the same file as the declaration.
183 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
184 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
185 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
186 CommentBeginDecomp.second)) {
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000187 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000188 }
189 }
190
191 // The comment just after the declaration was not a trailing comment.
192 // Let's look at the previous comment.
193 if (Comment == RawComments.begin())
194 return NULL;
195 --Comment;
196
197 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000198 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000199 return NULL;
200
201 // Decompose the end of the comment.
202 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000203 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000204
205 // If the comment and the declaration aren't in the same file, then they
206 // aren't related.
207 if (DeclLocDecomp.first != CommentEndDecomp.first)
208 return NULL;
209
210 // Get the corresponding buffer.
211 bool Invalid = false;
212 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
213 &Invalid).data();
214 if (Invalid)
215 return NULL;
216
217 // Extract text between the comment and declaration.
218 StringRef Text(Buffer + CommentEndDecomp.second,
219 DeclLocDecomp.second - CommentEndDecomp.second);
220
Dmitri Gribenko7e8729b2012-06-27 23:43:37 +0000221 // There should be no other declarations or preprocessor directives between
222 // comment and declaration.
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000223 if (Text.find_first_of(",;{}#@") != StringRef::npos)
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000224 return NULL;
225
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000226 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000227}
228
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000229namespace {
230/// If we have a 'templated' declaration for a template, adjust 'D' to
231/// refer to the actual template.
Dmitri Gribenko90631802012-08-22 17:44:32 +0000232/// If we have an implicit instantiation, adjust 'D' to refer to template.
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000233const Decl *adjustDeclToTemplate(const Decl *D) {
Douglas Gregor35ceb272012-08-13 16:37:30 +0000234 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000235 // Is this function declaration part of a function template?
Douglas Gregor35ceb272012-08-13 16:37:30 +0000236 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko90631802012-08-22 17:44:32 +0000237 return FTD;
238
239 // Nothing to do if function is not an implicit instantiation.
240 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
241 return D;
242
243 // Function is an implicit instantiation of a function template?
244 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
245 return FTD;
246
247 // Function is instantiated from a member definition of a class template?
248 if (const FunctionDecl *MemberDecl =
249 FD->getInstantiatedFromMemberFunction())
250 return MemberDecl;
251
252 return D;
Douglas Gregor35ceb272012-08-13 16:37:30 +0000253 }
Dmitri Gribenko90631802012-08-22 17:44:32 +0000254 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
255 // Static data member is instantiated from a member definition of a class
256 // template?
257 if (VD->isStaticDataMember())
258 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
259 return MemberDecl;
260
261 return D;
262 }
263 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
264 // Is this class declaration part of a class template?
265 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
266 return CTD;
267
268 // Class is an implicit instantiation of a class template or partial
269 // specialization?
270 if (const ClassTemplateSpecializationDecl *CTSD =
271 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
272 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
273 return D;
274 llvm::PointerUnion<ClassTemplateDecl *,
275 ClassTemplatePartialSpecializationDecl *>
276 PU = CTSD->getSpecializedTemplateOrPartial();
277 return PU.is<ClassTemplateDecl*>() ?
278 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
279 static_cast<const Decl*>(
280 PU.get<ClassTemplatePartialSpecializationDecl *>());
281 }
282
283 // Class is instantiated from a member definition of a class template?
284 if (const MemberSpecializationInfo *Info =
285 CRD->getMemberSpecializationInfo())
286 return Info->getInstantiatedFrom();
287
288 return D;
289 }
290 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
291 // Enum is instantiated from a member definition of a class template?
292 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
293 return MemberDecl;
294
295 return D;
296 }
297 // FIXME: Adjust alias templates?
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000298 return D;
299}
300} // unnamed namespace
301
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000302const RawComment *ASTContext::getRawCommentForAnyRedecl(
303 const Decl *D,
304 const Decl **OriginalDecl) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000305 D = adjustDeclToTemplate(D);
Douglas Gregor35ceb272012-08-13 16:37:30 +0000306
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000307 // Check whether we have cached a comment for this declaration already.
308 {
309 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
310 RedeclComments.find(D);
311 if (Pos != RedeclComments.end()) {
312 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000313 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
314 if (OriginalDecl)
315 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000316 return Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000317 }
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000318 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000319 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000320
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000321 // Search for comments attached to declarations in the redeclaration chain.
322 const RawComment *RC = NULL;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000323 const Decl *OriginalDeclForRC = NULL;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000324 for (Decl::redecl_iterator I = D->redecls_begin(),
325 E = D->redecls_end();
326 I != E; ++I) {
327 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
328 RedeclComments.find(*I);
329 if (Pos != RedeclComments.end()) {
330 const RawCommentAndCacheFlags &Raw = Pos->second;
331 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
332 RC = Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000333 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000334 break;
335 }
336 } else {
337 RC = getRawCommentForDeclNoCache(*I);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000338 OriginalDeclForRC = *I;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000339 RawCommentAndCacheFlags Raw;
340 if (RC) {
341 Raw.setRaw(RC);
342 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
343 } else
344 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000345 Raw.setOriginalDecl(*I);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000346 RedeclComments[*I] = Raw;
347 if (RC)
348 break;
349 }
350 }
351
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000352 // If we found a comment, it should be a documentation comment.
353 assert(!RC || RC->isDocumentation());
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000354
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000355 if (OriginalDecl)
356 *OriginalDecl = OriginalDeclForRC;
357
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000358 // Update cache for every declaration in the redeclaration chain.
359 RawCommentAndCacheFlags Raw;
360 Raw.setRaw(RC);
361 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000362 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000363
364 for (Decl::redecl_iterator I = D->redecls_begin(),
365 E = D->redecls_end();
366 I != E; ++I) {
367 RawCommentAndCacheFlags &R = RedeclComments[*I];
368 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
369 R = Raw;
370 }
371
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000372 return RC;
373}
374
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000375static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
376 SmallVectorImpl<const NamedDecl *> &Redeclared) {
377 const DeclContext *DC = ObjCMethod->getDeclContext();
378 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
379 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
380 if (!ID)
381 return;
382 // Add redeclared method here.
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000383 for (ObjCInterfaceDecl::known_extensions_iterator
384 Ext = ID->known_extensions_begin(),
385 ExtEnd = ID->known_extensions_end();
386 Ext != ExtEnd; ++Ext) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000387 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000388 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000389 ObjCMethod->isInstanceMethod()))
390 Redeclared.push_back(RedeclaredMethod);
391 }
392 }
393}
394
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000395comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
396 const Decl *D) const {
397 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
398 ThisDeclInfo->CommentDecl = D;
399 ThisDeclInfo->IsFilled = false;
400 ThisDeclInfo->fill();
401 ThisDeclInfo->CommentDecl = FC->getDecl();
402 comments::FullComment *CFC =
403 new (*this) comments::FullComment(FC->getBlocks(),
404 ThisDeclInfo);
405 return CFC;
406
407}
408
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000409comments::FullComment *ASTContext::getCommentForDecl(
410 const Decl *D,
411 const Preprocessor *PP) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000412 D = adjustDeclToTemplate(D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000413
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000414 const Decl *Canonical = D->getCanonicalDecl();
415 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
416 ParsedComments.find(Canonical);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000417
418 if (Pos != ParsedComments.end()) {
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000419 if (Canonical != D) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000420 comments::FullComment *FC = Pos->second;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000421 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000422 return CFC;
423 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000424 return Pos->second;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000425 }
426
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000427 const Decl *OriginalDecl;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000428
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000429 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000430 if (!RC) {
431 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000432 SmallVector<const NamedDecl*, 8> Overridden;
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000433 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000434 if (OMD && OMD->isPropertyAccessor())
435 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
436 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
437 return cloneFullComment(FC, D);
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000438 if (OMD)
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000439 addRedeclaredMethods(OMD, Overridden);
440 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000441 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
442 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
443 return cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000444 }
Fariborz Jahanian6384fbb2013-05-02 15:44:16 +0000445 else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000446 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000447 // does not have one of its own.
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000448 QualType QT = TD->getUnderlyingType();
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000449 if (const TagType *TT = QT->getAs<TagType>())
450 if (const Decl *TD = TT->getDecl())
451 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000452 return cloneFullComment(FC, D);
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000453 }
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000454 else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
455 while (IC->getSuperClass()) {
456 IC = IC->getSuperClass();
457 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
458 return cloneFullComment(FC, D);
459 }
460 }
461 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
462 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
463 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
464 return cloneFullComment(FC, D);
465 }
466 else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
467 if (!(RD = RD->getDefinition()))
468 return NULL;
469 // Check non-virtual bases.
470 for (CXXRecordDecl::base_class_const_iterator I =
471 RD->bases_begin(), E = RD->bases_end(); I != E; ++I) {
Fariborz Jahanian5a2e4a22013-04-26 23:34:36 +0000472 if (I->isVirtual() || (I->getAccessSpecifier() != AS_public))
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000473 continue;
474 QualType Ty = I->getType();
475 if (Ty.isNull())
476 continue;
477 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
478 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
479 continue;
480
481 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
482 return cloneFullComment(FC, D);
483 }
484 }
485 // Check virtual bases.
486 for (CXXRecordDecl::base_class_const_iterator I =
487 RD->vbases_begin(), E = RD->vbases_end(); I != E; ++I) {
Fariborz Jahanian5a2e4a22013-04-26 23:34:36 +0000488 if (I->getAccessSpecifier() != AS_public)
489 continue;
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000490 QualType Ty = I->getType();
491 if (Ty.isNull())
492 continue;
493 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
494 if (!(VirtualBase= VirtualBase->getDefinition()))
495 continue;
496 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
497 return cloneFullComment(FC, D);
498 }
499 }
500 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000501 return NULL;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000502 }
503
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000504 // If the RawComment was attached to other redeclaration of this Decl, we
505 // should parse the comment in context of that other Decl. This is important
506 // because comments can contain references to parameter names which can be
507 // different across redeclarations.
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000508 if (D != OriginalDecl)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000509 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000510
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000511 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000512 ParsedComments[Canonical] = FC;
513 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000514}
515
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000516void
517ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
518 TemplateTemplateParmDecl *Parm) {
519 ID.AddInteger(Parm->getDepth());
520 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000521 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000522
523 TemplateParameterList *Params = Parm->getTemplateParameters();
524 ID.AddInteger(Params->size());
525 for (TemplateParameterList::const_iterator P = Params->begin(),
526 PEnd = Params->end();
527 P != PEnd; ++P) {
528 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
529 ID.AddInteger(0);
530 ID.AddBoolean(TTP->isParameterPack());
531 continue;
532 }
533
534 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
535 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000536 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000537 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000538 if (NTTP->isExpandedParameterPack()) {
539 ID.AddBoolean(true);
540 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000541 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
542 QualType T = NTTP->getExpansionType(I);
543 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
544 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000545 } else
546 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000547 continue;
548 }
549
550 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
551 ID.AddInteger(2);
552 Profile(ID, TTP);
553 }
554}
555
556TemplateTemplateParmDecl *
557ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000558 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000559 // Check if we already have a canonical template template parameter.
560 llvm::FoldingSetNodeID ID;
561 CanonicalTemplateTemplateParm::Profile(ID, TTP);
562 void *InsertPos = 0;
563 CanonicalTemplateTemplateParm *Canonical
564 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
565 if (Canonical)
566 return Canonical->getParam();
567
568 // Build a canonical template parameter list.
569 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000570 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000571 CanonParams.reserve(Params->size());
572 for (TemplateParameterList::const_iterator P = Params->begin(),
573 PEnd = Params->end();
574 P != PEnd; ++P) {
575 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
576 CanonParams.push_back(
577 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000578 SourceLocation(),
579 SourceLocation(),
580 TTP->getDepth(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000581 TTP->getIndex(), 0, false,
582 TTP->isParameterPack()));
583 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000584 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
585 QualType T = getCanonicalType(NTTP->getType());
586 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
587 NonTypeTemplateParmDecl *Param;
588 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000589 SmallVector<QualType, 2> ExpandedTypes;
590 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000591 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
592 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
593 ExpandedTInfos.push_back(
594 getTrivialTypeSourceInfo(ExpandedTypes.back()));
595 }
596
597 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000598 SourceLocation(),
599 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000600 NTTP->getDepth(),
601 NTTP->getPosition(), 0,
602 T,
603 TInfo,
604 ExpandedTypes.data(),
605 ExpandedTypes.size(),
606 ExpandedTInfos.data());
607 } else {
608 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000609 SourceLocation(),
610 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000611 NTTP->getDepth(),
612 NTTP->getPosition(), 0,
613 T,
614 NTTP->isParameterPack(),
615 TInfo);
616 }
617 CanonParams.push_back(Param);
618
619 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000620 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
621 cast<TemplateTemplateParmDecl>(*P)));
622 }
623
624 TemplateTemplateParmDecl *CanonTTP
625 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
626 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000627 TTP->getPosition(),
628 TTP->isParameterPack(),
629 0,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000630 TemplateParameterList::Create(*this, SourceLocation(),
631 SourceLocation(),
632 CanonParams.data(),
633 CanonParams.size(),
634 SourceLocation()));
635
636 // Get the new insert position for the node we care about.
637 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
638 assert(Canonical == 0 && "Shouldn't be in the map!");
639 (void)Canonical;
640
641 // Create the canonical template template parameter entry.
642 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
643 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
644 return CanonTTP;
645}
646
Charles Davis53c59df2010-08-16 03:33:14 +0000647CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000648 if (!LangOpts.CPlusPlus) return 0;
649
John McCall359b8852013-01-25 22:30:49 +0000650 switch (T.getCXXABI().getKind()) {
651 case TargetCXXABI::GenericARM:
652 case TargetCXXABI::iOS:
John McCall86353412010-08-21 22:46:04 +0000653 return CreateARMCXXABI(*this);
Tim Northover9bb857a2013-01-31 12:13:10 +0000654 case TargetCXXABI::GenericAArch64: // Same as Itanium at this level
John McCall359b8852013-01-25 22:30:49 +0000655 case TargetCXXABI::GenericItanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000656 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000657 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000658 return CreateMicrosoftCXXABI(*this);
659 }
David Blaikie8a40f702012-01-17 06:56:22 +0000660 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000661}
662
Douglas Gregore8bbc122011-09-02 00:18:52 +0000663static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000664 const LangOptions &LOpts) {
665 if (LOpts.FakeAddressSpaceMap) {
666 // The fake address space map must have a distinct entry for each
667 // language-specific address space.
668 static const unsigned FakeAddrSpaceMap[] = {
669 1, // opencl_global
670 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000671 3, // opencl_constant
672 4, // cuda_device
673 5, // cuda_constant
674 6 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000675 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000676 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000677 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000678 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000679 }
680}
681
Douglas Gregor7018d5b2011-09-01 20:23:19 +0000682ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000683 const TargetInfo *t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000684 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000685 Builtin::Context &builtins,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000686 unsigned size_reserve,
687 bool DelayInitialization)
688 : FunctionProtoTypes(this_()),
689 TemplateSpecializationTypes(this_()),
690 DependentTemplateSpecializationTypes(this_()),
691 SubstTemplateTemplateParmPacks(this_()),
692 GlobalNestedNameSpecifier(0),
693 Int128Decl(0), UInt128Decl(0),
Meador Inge5d3fb222012-06-16 03:34:49 +0000694 BuiltinVaListDecl(0),
Douglas Gregord53ae832012-01-17 18:09:05 +0000695 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Fariborz Jahanianf2578572012-08-30 18:49:41 +0000696 BOOLDecl(0),
Douglas Gregorbab8a962011-09-08 01:46:34 +0000697 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000698 FILEDecl(0),
Rafael Espindola6cfa82b2011-11-13 21:51:09 +0000699 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
700 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
701 cudaConfigureCallDecl(0),
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000702 NullTypeSourceInfo(QualType()),
703 FirstLocalImport(), LastLocalImport(),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000704 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000705 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000706 Idents(idents), Selectors(sels),
707 BuiltinInfo(builtins),
708 DeclarationNames(*this),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000709 ExternalSource(0), Listener(0),
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000710 Comments(SM), CommentsLoaded(false),
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000711 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000712 LastSDM(0, 0),
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +0000713 UniqueBlockByRefTypeID(0)
Douglas Gregore8bbc122011-09-02 00:18:52 +0000714{
Mike Stump11289f42009-09-09 15:08:12 +0000715 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000716 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000717
718 if (!DelayInitialization) {
719 assert(t && "No target supplied for ASTContext initialization");
720 InitBuiltinTypes(*t);
721 }
Daniel Dunbar221fa942008-08-11 04:54:23 +0000722}
723
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000724ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000725 // Release the DenseMaps associated with DeclContext objects.
726 // FIXME: Is this the ideal solution?
727 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000728
Douglas Gregor5b11d492010-07-25 17:53:33 +0000729 // Call all of the deallocation functions.
730 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
731 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor1a809332010-05-23 18:26:36 +0000732
Ted Kremenek076baeb2010-06-08 23:00:58 +0000733 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000734 // because they can contain DenseMaps.
735 for (llvm::DenseMap<const ObjCContainerDecl*,
736 const ASTRecordLayout*>::iterator
737 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
738 // Increment in loop to prevent using deallocated memory.
739 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
740 R->Destroy(*this);
741
Ted Kremenek076baeb2010-06-08 23:00:58 +0000742 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
743 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
744 // Increment in loop to prevent using deallocated memory.
745 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
746 R->Destroy(*this);
747 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000748
749 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
750 AEnd = DeclAttrs.end();
751 A != AEnd; ++A)
752 A->second->~AttrVec();
753}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000754
Douglas Gregor1a809332010-05-23 18:26:36 +0000755void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
756 Deallocations.push_back(std::make_pair(Callback, Data));
757}
758
Mike Stump11289f42009-09-09 15:08:12 +0000759void
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000760ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000761 ExternalSource.reset(Source.take());
762}
763
Chris Lattner4eb445d2007-01-26 01:27:23 +0000764void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000765 llvm::errs() << "\n*** AST Context Stats:\n";
766 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000767
Douglas Gregora30d0462009-05-26 14:40:08 +0000768 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000769#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000770#define ABSTRACT_TYPE(Name, Parent)
771#include "clang/AST/TypeNodes.def"
772 0 // Extra
773 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000774
Chris Lattner4eb445d2007-01-26 01:27:23 +0000775 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
776 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000777 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000778 }
779
Douglas Gregora30d0462009-05-26 14:40:08 +0000780 unsigned Idx = 0;
781 unsigned TotalBytes = 0;
782#define TYPE(Name, Parent) \
783 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000784 llvm::errs() << " " << counts[Idx] << " " << #Name \
785 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000786 TotalBytes += counts[Idx] * sizeof(Name##Type); \
787 ++Idx;
788#define ABSTRACT_TYPE(Name, Parent)
789#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000790
Chandler Carruth3c147a72011-07-04 05:32:14 +0000791 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
792
Douglas Gregor7454c562010-07-02 20:37:36 +0000793 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000794 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
795 << NumImplicitDefaultConstructors
796 << " implicit default constructors created\n";
797 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
798 << NumImplicitCopyConstructors
799 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000800 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000801 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
802 << NumImplicitMoveConstructors
803 << " implicit move constructors created\n";
804 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
805 << NumImplicitCopyAssignmentOperators
806 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000807 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000808 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
809 << NumImplicitMoveAssignmentOperators
810 << " implicit move assignment operators created\n";
811 llvm::errs() << NumImplicitDestructorsDeclared << "/"
812 << NumImplicitDestructors
813 << " implicit destructors created\n";
814
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000815 if (ExternalSource.get()) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000816 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000817 ExternalSource->PrintStats();
818 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000819
Douglas Gregor5b11d492010-07-25 17:53:33 +0000820 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000821}
822
Douglas Gregor801c99d2011-08-12 06:49:56 +0000823TypedefDecl *ASTContext::getInt128Decl() const {
824 if (!Int128Decl) {
825 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
826 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
827 getTranslationUnitDecl(),
828 SourceLocation(),
829 SourceLocation(),
830 &Idents.get("__int128_t"),
831 TInfo);
832 }
833
834 return Int128Decl;
835}
836
837TypedefDecl *ASTContext::getUInt128Decl() const {
838 if (!UInt128Decl) {
839 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
840 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
841 getTranslationUnitDecl(),
842 SourceLocation(),
843 SourceLocation(),
844 &Idents.get("__uint128_t"),
845 TInfo);
846 }
847
848 return UInt128Decl;
849}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000850
John McCall48f2d582009-10-23 23:03:21 +0000851void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000852 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000853 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000854 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000855}
856
Douglas Gregore8bbc122011-09-02 00:18:52 +0000857void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
858 assert((!this->Target || this->Target == &Target) &&
859 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000860 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000861
Douglas Gregore8bbc122011-09-02 00:18:52 +0000862 this->Target = &Target;
863
864 ABI.reset(createCXXABI(Target));
865 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
866
Chris Lattner970e54e2006-11-12 00:37:36 +0000867 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000868 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000869
Chris Lattner970e54e2006-11-12 00:37:36 +0000870 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000871 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000872 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000873 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000874 InitBuiltinType(CharTy, BuiltinType::Char_S);
875 else
876 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000877 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000878 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
879 InitBuiltinType(ShortTy, BuiltinType::Short);
880 InitBuiltinType(IntTy, BuiltinType::Int);
881 InitBuiltinType(LongTy, BuiltinType::Long);
882 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000883
Chris Lattner970e54e2006-11-12 00:37:36 +0000884 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000885 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
886 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
887 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
888 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
889 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000890
Chris Lattner970e54e2006-11-12 00:37:36 +0000891 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000892 InitBuiltinType(FloatTy, BuiltinType::Float);
893 InitBuiltinType(DoubleTy, BuiltinType::Double);
894 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000895
Chris Lattnerf122cef2009-04-30 02:43:43 +0000896 // GNU extension, 128-bit integers.
897 InitBuiltinType(Int128Ty, BuiltinType::Int128);
898 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
899
Aaron Ballmand428ff42013-05-04 16:56:22 +0000900 if (LangOpts.CPlusPlus && LangOpts.WChar) { // C++ 3.9.1p5
Eli Friedman786d0872011-04-30 19:24:24 +0000901 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattnerad3467e2010-12-25 23:25:43 +0000902 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
903 else // -fshort-wchar makes wchar_t be unsigned.
904 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
Aaron Ballmand428ff42013-05-04 16:56:22 +0000905 } else // C99 (or C++ using -fno-wchar)
Chris Lattner007cb022009-02-26 23:43:47 +0000906 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000907
James Molloy36365542012-05-04 10:55:22 +0000908 WIntTy = getFromTargetType(Target.getWIntType());
909
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000910 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
911 InitBuiltinType(Char16Ty, BuiltinType::Char16);
912 else // C99
913 Char16Ty = getFromTargetType(Target.getChar16Type());
914
915 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
916 InitBuiltinType(Char32Ty, BuiltinType::Char32);
917 else // C99
918 Char32Ty = getFromTargetType(Target.getChar32Type());
919
Douglas Gregor4619e432008-12-05 23:32:09 +0000920 // Placeholder type for type-dependent expressions whose type is
921 // completely unknown. No code should ever check a type against
922 // DependentTy and users should never see it; however, it is here to
923 // help diagnose failures to properly check for type-dependent
924 // expressions.
925 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000926
John McCall36e7fe32010-10-12 00:20:44 +0000927 // Placeholder type for functions.
928 InitBuiltinType(OverloadTy, BuiltinType::Overload);
929
John McCall0009fcc2011-04-26 20:42:42 +0000930 // Placeholder type for bound members.
931 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
932
John McCall526ab472011-10-25 17:37:35 +0000933 // Placeholder type for pseudo-objects.
934 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
935
John McCall31996342011-04-07 08:22:57 +0000936 // "any" type; useful for debugger-like clients.
937 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
938
John McCall8a6b59a2011-10-17 18:09:15 +0000939 // Placeholder type for unbridged ARC casts.
940 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
941
Eli Friedman34866c72012-08-31 00:14:07 +0000942 // Placeholder type for builtin functions.
943 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
944
Chris Lattner970e54e2006-11-12 00:37:36 +0000945 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000946 FloatComplexTy = getComplexType(FloatTy);
947 DoubleComplexTy = getComplexType(DoubleTy);
948 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000949
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000950 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000951 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
952 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000953 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000954
955 if (LangOpts.OpenCL) {
956 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
957 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
958 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
959 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
960 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
961 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +0000962
Guy Benyei61054192013-02-07 10:55:47 +0000963 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +0000964 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000965 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000966
967 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +0000968 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
969 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000970
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000971 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +0000972
973 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000974
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000975 // void * type
976 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000977
978 // nullptr type (C++0x 2.14.7)
979 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000980
981 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
982 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +0000983
984 // Builtin type used to help define __builtin_va_list.
985 VaListTagTy = QualType();
Chris Lattner970e54e2006-11-12 00:37:36 +0000986}
987
David Blaikie9c902b52011-09-25 23:23:43 +0000988DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000989 return SourceMgr.getDiagnostics();
990}
991
Douglas Gregor561eceb2010-08-30 16:49:28 +0000992AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
993 AttrVec *&Result = DeclAttrs[D];
994 if (!Result) {
995 void *Mem = Allocate(sizeof(AttrVec));
996 Result = new (Mem) AttrVec;
997 }
998
999 return *Result;
1000}
1001
1002/// \brief Erase the attributes corresponding to the given declaration.
1003void ASTContext::eraseDeclAttrs(const Decl *D) {
1004 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1005 if (Pos != DeclAttrs.end()) {
1006 Pos->second->~AttrVec();
1007 DeclAttrs.erase(Pos);
1008 }
1009}
1010
Douglas Gregor86d142a2009-10-08 07:24:58 +00001011MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001012ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001013 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +00001014 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001015 = InstantiatedFromStaticDataMember.find(Var);
1016 if (Pos == InstantiatedFromStaticDataMember.end())
1017 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001018
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001019 return Pos->second;
1020}
1021
Mike Stump11289f42009-09-09 15:08:12 +00001022void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001023ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001024 TemplateSpecializationKind TSK,
1025 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001026 assert(Inst->isStaticDataMember() && "Not a static data member");
1027 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1028 assert(!InstantiatedFromStaticDataMember[Inst] &&
1029 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +00001030 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001031 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001032}
1033
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001034FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1035 const FunctionDecl *FD){
1036 assert(FD && "Specialization is 0");
1037 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001038 = ClassScopeSpecializationPattern.find(FD);
1039 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001040 return 0;
1041
1042 return Pos->second;
1043}
1044
1045void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1046 FunctionDecl *Pattern) {
1047 assert(FD && "Specialization is 0");
1048 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001049 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001050}
1051
John McCalle61f2ba2009-11-18 02:36:19 +00001052NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +00001053ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +00001054 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +00001055 = InstantiatedFromUsingDecl.find(UUD);
1056 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001057 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001058
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001059 return Pos->second;
1060}
1061
1062void
John McCallb96ec562009-12-04 22:46:56 +00001063ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1064 assert((isa<UsingDecl>(Pattern) ||
1065 isa<UnresolvedUsingValueDecl>(Pattern) ||
1066 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1067 "pattern decl is not a using decl");
1068 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1069 InstantiatedFromUsingDecl[Inst] = Pattern;
1070}
1071
1072UsingShadowDecl *
1073ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1074 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1075 = InstantiatedFromUsingShadowDecl.find(Inst);
1076 if (Pos == InstantiatedFromUsingShadowDecl.end())
1077 return 0;
1078
1079 return Pos->second;
1080}
1081
1082void
1083ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1084 UsingShadowDecl *Pattern) {
1085 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1086 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001087}
1088
Anders Carlsson5da84842009-09-01 04:26:58 +00001089FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1090 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1091 = InstantiatedFromUnnamedFieldDecl.find(Field);
1092 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1093 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001094
Anders Carlsson5da84842009-09-01 04:26:58 +00001095 return Pos->second;
1096}
1097
1098void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1099 FieldDecl *Tmpl) {
1100 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1101 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1102 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1103 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001104
Anders Carlsson5da84842009-09-01 04:26:58 +00001105 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1106}
1107
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +00001108bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
1109 const FieldDecl *LastFD) const {
1110 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001111 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +00001112}
1113
Fariborz Jahanianeb397412011-05-02 17:20:56 +00001114bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
1115 const FieldDecl *LastFD) const {
1116 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001117 FD->getBitWidthValue(*this) == 0 &&
1118 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanianeb397412011-05-02 17:20:56 +00001119}
1120
Fariborz Jahanian84335f72011-05-04 18:51:37 +00001121bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
1122 const FieldDecl *LastFD) const {
1123 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001124 FD->getBitWidthValue(*this) &&
1125 LastFD->getBitWidthValue(*this));
Fariborz Jahanian84335f72011-05-04 18:51:37 +00001126}
1127
Chad Rosierf01a7dd2011-08-04 23:34:15 +00001128bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +00001129 const FieldDecl *LastFD) const {
1130 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001131 LastFD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +00001132}
1133
Chad Rosierf01a7dd2011-08-04 23:34:15 +00001134bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +00001135 const FieldDecl *LastFD) const {
1136 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001137 FD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +00001138}
1139
Douglas Gregor832940b2010-03-02 23:58:15 +00001140ASTContext::overridden_cxx_method_iterator
1141ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1142 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001143 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001144 if (Pos == OverriddenMethods.end())
1145 return 0;
1146
1147 return Pos->second.begin();
1148}
1149
1150ASTContext::overridden_cxx_method_iterator
1151ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1152 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001153 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001154 if (Pos == OverriddenMethods.end())
1155 return 0;
1156
1157 return Pos->second.end();
1158}
1159
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001160unsigned
1161ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1162 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001163 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001164 if (Pos == OverriddenMethods.end())
1165 return 0;
1166
1167 return Pos->second.size();
1168}
1169
Douglas Gregor832940b2010-03-02 23:58:15 +00001170void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1171 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001172 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001173 OverriddenMethods[Method].push_back(Overridden);
1174}
1175
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001176void ASTContext::getOverriddenMethods(
1177 const NamedDecl *D,
1178 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001179 assert(D);
1180
1181 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001182 Overridden.append(overridden_methods_begin(CXXMethod),
1183 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001184 return;
1185 }
1186
1187 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1188 if (!Method)
1189 return;
1190
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001191 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1192 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001193 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001194}
1195
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001196void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1197 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1198 assert(!Import->isFromASTFile() && "Non-local import declaration");
1199 if (!FirstLocalImport) {
1200 FirstLocalImport = Import;
1201 LastLocalImport = Import;
1202 return;
1203 }
1204
1205 LastLocalImport->NextLocalImport = Import;
1206 LastLocalImport = Import;
1207}
1208
Chris Lattner53cfe802007-07-18 17:52:12 +00001209//===----------------------------------------------------------------------===//
1210// Type Sizing and Analysis
1211//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001212
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001213/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1214/// scalar floating point type.
1215const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001216 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001217 assert(BT && "Not a floating point type!");
1218 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001219 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001220 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001221 case BuiltinType::Float: return Target->getFloatFormat();
1222 case BuiltinType::Double: return Target->getDoubleFormat();
1223 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001224 }
1225}
1226
Ken Dyck160146e2010-01-27 17:10:57 +00001227/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +00001228/// specified decl. Note that bitfields do not have a valid alignment, so
1229/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001230/// If @p RefAsPointee, references are treated like their underlying type
1231/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad39c79802011-01-12 09:06:06 +00001232CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001233 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001234
John McCall94268702010-10-08 18:24:19 +00001235 bool UseAlignAttrOnly = false;
1236 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1237 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001238
John McCall94268702010-10-08 18:24:19 +00001239 // __attribute__((aligned)) can increase or decrease alignment
1240 // *except* on a struct or struct member, where it only increases
1241 // alignment unless 'packed' is also specified.
1242 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001243 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001244 // ignore that possibility; Sema should diagnose it.
1245 if (isa<FieldDecl>(D)) {
1246 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1247 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1248 } else {
1249 UseAlignAttrOnly = true;
1250 }
1251 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001252 else if (isa<FieldDecl>(D))
1253 UseAlignAttrOnly =
1254 D->hasAttr<PackedAttr>() ||
1255 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001256
John McCall4e819612011-01-20 07:57:12 +00001257 // If we're using the align attribute only, just ignore everything
1258 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001259 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001260 // do nothing
1261
John McCall94268702010-10-08 18:24:19 +00001262 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001263 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001264 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001265 if (RefAsPointee)
1266 T = RT->getPointeeType();
1267 else
1268 T = getPointerType(RT->getPointeeType());
1269 }
1270 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +00001271 // Adjust alignments of declarations with array type by the
1272 // large-array alignment on the target.
Douglas Gregore8bbc122011-09-02 00:18:52 +00001273 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall33ddac02011-01-19 10:06:00 +00001274 const ArrayType *arrayType;
1275 if (MinWidth && (arrayType = getAsArrayType(T))) {
1276 if (isa<VariableArrayType>(arrayType))
Douglas Gregore8bbc122011-09-02 00:18:52 +00001277 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall33ddac02011-01-19 10:06:00 +00001278 else if (isa<ConstantArrayType>(arrayType) &&
1279 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregore8bbc122011-09-02 00:18:52 +00001280 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedman19a546c2009-02-22 02:56:25 +00001281
John McCall33ddac02011-01-19 10:06:00 +00001282 // Walk through any array types while we're at it.
1283 T = getBaseElementType(arrayType);
1284 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001285 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedman19a546c2009-02-22 02:56:25 +00001286 }
John McCall4e819612011-01-20 07:57:12 +00001287
1288 // Fields can be subject to extra alignment constraints, like if
1289 // the field is packed, the struct is packed, or the struct has a
1290 // a max-field-alignment constraint (#pragma pack). So calculate
1291 // the actual alignment of the field within the struct, and then
1292 // (as we're expected to) constrain that by the alignment of the type.
1293 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
1294 // So calculate the alignment of the field.
1295 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
1296
1297 // Start with the record's overall alignment.
Ken Dyck7ad11e72011-02-15 02:32:40 +00001298 unsigned fieldAlign = toBits(layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001299
1300 // Use the GCD of that and the offset within the record.
1301 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
1302 if (offset > 0) {
1303 // Alignment is always a power of 2, so the GCD will be a power of 2,
1304 // which means we get to do this crazy thing instead of Euclid's.
1305 uint64_t lowBitOfOffset = offset & (~offset + 1);
1306 if (lowBitOfOffset < fieldAlign)
1307 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
1308 }
1309
1310 Align = std::min(Align, fieldAlign);
Charles Davis3fc51072010-02-23 04:52:00 +00001311 }
Chris Lattner68061312009-01-24 21:53:27 +00001312 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001313
Ken Dyckcc56c542011-01-15 18:38:59 +00001314 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001315}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001316
John McCallf1249922012-08-21 04:10:00 +00001317// getTypeInfoDataSizeInChars - Return the size of a type, in
1318// chars. If the type is a record, its data size is returned. This is
1319// the size of the memcpy that's performed when assigning this type
1320// using a trivial copy/move assignment operator.
1321std::pair<CharUnits, CharUnits>
1322ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1323 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1324
1325 // In C++, objects can sometimes be allocated into the tail padding
1326 // of a base-class subobject. We decide whether that's possible
1327 // during class layout, so here we can just trust the layout results.
1328 if (getLangOpts().CPlusPlus) {
1329 if (const RecordType *RT = T->getAs<RecordType>()) {
1330 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1331 sizeAndAlign.first = layout.getDataSize();
1332 }
1333 }
1334
1335 return sizeAndAlign;
1336}
1337
John McCall87fe5d52010-05-20 01:18:31 +00001338std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001339ASTContext::getTypeInfoInChars(const Type *T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001340 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +00001341 return std::make_pair(toCharUnitsFromBits(Info.first),
1342 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +00001343}
1344
1345std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001346ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001347 return getTypeInfoInChars(T.getTypePtr());
1348}
1349
Daniel Dunbarc6475872012-03-09 04:12:54 +00001350std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1351 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1352 if (it != MemoizedTypeInfo.end())
1353 return it->second;
1354
1355 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1356 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1357 return Info;
1358}
1359
1360/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1361/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001362///
1363/// FIXME: Pointers into different addr spaces could have different sizes and
1364/// alignment requirements: getPointerInfo should take an AddrSpace, this
1365/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +00001366std::pair<uint64_t, unsigned>
Daniel Dunbarc6475872012-03-09 04:12:54 +00001367ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +00001368 uint64_t Width=0;
1369 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001370 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001371#define TYPE(Class, Base)
1372#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001373#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001374#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1375#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001376 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001377
Chris Lattner355332d2007-07-13 22:27:08 +00001378 case Type::FunctionNoProto:
1379 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001380 // GCC extension: alignof(function) = 32 bits
1381 Width = 0;
1382 Align = 32;
1383 break;
1384
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001385 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001386 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001387 Width = 0;
1388 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1389 break;
1390
Steve Naroff5c131802007-08-30 01:06:46 +00001391 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001392 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001393
Chris Lattner37e05872008-03-05 18:54:05 +00001394 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001395 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarc6475872012-03-09 04:12:54 +00001396 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1397 "Overflow in array type bit size evaluation");
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001398 Width = EltInfo.first*Size;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001399 Align = EltInfo.second;
Argyrios Kyrtzidisae40e4e2011-04-26 21:05:39 +00001400 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001401 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001402 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001403 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001404 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001405 const VectorType *VT = cast<VectorType>(T);
1406 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1407 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001408 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001409 // If the alignment is not a power of 2, round up to the next power of 2.
1410 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001411 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001412 Align = llvm::NextPowerOf2(Align);
1413 Width = llvm::RoundUpToAlignment(Width, Align);
1414 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001415 // Adjust the alignment based on the target max.
1416 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1417 if (TargetVectorAlign && TargetVectorAlign < Align)
1418 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001419 break;
1420 }
Chris Lattner647fb222007-07-18 18:26:58 +00001421
Chris Lattner7570e9c2008-03-08 08:52:55 +00001422 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001423 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001424 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001425 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001426 // GCC extension: alignof(void) = 8 bits.
1427 Width = 0;
1428 Align = 8;
1429 break;
1430
Chris Lattner6a4f7452007-12-19 19:23:28 +00001431 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001432 Width = Target->getBoolWidth();
1433 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001434 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001435 case BuiltinType::Char_S:
1436 case BuiltinType::Char_U:
1437 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001438 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001439 Width = Target->getCharWidth();
1440 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001441 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001442 case BuiltinType::WChar_S:
1443 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001444 Width = Target->getWCharWidth();
1445 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001446 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001447 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001448 Width = Target->getChar16Width();
1449 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001450 break;
1451 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001452 Width = Target->getChar32Width();
1453 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001454 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001455 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001456 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001457 Width = Target->getShortWidth();
1458 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001459 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001460 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001461 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001462 Width = Target->getIntWidth();
1463 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001464 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001465 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001466 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001467 Width = Target->getLongWidth();
1468 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001469 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001470 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001471 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001472 Width = Target->getLongLongWidth();
1473 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001474 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001475 case BuiltinType::Int128:
1476 case BuiltinType::UInt128:
1477 Width = 128;
1478 Align = 128; // int128_t is 128-bit aligned on all targets.
1479 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001480 case BuiltinType::Half:
1481 Width = Target->getHalfWidth();
1482 Align = Target->getHalfAlign();
1483 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001484 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001485 Width = Target->getFloatWidth();
1486 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001487 break;
1488 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001489 Width = Target->getDoubleWidth();
1490 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001491 break;
1492 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001493 Width = Target->getLongDoubleWidth();
1494 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001495 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001496 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001497 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1498 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001499 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001500 case BuiltinType::ObjCId:
1501 case BuiltinType::ObjCClass:
1502 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001503 Width = Target->getPointerWidth(0);
1504 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001505 break;
Guy Benyei61054192013-02-07 10:55:47 +00001506 case BuiltinType::OCLSampler:
1507 // Samplers are modeled as integers.
1508 Width = Target->getIntWidth();
1509 Align = Target->getIntAlign();
1510 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001511 case BuiltinType::OCLEvent:
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001512 case BuiltinType::OCLImage1d:
1513 case BuiltinType::OCLImage1dArray:
1514 case BuiltinType::OCLImage1dBuffer:
1515 case BuiltinType::OCLImage2d:
1516 case BuiltinType::OCLImage2dArray:
1517 case BuiltinType::OCLImage3d:
1518 // Currently these types are pointers to opaque types.
1519 Width = Target->getPointerWidth(0);
1520 Align = Target->getPointerAlign(0);
1521 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001522 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001523 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001524 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001525 Width = Target->getPointerWidth(0);
1526 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001527 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001528 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001529 unsigned AS = getTargetAddressSpace(
1530 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001531 Width = Target->getPointerWidth(AS);
1532 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001533 break;
1534 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001535 case Type::LValueReference:
1536 case Type::RValueReference: {
1537 // alignof and sizeof should never enter this code path here, so we go
1538 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001539 unsigned AS = getTargetAddressSpace(
1540 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001541 Width = Target->getPointerWidth(AS);
1542 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001543 break;
1544 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001545 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001546 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001547 Width = Target->getPointerWidth(AS);
1548 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001549 break;
1550 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001551 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001552 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Reid Kleckner3a52abf2013-03-28 20:02:56 +00001553 llvm::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001554 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001555 }
Chris Lattner647fb222007-07-18 18:26:58 +00001556 case Type::Complex: {
1557 // Complex types have the same alignment as their elements, but twice the
1558 // size.
Mike Stump11289f42009-09-09 15:08:12 +00001559 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +00001560 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +00001561 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +00001562 Align = EltInfo.second;
1563 break;
1564 }
John McCall8b07ec22010-05-15 11:32:37 +00001565 case Type::ObjCObject:
1566 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001567 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001568 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001569 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001570 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001571 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001572 break;
1573 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001574 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001575 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001576 const TagType *TT = cast<TagType>(T);
1577
1578 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001579 Width = 8;
1580 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001581 break;
1582 }
Mike Stump11289f42009-09-09 15:08:12 +00001583
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001584 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +00001585 return getTypeInfo(ET->getDecl()->getIntegerType());
1586
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001587 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +00001588 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001589 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001590 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +00001591 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001592 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001593
Chris Lattner63d2b362009-10-22 05:17:15 +00001594 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001595 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1596 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001597
Richard Smith30482bc2011-02-20 03:19:35 +00001598 case Type::Auto: {
1599 const AutoType *A = cast<AutoType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00001600 assert(!A->getDeducedType().isNull() &&
1601 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001602 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001603 }
1604
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001605 case Type::Paren:
1606 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1607
Douglas Gregoref462e62009-04-30 17:32:17 +00001608 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001609 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +00001610 std::pair<uint64_t, unsigned> Info
1611 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001612 // If the typedef has an aligned attribute on it, it overrides any computed
1613 // alignment we have. This violates the GCC documentation (which says that
1614 // attribute(aligned) can only round up) but matches its implementation.
1615 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1616 Align = AttrAlign;
1617 else
1618 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +00001619 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +00001620 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001621 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001622
1623 case Type::TypeOfExpr:
1624 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1625 .getTypePtr());
1626
1627 case Type::TypeOf:
1628 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1629
Anders Carlsson81df7b82009-06-24 19:06:50 +00001630 case Type::Decltype:
1631 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1632 .getTypePtr());
1633
Alexis Hunte852b102011-05-24 22:41:36 +00001634 case Type::UnaryTransform:
1635 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1636
Abramo Bagnara6150c882010-05-11 21:36:43 +00001637 case Type::Elaborated:
1638 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001639
John McCall81904512011-01-06 01:58:22 +00001640 case Type::Attributed:
1641 return getTypeInfo(
1642 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1643
Richard Smith3f1b5d02011-05-05 21:57:07 +00001644 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00001645 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +00001646 "Cannot request the size of a dependent type");
Richard Smith3f1b5d02011-05-05 21:57:07 +00001647 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1648 // A type alias template specialization may refer to a typedef with the
1649 // aligned attribute on it.
1650 if (TST->isTypeAlias())
1651 return getTypeInfo(TST->getAliasedType().getTypePtr());
1652 else
1653 return getTypeInfo(getCanonicalType(T));
1654 }
1655
Eli Friedman0dfb8892011-10-06 23:00:33 +00001656 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00001657 // Start with the base type information.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001658 std::pair<uint64_t, unsigned> Info
1659 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1660 Width = Info.first;
1661 Align = Info.second;
John McCalla8ec7eb2013-03-07 21:37:17 +00001662
1663 // If the size of the type doesn't exceed the platform's max
1664 // atomic promotion width, make the size and alignment more
1665 // favorable to atomic operations:
1666 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1667 // Round the size up to a power of 2.
1668 if (!llvm::isPowerOf2_64(Width))
1669 Width = llvm::NextPowerOf2(Width);
1670
1671 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001672 Align = static_cast<unsigned>(Width);
1673 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001674 }
1675
Douglas Gregoref462e62009-04-30 17:32:17 +00001676 }
Mike Stump11289f42009-09-09 15:08:12 +00001677
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001678 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +00001679 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001680}
1681
Ken Dyckcc56c542011-01-15 18:38:59 +00001682/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1683CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1684 return CharUnits::fromQuantity(BitSize / getCharWidth());
1685}
1686
Ken Dyckb0fcc592011-02-11 01:54:29 +00001687/// toBits - Convert a size in characters to a size in characters.
1688int64_t ASTContext::toBits(CharUnits CharSize) const {
1689 return CharSize.getQuantity() * getCharWidth();
1690}
1691
Ken Dyck8c89d592009-12-22 14:23:30 +00001692/// getTypeSizeInChars - Return the size of the specified type, in characters.
1693/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001694CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001695 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001696}
Jay Foad39c79802011-01-12 09:06:06 +00001697CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001698 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001699}
1700
Ken Dycka6046ab2010-01-26 17:25:18 +00001701/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001702/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001703CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001704 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001705}
Jay Foad39c79802011-01-12 09:06:06 +00001706CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001707 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001708}
1709
Chris Lattnera3402cd2009-01-27 18:08:34 +00001710/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1711/// type for the current target in bits. This can be different than the ABI
1712/// alignment in cases where it is beneficial for performance to overalign
1713/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001714unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +00001715 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +00001716
1717 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +00001718 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001719 T = CT->getElementType().getTypePtr();
1720 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001721 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1722 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman7ab09572009-05-25 21:27:19 +00001723 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1724
Chris Lattnera3402cd2009-01-27 18:08:34 +00001725 return ABIAlign;
1726}
1727
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001728/// DeepCollectObjCIvars -
1729/// This routine first collects all declared, but not synthesized, ivars in
1730/// super class and then collects all ivars, including those synthesized for
1731/// current class. This routine is used for implementation of current class
1732/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001733///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001734void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1735 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001736 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001737 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1738 DeepCollectObjCIvars(SuperClass, false, Ivars);
1739 if (!leafClass) {
1740 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1741 E = OI->ivar_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001742 Ivars.push_back(*I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001743 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001744 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001745 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001746 Iv= Iv->getNextIvar())
1747 Ivars.push_back(Iv);
1748 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001749}
1750
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001751/// CollectInheritedProtocols - Collect all protocols in current class and
1752/// those inherited by it.
1753void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001754 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001755 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001756 // We can use protocol_iterator here instead of
1757 // all_referenced_protocol_iterator since we are walking all categories.
1758 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1759 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001760 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001761 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001762 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001763 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001764 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001765 CollectInheritedProtocols(*P, Protocols);
1766 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001767 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001768
1769 // Categories of this Interface.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001770 for (ObjCInterfaceDecl::visible_categories_iterator
1771 Cat = OI->visible_categories_begin(),
1772 CatEnd = OI->visible_categories_end();
1773 Cat != CatEnd; ++Cat) {
1774 CollectInheritedProtocols(*Cat, Protocols);
1775 }
1776
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001777 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1778 while (SD) {
1779 CollectInheritedProtocols(SD, Protocols);
1780 SD = SD->getSuperClass();
1781 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001782 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001783 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001784 PE = OC->protocol_end(); P != PE; ++P) {
1785 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001786 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001787 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1788 PE = Proto->protocol_end(); P != PE; ++P)
1789 CollectInheritedProtocols(*P, Protocols);
1790 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001791 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001792 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1793 PE = OP->protocol_end(); P != PE; ++P) {
1794 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001795 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001796 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1797 PE = Proto->protocol_end(); P != PE; ++P)
1798 CollectInheritedProtocols(*P, Protocols);
1799 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001800 }
1801}
1802
Jay Foad39c79802011-01-12 09:06:06 +00001803unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001804 unsigned count = 0;
1805 // Count ivars declared in class extension.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001806 for (ObjCInterfaceDecl::known_extensions_iterator
1807 Ext = OI->known_extensions_begin(),
1808 ExtEnd = OI->known_extensions_end();
1809 Ext != ExtEnd; ++Ext) {
1810 count += Ext->ivar_size();
1811 }
1812
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001813 // Count ivar defined in this class's implementation. This
1814 // includes synthesized ivars.
1815 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001816 count += ImplDecl->ivar_size();
1817
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001818 return count;
1819}
1820
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001821bool ASTContext::isSentinelNullExpr(const Expr *E) {
1822 if (!E)
1823 return false;
1824
1825 // nullptr_t is always treated as null.
1826 if (E->getType()->isNullPtrType()) return true;
1827
1828 if (E->getType()->isAnyPointerType() &&
1829 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1830 Expr::NPC_ValueDependentIsNull))
1831 return true;
1832
1833 // Unfortunately, __null has type 'int'.
1834 if (isa<GNUNullExpr>(E)) return true;
1835
1836 return false;
1837}
1838
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001839/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1840ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1841 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1842 I = ObjCImpls.find(D);
1843 if (I != ObjCImpls.end())
1844 return cast<ObjCImplementationDecl>(I->second);
1845 return 0;
1846}
1847/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1848ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1849 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1850 I = ObjCImpls.find(D);
1851 if (I != ObjCImpls.end())
1852 return cast<ObjCCategoryImplDecl>(I->second);
1853 return 0;
1854}
1855
1856/// \brief Set the implementation of ObjCInterfaceDecl.
1857void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1858 ObjCImplementationDecl *ImplD) {
1859 assert(IFaceD && ImplD && "Passed null params");
1860 ObjCImpls[IFaceD] = ImplD;
1861}
1862/// \brief Set the implementation of ObjCCategoryDecl.
1863void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1864 ObjCCategoryImplDecl *ImplD) {
1865 assert(CatD && ImplD && "Passed null params");
1866 ObjCImpls[CatD] = ImplD;
1867}
1868
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001869const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
1870 const NamedDecl *ND) const {
1871 if (const ObjCInterfaceDecl *ID =
1872 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001873 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001874 if (const ObjCCategoryDecl *CD =
1875 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001876 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001877 if (const ObjCImplDecl *IMD =
1878 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001879 return IMD->getClassInterface();
1880
1881 return 0;
1882}
1883
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001884/// \brief Get the copy initialization expression of VarDecl,or NULL if
1885/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001886Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001887 assert(VD && "Passed null params");
1888 assert(VD->hasAttr<BlocksAttr>() &&
1889 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001890 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001891 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001892 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1893}
1894
1895/// \brief Set the copy inialization expression of a block var decl.
1896void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1897 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001898 assert(VD->hasAttr<BlocksAttr>() &&
1899 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001900 BlockVarCopyInits[VD] = Init;
1901}
1902
John McCallbcd03502009-12-07 02:54:59 +00001903TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001904 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001905 if (!DataSize)
1906 DataSize = TypeLoc::getFullDataSizeForType(T);
1907 else
1908 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001909 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001910
John McCallbcd03502009-12-07 02:54:59 +00001911 TypeSourceInfo *TInfo =
1912 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1913 new (TInfo) TypeSourceInfo(T);
1914 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001915}
1916
John McCallbcd03502009-12-07 02:54:59 +00001917TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001918 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001919 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001920 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001921 return DI;
1922}
1923
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001924const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001925ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001926 return getObjCLayout(D, 0);
1927}
1928
1929const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001930ASTContext::getASTObjCImplementationLayout(
1931 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001932 return getObjCLayout(D->getClassInterface(), D);
1933}
1934
Chris Lattner983a8bb2007-07-13 22:13:22 +00001935//===----------------------------------------------------------------------===//
1936// Type creation/memoization methods
1937//===----------------------------------------------------------------------===//
1938
Jay Foad39c79802011-01-12 09:06:06 +00001939QualType
John McCall33ddac02011-01-19 10:06:00 +00001940ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1941 unsigned fastQuals = quals.getFastQualifiers();
1942 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001943
1944 // Check if we've already instantiated this type.
1945 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001946 ExtQuals::Profile(ID, baseType, quals);
1947 void *insertPos = 0;
1948 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1949 assert(eq->getQualifiers() == quals);
1950 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001951 }
1952
John McCall33ddac02011-01-19 10:06:00 +00001953 // If the base type is not canonical, make the appropriate canonical type.
1954 QualType canon;
1955 if (!baseType->isCanonicalUnqualified()) {
1956 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00001957 canonSplit.Quals.addConsistentQualifiers(quals);
1958 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00001959
1960 // Re-find the insert position.
1961 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1962 }
1963
1964 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1965 ExtQualNodes.InsertNode(eq, insertPos);
1966 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001967}
1968
Jay Foad39c79802011-01-12 09:06:06 +00001969QualType
1970ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001971 QualType CanT = getCanonicalType(T);
1972 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001973 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001974
John McCall8ccfcb52009-09-24 19:53:00 +00001975 // If we are composing extended qualifiers together, merge together
1976 // into one ExtQuals node.
1977 QualifierCollector Quals;
1978 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001979
John McCall8ccfcb52009-09-24 19:53:00 +00001980 // If this type already has an address space specified, it cannot get
1981 // another one.
1982 assert(!Quals.hasAddressSpace() &&
1983 "Type cannot be in multiple addr spaces!");
1984 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001985
John McCall8ccfcb52009-09-24 19:53:00 +00001986 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001987}
1988
Chris Lattnerd60183d2009-02-18 22:53:11 +00001989QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001990 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001991 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001992 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001993 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001994
John McCall53fa7142010-12-24 02:08:15 +00001995 if (const PointerType *ptr = T->getAs<PointerType>()) {
1996 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001997 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001998 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1999 return getPointerType(ResultType);
2000 }
2001 }
Mike Stump11289f42009-09-09 15:08:12 +00002002
John McCall8ccfcb52009-09-24 19:53:00 +00002003 // If we are composing extended qualifiers together, merge together
2004 // into one ExtQuals node.
2005 QualifierCollector Quals;
2006 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002007
John McCall8ccfcb52009-09-24 19:53:00 +00002008 // If this type already has an ObjCGC specified, it cannot get
2009 // another one.
2010 assert(!Quals.hasObjCGCAttr() &&
2011 "Type cannot have multiple ObjCGCs!");
2012 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002013
John McCall8ccfcb52009-09-24 19:53:00 +00002014 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002015}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002016
John McCall4f5019e2010-12-19 02:44:49 +00002017const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2018 FunctionType::ExtInfo Info) {
2019 if (T->getExtInfo() == Info)
2020 return T;
2021
2022 QualType Result;
2023 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
2024 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
2025 } else {
2026 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2027 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2028 EPI.ExtInfo = Info;
Jordan Rose5c382722013-03-08 21:51:21 +00002029 Result = getFunctionType(FPT->getResultType(),
2030 ArrayRef<QualType>(FPT->arg_type_begin(),
2031 FPT->getNumArgs()),
2032 EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002033 }
2034
2035 return cast<FunctionType>(Result.getTypePtr());
2036}
2037
Richard Smith2a7d4812013-05-04 07:00:32 +00002038void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2039 QualType ResultType) {
2040 // FIXME: Need to inform serialization code about this!
2041 for (FD = FD->getMostRecentDecl(); FD; FD = FD->getPreviousDecl()) {
2042 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2043 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2044 FD->setType(getFunctionType(ResultType, FPT->getArgTypes(), EPI));
2045 }
2046}
2047
Chris Lattnerc6395932007-06-22 20:56:16 +00002048/// getComplexType - Return the uniqued reference to the type for a complex
2049/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002050QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002051 // Unique pointers, to guarantee there is only one pointer of a particular
2052 // structure.
2053 llvm::FoldingSetNodeID ID;
2054 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002055
Chris Lattnerc6395932007-06-22 20:56:16 +00002056 void *InsertPos = 0;
2057 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2058 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002059
Chris Lattnerc6395932007-06-22 20:56:16 +00002060 // If the pointee type isn't canonical, this won't be a canonical type either,
2061 // so fill in the canonical type field.
2062 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002063 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002064 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002065
Chris Lattnerc6395932007-06-22 20:56:16 +00002066 // Get the new insert position for the node we care about.
2067 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002068 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002069 }
John McCall90d1c2d2009-09-24 23:30:46 +00002070 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002071 Types.push_back(New);
2072 ComplexTypes.InsertNode(New, InsertPos);
2073 return QualType(New, 0);
2074}
2075
Chris Lattner970e54e2006-11-12 00:37:36 +00002076/// getPointerType - Return the uniqued reference to the type for a pointer to
2077/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002078QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002079 // Unique pointers, to guarantee there is only one pointer of a particular
2080 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002081 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002082 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002083
Chris Lattner67521df2007-01-27 01:29:36 +00002084 void *InsertPos = 0;
2085 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002086 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002087
Chris Lattner7ccecb92006-11-12 08:50:50 +00002088 // If the pointee type isn't canonical, this won't be a canonical type either,
2089 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002090 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002091 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002092 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002093
Bob Wilsonc8541f22013-03-15 17:12:43 +00002094 // Get the new insert position for the node we care about.
2095 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2096 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2097 }
John McCall90d1c2d2009-09-24 23:30:46 +00002098 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002099 Types.push_back(New);
2100 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002101 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002102}
2103
Mike Stump11289f42009-09-09 15:08:12 +00002104/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002105/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002106QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002107 assert(T->isFunctionType() && "block of function types only");
2108 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002109 // structure.
2110 llvm::FoldingSetNodeID ID;
2111 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002112
Steve Naroffec33ed92008-08-27 16:04:49 +00002113 void *InsertPos = 0;
2114 if (BlockPointerType *PT =
2115 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2116 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002117
2118 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002119 // type either so fill in the canonical type field.
2120 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002121 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002122 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002123
Steve Naroffec33ed92008-08-27 16:04:49 +00002124 // Get the new insert position for the node we care about.
2125 BlockPointerType *NewIP =
2126 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002127 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002128 }
John McCall90d1c2d2009-09-24 23:30:46 +00002129 BlockPointerType *New
2130 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002131 Types.push_back(New);
2132 BlockPointerTypes.InsertNode(New, InsertPos);
2133 return QualType(New, 0);
2134}
2135
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002136/// getLValueReferenceType - Return the uniqued reference to the type for an
2137/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002138QualType
2139ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002140 assert(getCanonicalType(T) != OverloadTy &&
2141 "Unresolved overloaded function type");
2142
Bill Wendling3708c182007-05-27 10:15:43 +00002143 // Unique pointers, to guarantee there is only one pointer of a particular
2144 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002145 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002146 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002147
2148 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002149 if (LValueReferenceType *RT =
2150 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002151 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002152
John McCallfc93cf92009-10-22 22:37:11 +00002153 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2154
Bill Wendling3708c182007-05-27 10:15:43 +00002155 // If the referencee type isn't canonical, this won't be a canonical type
2156 // either, so fill in the canonical type field.
2157 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002158 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2159 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2160 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002161
Bill Wendling3708c182007-05-27 10:15:43 +00002162 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002163 LValueReferenceType *NewIP =
2164 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002165 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002166 }
2167
John McCall90d1c2d2009-09-24 23:30:46 +00002168 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002169 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2170 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002171 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002172 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002173
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002174 return QualType(New, 0);
2175}
2176
2177/// getRValueReferenceType - Return the uniqued reference to the type for an
2178/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002179QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002180 // Unique pointers, to guarantee there is only one pointer of a particular
2181 // structure.
2182 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002183 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002184
2185 void *InsertPos = 0;
2186 if (RValueReferenceType *RT =
2187 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2188 return QualType(RT, 0);
2189
John McCallfc93cf92009-10-22 22:37:11 +00002190 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2191
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002192 // If the referencee type isn't canonical, this won't be a canonical type
2193 // either, so fill in the canonical type field.
2194 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002195 if (InnerRef || !T.isCanonical()) {
2196 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2197 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002198
2199 // Get the new insert position for the node we care about.
2200 RValueReferenceType *NewIP =
2201 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002202 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002203 }
2204
John McCall90d1c2d2009-09-24 23:30:46 +00002205 RValueReferenceType *New
2206 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002207 Types.push_back(New);
2208 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002209 return QualType(New, 0);
2210}
2211
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002212/// getMemberPointerType - Return the uniqued reference to the type for a
2213/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002214QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002215 // Unique pointers, to guarantee there is only one pointer of a particular
2216 // structure.
2217 llvm::FoldingSetNodeID ID;
2218 MemberPointerType::Profile(ID, T, Cls);
2219
2220 void *InsertPos = 0;
2221 if (MemberPointerType *PT =
2222 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2223 return QualType(PT, 0);
2224
2225 // If the pointee or class type isn't canonical, this won't be a canonical
2226 // type either, so fill in the canonical type field.
2227 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002228 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002229 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2230
2231 // Get the new insert position for the node we care about.
2232 MemberPointerType *NewIP =
2233 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002234 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002235 }
John McCall90d1c2d2009-09-24 23:30:46 +00002236 MemberPointerType *New
2237 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002238 Types.push_back(New);
2239 MemberPointerTypes.InsertNode(New, InsertPos);
2240 return QualType(New, 0);
2241}
2242
Mike Stump11289f42009-09-09 15:08:12 +00002243/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002244/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002245QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002246 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002247 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002248 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002249 assert((EltTy->isDependentType() ||
2250 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002251 "Constant array of VLAs is illegal!");
2252
Chris Lattnere2df3f92009-05-13 04:12:56 +00002253 // Convert the array size into a canonical width matching the pointer size for
2254 // the target.
2255 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002256 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002257 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002258
Chris Lattner23b7eb62007-06-15 23:05:46 +00002259 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002260 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002261
Chris Lattner36f8e652007-01-27 08:31:04 +00002262 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002263 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002264 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002265 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002266
John McCall33ddac02011-01-19 10:06:00 +00002267 // If the element type isn't canonical or has qualifiers, this won't
2268 // be a canonical type either, so fill in the canonical type field.
2269 QualType Canon;
2270 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2271 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002272 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002273 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002274 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002275
Chris Lattner36f8e652007-01-27 08:31:04 +00002276 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002277 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002278 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002279 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002280 }
Mike Stump11289f42009-09-09 15:08:12 +00002281
John McCall90d1c2d2009-09-24 23:30:46 +00002282 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002283 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002284 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002285 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002286 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002287}
2288
John McCall06549462011-01-18 08:40:38 +00002289/// getVariableArrayDecayedType - Turns the given type, which may be
2290/// variably-modified, into the corresponding type with all the known
2291/// sizes replaced with [*].
2292QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2293 // Vastly most common case.
2294 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002295
John McCall06549462011-01-18 08:40:38 +00002296 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002297
John McCall06549462011-01-18 08:40:38 +00002298 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002299 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002300 switch (ty->getTypeClass()) {
2301#define TYPE(Class, Base)
2302#define ABSTRACT_TYPE(Class, Base)
2303#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2304#include "clang/AST/TypeNodes.def"
2305 llvm_unreachable("didn't desugar past all non-canonical types?");
2306
2307 // These types should never be variably-modified.
2308 case Type::Builtin:
2309 case Type::Complex:
2310 case Type::Vector:
2311 case Type::ExtVector:
2312 case Type::DependentSizedExtVector:
2313 case Type::ObjCObject:
2314 case Type::ObjCInterface:
2315 case Type::ObjCObjectPointer:
2316 case Type::Record:
2317 case Type::Enum:
2318 case Type::UnresolvedUsing:
2319 case Type::TypeOfExpr:
2320 case Type::TypeOf:
2321 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002322 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002323 case Type::DependentName:
2324 case Type::InjectedClassName:
2325 case Type::TemplateSpecialization:
2326 case Type::DependentTemplateSpecialization:
2327 case Type::TemplateTypeParm:
2328 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002329 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002330 case Type::PackExpansion:
2331 llvm_unreachable("type should never be variably-modified");
2332
2333 // These types can be variably-modified but should never need to
2334 // further decay.
2335 case Type::FunctionNoProto:
2336 case Type::FunctionProto:
2337 case Type::BlockPointer:
2338 case Type::MemberPointer:
2339 return type;
2340
2341 // These types can be variably-modified. All these modifications
2342 // preserve structure except as noted by comments.
2343 // TODO: if we ever care about optimizing VLAs, there are no-op
2344 // optimizations available here.
2345 case Type::Pointer:
2346 result = getPointerType(getVariableArrayDecayedType(
2347 cast<PointerType>(ty)->getPointeeType()));
2348 break;
2349
2350 case Type::LValueReference: {
2351 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2352 result = getLValueReferenceType(
2353 getVariableArrayDecayedType(lv->getPointeeType()),
2354 lv->isSpelledAsLValue());
2355 break;
2356 }
2357
2358 case Type::RValueReference: {
2359 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2360 result = getRValueReferenceType(
2361 getVariableArrayDecayedType(lv->getPointeeType()));
2362 break;
2363 }
2364
Eli Friedman0dfb8892011-10-06 23:00:33 +00002365 case Type::Atomic: {
2366 const AtomicType *at = cast<AtomicType>(ty);
2367 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2368 break;
2369 }
2370
John McCall06549462011-01-18 08:40:38 +00002371 case Type::ConstantArray: {
2372 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2373 result = getConstantArrayType(
2374 getVariableArrayDecayedType(cat->getElementType()),
2375 cat->getSize(),
2376 cat->getSizeModifier(),
2377 cat->getIndexTypeCVRQualifiers());
2378 break;
2379 }
2380
2381 case Type::DependentSizedArray: {
2382 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2383 result = getDependentSizedArrayType(
2384 getVariableArrayDecayedType(dat->getElementType()),
2385 dat->getSizeExpr(),
2386 dat->getSizeModifier(),
2387 dat->getIndexTypeCVRQualifiers(),
2388 dat->getBracketsRange());
2389 break;
2390 }
2391
2392 // Turn incomplete types into [*] types.
2393 case Type::IncompleteArray: {
2394 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2395 result = getVariableArrayType(
2396 getVariableArrayDecayedType(iat->getElementType()),
2397 /*size*/ 0,
2398 ArrayType::Normal,
2399 iat->getIndexTypeCVRQualifiers(),
2400 SourceRange());
2401 break;
2402 }
2403
2404 // Turn VLA types into [*] types.
2405 case Type::VariableArray: {
2406 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2407 result = getVariableArrayType(
2408 getVariableArrayDecayedType(vat->getElementType()),
2409 /*size*/ 0,
2410 ArrayType::Star,
2411 vat->getIndexTypeCVRQualifiers(),
2412 vat->getBracketsRange());
2413 break;
2414 }
2415 }
2416
2417 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002418 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002419}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002420
Steve Naroffcadebd02007-08-30 18:14:25 +00002421/// getVariableArrayType - Returns a non-unique reference to the type for a
2422/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002423QualType ASTContext::getVariableArrayType(QualType EltTy,
2424 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002425 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002426 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002427 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002428 // Since we don't unique expressions, it isn't possible to unique VLA's
2429 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002430 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002431
John McCall33ddac02011-01-19 10:06:00 +00002432 // Be sure to pull qualifiers off the element type.
2433 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2434 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002435 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002436 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002437 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002438 }
2439
John McCall90d1c2d2009-09-24 23:30:46 +00002440 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002441 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002442
2443 VariableArrayTypes.push_back(New);
2444 Types.push_back(New);
2445 return QualType(New, 0);
2446}
2447
Douglas Gregor4619e432008-12-05 23:32:09 +00002448/// getDependentSizedArrayType - Returns a non-unique reference to
2449/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002450/// type.
John McCall33ddac02011-01-19 10:06:00 +00002451QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2452 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002453 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002454 unsigned elementTypeQuals,
2455 SourceRange brackets) const {
2456 assert((!numElements || numElements->isTypeDependent() ||
2457 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002458 "Size must be type- or value-dependent!");
2459
John McCall33ddac02011-01-19 10:06:00 +00002460 // Dependently-sized array types that do not have a specified number
2461 // of elements will have their sizes deduced from a dependent
2462 // initializer. We do no canonicalization here at all, which is okay
2463 // because they can't be used in most locations.
2464 if (!numElements) {
2465 DependentSizedArrayType *newType
2466 = new (*this, TypeAlignment)
2467 DependentSizedArrayType(*this, elementType, QualType(),
2468 numElements, ASM, elementTypeQuals,
2469 brackets);
2470 Types.push_back(newType);
2471 return QualType(newType, 0);
2472 }
2473
2474 // Otherwise, we actually build a new type every time, but we
2475 // also build a canonical type.
2476
2477 SplitQualType canonElementType = getCanonicalType(elementType).split();
2478
2479 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002480 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002481 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002482 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002483 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002484
John McCall33ddac02011-01-19 10:06:00 +00002485 // Look for an existing type with these properties.
2486 DependentSizedArrayType *canonTy =
2487 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002488
John McCall33ddac02011-01-19 10:06:00 +00002489 // If we don't have one, build one.
2490 if (!canonTy) {
2491 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002492 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002493 QualType(), numElements, ASM, elementTypeQuals,
2494 brackets);
2495 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2496 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002497 }
2498
John McCall33ddac02011-01-19 10:06:00 +00002499 // Apply qualifiers from the element type to the array.
2500 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002501 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002502
John McCall33ddac02011-01-19 10:06:00 +00002503 // If we didn't need extra canonicalization for the element type,
2504 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00002505 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00002506 return canon;
2507
2508 // Otherwise, we need to build a type which follows the spelling
2509 // of the element type.
2510 DependentSizedArrayType *sugaredType
2511 = new (*this, TypeAlignment)
2512 DependentSizedArrayType(*this, elementType, canon, numElements,
2513 ASM, elementTypeQuals, brackets);
2514 Types.push_back(sugaredType);
2515 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002516}
2517
John McCall33ddac02011-01-19 10:06:00 +00002518QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002519 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002520 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002521 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002522 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002523
John McCall33ddac02011-01-19 10:06:00 +00002524 void *insertPos = 0;
2525 if (IncompleteArrayType *iat =
2526 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2527 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002528
2529 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002530 // either, so fill in the canonical type field. We also have to pull
2531 // qualifiers off the element type.
2532 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002533
John McCall33ddac02011-01-19 10:06:00 +00002534 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2535 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002536 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002537 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002538 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002539
2540 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002541 IncompleteArrayType *existing =
2542 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2543 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002544 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002545
John McCall33ddac02011-01-19 10:06:00 +00002546 IncompleteArrayType *newType = new (*this, TypeAlignment)
2547 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002548
John McCall33ddac02011-01-19 10:06:00 +00002549 IncompleteArrayTypes.InsertNode(newType, insertPos);
2550 Types.push_back(newType);
2551 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002552}
2553
Steve Naroff91fcddb2007-07-18 18:00:27 +00002554/// getVectorType - Return the unique reference to a vector type of
2555/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002556QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002557 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002558 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002559
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002560 // Check if we've already instantiated a vector of this type.
2561 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002562 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002563
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002564 void *InsertPos = 0;
2565 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2566 return QualType(VTP, 0);
2567
2568 // If the element type isn't canonical, this won't be a canonical type either,
2569 // so fill in the canonical type field.
2570 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002571 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002572 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002573
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002574 // Get the new insert position for the node we care about.
2575 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002576 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002577 }
John McCall90d1c2d2009-09-24 23:30:46 +00002578 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002579 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002580 VectorTypes.InsertNode(New, InsertPos);
2581 Types.push_back(New);
2582 return QualType(New, 0);
2583}
2584
Nate Begemance4d7fc2008-04-18 23:10:10 +00002585/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002586/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002587QualType
2588ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002589 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002590
Steve Naroff91fcddb2007-07-18 18:00:27 +00002591 // Check if we've already instantiated a vector of this type.
2592 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002593 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002594 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002595 void *InsertPos = 0;
2596 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2597 return QualType(VTP, 0);
2598
2599 // If the element type isn't canonical, this won't be a canonical type either,
2600 // so fill in the canonical type field.
2601 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002602 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002603 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002604
Steve Naroff91fcddb2007-07-18 18:00:27 +00002605 // Get the new insert position for the node we care about.
2606 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002607 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002608 }
John McCall90d1c2d2009-09-24 23:30:46 +00002609 ExtVectorType *New = new (*this, TypeAlignment)
2610 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002611 VectorTypes.InsertNode(New, InsertPos);
2612 Types.push_back(New);
2613 return QualType(New, 0);
2614}
2615
Jay Foad39c79802011-01-12 09:06:06 +00002616QualType
2617ASTContext::getDependentSizedExtVectorType(QualType vecType,
2618 Expr *SizeExpr,
2619 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002620 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002621 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002622 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002623
Douglas Gregor352169a2009-07-31 03:54:25 +00002624 void *InsertPos = 0;
2625 DependentSizedExtVectorType *Canon
2626 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2627 DependentSizedExtVectorType *New;
2628 if (Canon) {
2629 // We already have a canonical version of this array type; use it as
2630 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002631 New = new (*this, TypeAlignment)
2632 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2633 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002634 } else {
2635 QualType CanonVecTy = getCanonicalType(vecType);
2636 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002637 New = new (*this, TypeAlignment)
2638 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2639 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002640
2641 DependentSizedExtVectorType *CanonCheck
2642 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2643 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2644 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002645 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2646 } else {
2647 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2648 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002649 New = new (*this, TypeAlignment)
2650 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002651 }
2652 }
Mike Stump11289f42009-09-09 15:08:12 +00002653
Douglas Gregor758a8692009-06-17 21:51:59 +00002654 Types.push_back(New);
2655 return QualType(New, 0);
2656}
2657
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002658/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002659///
Jay Foad39c79802011-01-12 09:06:06 +00002660QualType
2661ASTContext::getFunctionNoProtoType(QualType ResultTy,
2662 const FunctionType::ExtInfo &Info) const {
Roman Divacky65b88cd2011-03-01 17:40:53 +00002663 const CallingConv DefaultCC = Info.getCC();
2664 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2665 CC_X86StdCall : DefaultCC;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002666 // Unique functions, to guarantee there is only one function of a particular
2667 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002668 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002669 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002670
Chris Lattner47955de2007-01-27 08:37:20 +00002671 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002672 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002673 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002674 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002675
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002676 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00002677 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00002678 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002679 Canonical =
2680 getFunctionNoProtoType(getCanonicalType(ResultTy),
2681 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00002682
Chris Lattner47955de2007-01-27 08:37:20 +00002683 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002684 FunctionNoProtoType *NewIP =
2685 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002686 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002687 }
Mike Stump11289f42009-09-09 15:08:12 +00002688
Roman Divacky65b88cd2011-03-01 17:40:53 +00002689 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002690 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002691 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002692 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002693 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002694 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002695}
2696
Douglas Gregorcd780372013-01-17 23:36:45 +00002697/// \brief Determine whether \p T is canonical as the result type of a function.
2698static bool isCanonicalResultType(QualType T) {
2699 return T.isCanonical() &&
2700 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2701 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2702}
2703
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002704/// getFunctionType - Return a normal function type with a typed argument
2705/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00002706QualType
Jordan Rose5c382722013-03-08 21:51:21 +00002707ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad39c79802011-01-12 09:06:06 +00002708 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rose5c382722013-03-08 21:51:21 +00002709 size_t NumArgs = ArgArray.size();
2710
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002711 // Unique functions, to guarantee there is only one function of a particular
2712 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002713 llvm::FoldingSetNodeID ID;
Jordan Rose5c382722013-03-08 21:51:21 +00002714 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
2715 *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002716
2717 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002718 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002719 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002720 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002721
2722 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002723 bool isCanonical =
Douglas Gregorcd780372013-01-17 23:36:45 +00002724 EPI.ExceptionSpecType == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smith5e580292012-02-10 09:58:53 +00002725 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002726 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002727 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002728 isCanonical = false;
2729
Roman Divacky65b88cd2011-03-01 17:40:53 +00002730 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2731 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2732 CC_X86StdCall : DefaultCC;
John McCalldb40c7f2010-12-14 08:05:40 +00002733
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002734 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002735 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002736 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00002737 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002738 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002739 CanonicalArgs.reserve(NumArgs);
2740 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002741 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002742
John McCalldb40c7f2010-12-14 08:05:40 +00002743 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002744 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002745 CanonicalEPI.ExceptionSpecType = EST_None;
2746 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002747 CanonicalEPI.ExtInfo
2748 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2749
Douglas Gregorcd780372013-01-17 23:36:45 +00002750 // Result types do not have ARC lifetime qualifiers.
2751 QualType CanResultTy = getCanonicalType(ResultTy);
2752 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2753 Qualifiers Qs = CanResultTy.getQualifiers();
2754 Qs.removeObjCLifetime();
2755 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2756 }
2757
Jordan Rose5c382722013-03-08 21:51:21 +00002758 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002759
Chris Lattnerfd4de792007-01-27 01:15:32 +00002760 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002761 FunctionProtoType *NewIP =
2762 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002763 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002764 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002765
John McCall31168b02011-06-15 23:02:42 +00002766 // FunctionProtoType objects are allocated with extra bytes after
2767 // them for three variable size arrays at the end:
2768 // - parameter types
2769 // - exception types
2770 // - consumed-arguments flags
2771 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00002772 // expression, or information used to resolve the exception
2773 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00002774 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002775 NumArgs * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002776 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002777 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002778 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002779 Size += sizeof(Expr*);
Richard Smithf623c962012-04-17 00:58:00 +00002780 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00002781 Size += 2 * sizeof(FunctionDecl*);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002782 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2783 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002784 }
John McCall31168b02011-06-15 23:02:42 +00002785 if (EPI.ConsumedArguments)
2786 Size += NumArgs * sizeof(bool);
2787
John McCalldb40c7f2010-12-14 08:05:40 +00002788 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002789 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2790 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Jordan Rose5c382722013-03-08 21:51:21 +00002791 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002792 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002793 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002794 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002795}
Chris Lattneref51c202006-11-10 07:17:23 +00002796
John McCalle78aac42010-03-10 03:28:59 +00002797#ifndef NDEBUG
2798static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2799 if (!isa<CXXRecordDecl>(D)) return false;
2800 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2801 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2802 return true;
2803 if (RD->getDescribedClassTemplate() &&
2804 !isa<ClassTemplateSpecializationDecl>(RD))
2805 return true;
2806 return false;
2807}
2808#endif
2809
2810/// getInjectedClassNameType - Return the unique reference to the
2811/// injected class name type for the specified templated declaration.
2812QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002813 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002814 assert(NeedsInjectedClassNameType(Decl));
2815 if (Decl->TypeForDecl) {
2816 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00002817 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00002818 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2819 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2820 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2821 } else {
John McCall424cec92011-01-19 06:33:43 +00002822 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002823 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002824 Decl->TypeForDecl = newType;
2825 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002826 }
2827 return QualType(Decl->TypeForDecl, 0);
2828}
2829
Douglas Gregor83a586e2008-04-13 21:07:44 +00002830/// getTypeDeclType - Return the unique reference to the type for the
2831/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002832QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002833 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002834 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002835
Richard Smithdda56e42011-04-15 14:24:37 +00002836 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002837 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002838
John McCall96f0b5f2010-03-10 06:48:02 +00002839 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2840 "Template type parameter types are always available.");
2841
John McCall81e38502010-02-16 03:57:14 +00002842 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002843 assert(!Record->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002844 "struct/union has previous declaration");
2845 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002846 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002847 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002848 assert(!Enum->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002849 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002850 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002851 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002852 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002853 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2854 Decl->TypeForDecl = newType;
2855 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002856 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002857 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002858
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002859 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002860}
2861
Chris Lattner32d920b2007-01-26 02:01:53 +00002862/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002863/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002864QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002865ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2866 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002867 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002868
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002869 if (Canonical.isNull())
2870 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002871 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002872 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002873 Decl->TypeForDecl = newType;
2874 Types.push_back(newType);
2875 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002876}
2877
Jay Foad39c79802011-01-12 09:06:06 +00002878QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002879 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2880
Douglas Gregorec9fd132012-01-14 16:38:05 +00002881 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002882 if (PrevDecl->TypeForDecl)
2883 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2884
John McCall424cec92011-01-19 06:33:43 +00002885 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2886 Decl->TypeForDecl = newType;
2887 Types.push_back(newType);
2888 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002889}
2890
Jay Foad39c79802011-01-12 09:06:06 +00002891QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002892 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2893
Douglas Gregorec9fd132012-01-14 16:38:05 +00002894 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002895 if (PrevDecl->TypeForDecl)
2896 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2897
John McCall424cec92011-01-19 06:33:43 +00002898 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2899 Decl->TypeForDecl = newType;
2900 Types.push_back(newType);
2901 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002902}
2903
John McCall81904512011-01-06 01:58:22 +00002904QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2905 QualType modifiedType,
2906 QualType equivalentType) {
2907 llvm::FoldingSetNodeID id;
2908 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2909
2910 void *insertPos = 0;
2911 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2912 if (type) return QualType(type, 0);
2913
2914 QualType canon = getCanonicalType(equivalentType);
2915 type = new (*this, TypeAlignment)
2916 AttributedType(canon, attrKind, modifiedType, equivalentType);
2917
2918 Types.push_back(type);
2919 AttributedTypes.InsertNode(type, insertPos);
2920
2921 return QualType(type, 0);
2922}
2923
2924
John McCallcebee162009-10-18 09:09:24 +00002925/// \brief Retrieve a substitution-result type.
2926QualType
2927ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00002928 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00002929 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00002930 && "replacement types must always be canonical");
2931
2932 llvm::FoldingSetNodeID ID;
2933 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2934 void *InsertPos = 0;
2935 SubstTemplateTypeParmType *SubstParm
2936 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2937
2938 if (!SubstParm) {
2939 SubstParm = new (*this, TypeAlignment)
2940 SubstTemplateTypeParmType(Parm, Replacement);
2941 Types.push_back(SubstParm);
2942 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2943 }
2944
2945 return QualType(SubstParm, 0);
2946}
2947
Douglas Gregorada4b792011-01-14 02:55:32 +00002948/// \brief Retrieve a
2949QualType ASTContext::getSubstTemplateTypeParmPackType(
2950 const TemplateTypeParmType *Parm,
2951 const TemplateArgument &ArgPack) {
2952#ifndef NDEBUG
2953 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2954 PEnd = ArgPack.pack_end();
2955 P != PEnd; ++P) {
2956 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2957 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2958 }
2959#endif
2960
2961 llvm::FoldingSetNodeID ID;
2962 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2963 void *InsertPos = 0;
2964 if (SubstTemplateTypeParmPackType *SubstParm
2965 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2966 return QualType(SubstParm, 0);
2967
2968 QualType Canon;
2969 if (!Parm->isCanonicalUnqualified()) {
2970 Canon = getCanonicalType(QualType(Parm, 0));
2971 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2972 ArgPack);
2973 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2974 }
2975
2976 SubstTemplateTypeParmPackType *SubstParm
2977 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2978 ArgPack);
2979 Types.push_back(SubstParm);
2980 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2981 return QualType(SubstParm, 0);
2982}
2983
Douglas Gregoreff93e02009-02-05 23:33:38 +00002984/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00002985/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00002986/// name.
Mike Stump11289f42009-09-09 15:08:12 +00002987QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00002988 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00002989 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00002990 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00002991 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002992 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002993 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00002994 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2995
2996 if (TypeParm)
2997 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002998
Chandler Carruth08836322011-05-01 00:51:33 +00002999 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003000 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003001 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003002
3003 TemplateTypeParmType *TypeCheck
3004 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3005 assert(!TypeCheck && "Template type parameter canonical type broken");
3006 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003007 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003008 TypeParm = new (*this, TypeAlignment)
3009 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003010
3011 Types.push_back(TypeParm);
3012 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3013
3014 return QualType(TypeParm, 0);
3015}
3016
John McCalle78aac42010-03-10 03:28:59 +00003017TypeSourceInfo *
3018ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3019 SourceLocation NameLoc,
3020 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003021 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003022 assert(!Name.getAsDependentTemplateName() &&
3023 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003024 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003025
3026 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003027 TemplateSpecializationTypeLoc TL =
3028 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003029 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003030 TL.setTemplateNameLoc(NameLoc);
3031 TL.setLAngleLoc(Args.getLAngleLoc());
3032 TL.setRAngleLoc(Args.getRAngleLoc());
3033 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3034 TL.setArgLocInfo(i, Args[i].getLocInfo());
3035 return DI;
3036}
3037
Mike Stump11289f42009-09-09 15:08:12 +00003038QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003039ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003040 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003041 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003042 assert(!Template.getAsDependentTemplateName() &&
3043 "No dependent template names here!");
3044
John McCall6b51f282009-11-23 01:53:49 +00003045 unsigned NumArgs = Args.size();
3046
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003047 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00003048 ArgVec.reserve(NumArgs);
3049 for (unsigned i = 0; i != NumArgs; ++i)
3050 ArgVec.push_back(Args[i].getArgument());
3051
John McCall2408e322010-04-27 00:57:59 +00003052 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003053 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003054}
3055
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003056#ifndef NDEBUG
3057static bool hasAnyPackExpansions(const TemplateArgument *Args,
3058 unsigned NumArgs) {
3059 for (unsigned I = 0; I != NumArgs; ++I)
3060 if (Args[I].isPackExpansion())
3061 return true;
3062
3063 return true;
3064}
3065#endif
3066
John McCall0ad16662009-10-29 08:12:44 +00003067QualType
3068ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00003069 const TemplateArgument *Args,
3070 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003071 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003072 assert(!Template.getAsDependentTemplateName() &&
3073 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003074 // Look through qualified template names.
3075 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3076 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003077
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003078 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003079 Template.getAsTemplateDecl() &&
3080 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003081 QualType CanonType;
3082 if (!Underlying.isNull())
3083 CanonType = getCanonicalType(Underlying);
3084 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003085 // We can get here with an alias template when the specialization contains
3086 // a pack expansion that does not match up with a parameter pack.
3087 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3088 "Caller must compute aliased type");
3089 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003090 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3091 NumArgs);
3092 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003093
Douglas Gregora8e02e72009-07-28 23:00:59 +00003094 // Allocate the (non-canonical) template specialization type, but don't
3095 // try to unique it: these types typically have location information that
3096 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003097 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3098 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003099 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003100 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003101 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003102 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3103 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003104
Douglas Gregor8bf42052009-02-09 18:46:07 +00003105 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003106 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003107}
3108
Mike Stump11289f42009-09-09 15:08:12 +00003109QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003110ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3111 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00003112 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003113 assert(!Template.getAsDependentTemplateName() &&
3114 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003115
Douglas Gregore29139c2011-03-03 17:04:51 +00003116 // Look through qualified template names.
3117 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3118 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003119
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003120 // Build the canonical template specialization type.
3121 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003122 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003123 CanonArgs.reserve(NumArgs);
3124 for (unsigned I = 0; I != NumArgs; ++I)
3125 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3126
3127 // Determine whether this canonical template specialization type already
3128 // exists.
3129 llvm::FoldingSetNodeID ID;
3130 TemplateSpecializationType::Profile(ID, CanonTemplate,
3131 CanonArgs.data(), NumArgs, *this);
3132
3133 void *InsertPos = 0;
3134 TemplateSpecializationType *Spec
3135 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3136
3137 if (!Spec) {
3138 // Allocate a new canonical template specialization type.
3139 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3140 sizeof(TemplateArgument) * NumArgs),
3141 TypeAlignment);
3142 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3143 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003144 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003145 Types.push_back(Spec);
3146 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3147 }
3148
3149 assert(Spec->isDependentType() &&
3150 "Non-dependent template-id type must have a canonical type");
3151 return QualType(Spec, 0);
3152}
3153
3154QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003155ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3156 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003157 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003158 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003159 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003160
3161 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003162 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003163 if (T)
3164 return QualType(T, 0);
3165
Douglas Gregorc42075a2010-02-04 18:10:26 +00003166 QualType Canon = NamedType;
3167 if (!Canon.isCanonical()) {
3168 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003169 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3170 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003171 (void)CheckT;
3172 }
3173
Abramo Bagnara6150c882010-05-11 21:36:43 +00003174 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003175 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003176 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003177 return QualType(T, 0);
3178}
3179
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003180QualType
Jay Foad39c79802011-01-12 09:06:06 +00003181ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003182 llvm::FoldingSetNodeID ID;
3183 ParenType::Profile(ID, InnerType);
3184
3185 void *InsertPos = 0;
3186 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3187 if (T)
3188 return QualType(T, 0);
3189
3190 QualType Canon = InnerType;
3191 if (!Canon.isCanonical()) {
3192 Canon = getCanonicalType(InnerType);
3193 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3194 assert(!CheckT && "Paren canonical type broken");
3195 (void)CheckT;
3196 }
3197
3198 T = new (*this) ParenType(InnerType, Canon);
3199 Types.push_back(T);
3200 ParenTypes.InsertNode(T, InsertPos);
3201 return QualType(T, 0);
3202}
3203
Douglas Gregor02085352010-03-31 20:19:30 +00003204QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3205 NestedNameSpecifier *NNS,
3206 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003207 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003208 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
3209
3210 if (Canon.isNull()) {
3211 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00003212 ElaboratedTypeKeyword CanonKeyword = Keyword;
3213 if (Keyword == ETK_None)
3214 CanonKeyword = ETK_Typename;
3215
3216 if (CanonNNS != NNS || CanonKeyword != Keyword)
3217 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003218 }
3219
3220 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003221 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003222
3223 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003224 DependentNameType *T
3225 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003226 if (T)
3227 return QualType(T, 0);
3228
Douglas Gregor02085352010-03-31 20:19:30 +00003229 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003230 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003231 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003232 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003233}
3234
Mike Stump11289f42009-09-09 15:08:12 +00003235QualType
John McCallc392f372010-06-11 00:33:02 +00003236ASTContext::getDependentTemplateSpecializationType(
3237 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003238 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003239 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003240 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003241 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003242 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003243 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3244 ArgCopy.push_back(Args[I].getArgument());
3245 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3246 ArgCopy.size(),
3247 ArgCopy.data());
3248}
3249
3250QualType
3251ASTContext::getDependentTemplateSpecializationType(
3252 ElaboratedTypeKeyword Keyword,
3253 NestedNameSpecifier *NNS,
3254 const IdentifierInfo *Name,
3255 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00003256 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003257 assert((!NNS || NNS->isDependent()) &&
3258 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003259
Douglas Gregorc42075a2010-02-04 18:10:26 +00003260 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003261 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3262 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003263
3264 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00003265 DependentTemplateSpecializationType *T
3266 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003267 if (T)
3268 return QualType(T, 0);
3269
John McCallc392f372010-06-11 00:33:02 +00003270 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003271
John McCallc392f372010-06-11 00:33:02 +00003272 ElaboratedTypeKeyword CanonKeyword = Keyword;
3273 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3274
3275 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003276 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003277 for (unsigned I = 0; I != NumArgs; ++I) {
3278 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3279 if (!CanonArgs[I].structurallyEquals(Args[I]))
3280 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003281 }
3282
John McCallc392f372010-06-11 00:33:02 +00003283 QualType Canon;
3284 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3285 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3286 Name, NumArgs,
3287 CanonArgs.data());
3288
3289 // Find the insert position again.
3290 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3291 }
3292
3293 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3294 sizeof(TemplateArgument) * NumArgs),
3295 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003296 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00003297 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003298 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003299 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003300 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003301}
3302
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003303QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00003304 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003305 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003306 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003307
3308 assert(Pattern->containsUnexpandedParameterPack() &&
3309 "Pack expansions must expand one or more parameter packs");
3310 void *InsertPos = 0;
3311 PackExpansionType *T
3312 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3313 if (T)
3314 return QualType(T, 0);
3315
3316 QualType Canon;
3317 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003318 Canon = getCanonicalType(Pattern);
3319 // The canonical type might not contain an unexpanded parameter pack, if it
3320 // contains an alias template specialization which ignores one of its
3321 // parameters.
3322 if (Canon->containsUnexpandedParameterPack()) {
3323 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003324
Richard Smith68eea502012-07-16 00:20:35 +00003325 // Find the insert position again, in case we inserted an element into
3326 // PackExpansionTypes and invalidated our insert position.
3327 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3328 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003329 }
3330
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003331 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003332 Types.push_back(T);
3333 PackExpansionTypes.InsertNode(T, InsertPos);
3334 return QualType(T, 0);
3335}
3336
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003337/// CmpProtocolNames - Comparison predicate for sorting protocols
3338/// alphabetically.
3339static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3340 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00003341 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003342}
3343
John McCall8b07ec22010-05-15 11:32:37 +00003344static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00003345 unsigned NumProtocols) {
3346 if (NumProtocols == 0) return true;
3347
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003348 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3349 return false;
3350
John McCallfc93cf92009-10-22 22:37:11 +00003351 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003352 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3353 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003354 return false;
3355 return true;
3356}
3357
3358static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003359 unsigned &NumProtocols) {
3360 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00003361
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003362 // Sort protocols, keyed by name.
3363 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3364
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003365 // Canonicalize.
3366 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3367 Protocols[I] = Protocols[I]->getCanonicalDecl();
3368
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003369 // Remove duplicates.
3370 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3371 NumProtocols = ProtocolsEnd-Protocols;
3372}
3373
John McCall8b07ec22010-05-15 11:32:37 +00003374QualType ASTContext::getObjCObjectType(QualType BaseType,
3375 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003376 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00003377 // If the base type is an interface and there aren't any protocols
3378 // to add, then the interface type will do just fine.
3379 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3380 return BaseType;
3381
3382 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003383 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00003384 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00003385 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00003386 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3387 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003388
John McCall8b07ec22010-05-15 11:32:37 +00003389 // Build the canonical type, which has the canonical base type and
3390 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00003391 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00003392 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3393 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3394 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003395 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003396 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003397 unsigned UniqueCount = NumProtocols;
3398
John McCallfc93cf92009-10-22 22:37:11 +00003399 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00003400 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3401 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00003402 } else {
John McCall8b07ec22010-05-15 11:32:37 +00003403 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3404 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003405 }
3406
3407 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003408 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3409 }
3410
3411 unsigned Size = sizeof(ObjCObjectTypeImpl);
3412 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3413 void *Mem = Allocate(Size, TypeAlignment);
3414 ObjCObjectTypeImpl *T =
3415 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3416
3417 Types.push_back(T);
3418 ObjCObjectTypes.InsertNode(T, InsertPos);
3419 return QualType(T, 0);
3420}
3421
3422/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3423/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003424QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003425 llvm::FoldingSetNodeID ID;
3426 ObjCObjectPointerType::Profile(ID, ObjectT);
3427
3428 void *InsertPos = 0;
3429 if (ObjCObjectPointerType *QT =
3430 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3431 return QualType(QT, 0);
3432
3433 // Find the canonical object type.
3434 QualType Canonical;
3435 if (!ObjectT.isCanonical()) {
3436 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3437
3438 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003439 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3440 }
3441
Douglas Gregorf85bee62010-02-08 22:59:26 +00003442 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003443 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3444 ObjCObjectPointerType *QType =
3445 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003446
Steve Narofffb4330f2009-06-17 22:40:22 +00003447 Types.push_back(QType);
3448 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003449 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003450}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003451
Douglas Gregor1c283312010-08-11 12:19:30 +00003452/// getObjCInterfaceType - Return the unique reference to the type for the
3453/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003454QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3455 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003456 if (Decl->TypeForDecl)
3457 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003458
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003459 if (PrevDecl) {
3460 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3461 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3462 return QualType(PrevDecl->TypeForDecl, 0);
3463 }
3464
Douglas Gregor7671e532011-12-16 16:34:57 +00003465 // Prefer the definition, if there is one.
3466 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3467 Decl = Def;
3468
Douglas Gregor1c283312010-08-11 12:19:30 +00003469 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3470 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3471 Decl->TypeForDecl = T;
3472 Types.push_back(T);
3473 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003474}
3475
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003476/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3477/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003478/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003479/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003480/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003481QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003482 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003483 if (tofExpr->isTypeDependent()) {
3484 llvm::FoldingSetNodeID ID;
3485 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003486
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003487 void *InsertPos = 0;
3488 DependentTypeOfExprType *Canon
3489 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3490 if (Canon) {
3491 // We already have a "canonical" version of an identical, dependent
3492 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003493 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003494 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003495 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003496 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003497 Canon
3498 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003499 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3500 toe = Canon;
3501 }
3502 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003503 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003504 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003505 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003506 Types.push_back(toe);
3507 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003508}
3509
Steve Naroffa773cd52007-08-01 18:02:17 +00003510/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3511/// TypeOfType AST's. The only motivation to unique these nodes would be
3512/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003513/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003514/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003515QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003516 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003517 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003518 Types.push_back(tot);
3519 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003520}
3521
Anders Carlssonad6bd352009-06-24 21:24:56 +00003522
Anders Carlsson81df7b82009-06-24 19:06:50 +00003523/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3524/// DecltypeType AST's. The only motivation to unique these nodes would be
3525/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003526/// an issue. This doesn't effect the type checker, since it operates
David Blaikie876657b2011-11-06 22:28:03 +00003527/// on canonical types (which are always unique).
Douglas Gregor81495f32012-02-12 18:42:33 +00003528QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003529 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003530
3531 // C++0x [temp.type]p2:
3532 // If an expression e involves a template parameter, decltype(e) denotes a
3533 // unique dependent type. Two such decltype-specifiers refer to the same
3534 // type only if their expressions are equivalent (14.5.6.1).
3535 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003536 llvm::FoldingSetNodeID ID;
3537 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003538
Douglas Gregora21f6c32009-07-30 23:36:40 +00003539 void *InsertPos = 0;
3540 DependentDecltypeType *Canon
3541 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3542 if (Canon) {
3543 // We already have a "canonical" version of an equivalent, dependent
3544 // decltype type. Use that as our canonical type.
Richard Smithef8bf432012-08-13 20:08:14 +00003545 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
Douglas Gregora21f6c32009-07-30 23:36:40 +00003546 QualType((DecltypeType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003547 } else {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003548 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003549 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003550 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3551 dt = Canon;
3552 }
3553 } else {
Douglas Gregor81495f32012-02-12 18:42:33 +00003554 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3555 getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003556 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003557 Types.push_back(dt);
3558 return QualType(dt, 0);
3559}
3560
Alexis Hunte852b102011-05-24 22:41:36 +00003561/// getUnaryTransformationType - We don't unique these, since the memory
3562/// savings are minimal and these are rare.
3563QualType ASTContext::getUnaryTransformType(QualType BaseType,
3564 QualType UnderlyingType,
3565 UnaryTransformType::UTTKind Kind)
3566 const {
3567 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003568 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3569 Kind,
3570 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003571 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003572 Types.push_back(Ty);
3573 return QualType(Ty, 0);
3574}
3575
Richard Smith2a7d4812013-05-04 07:00:32 +00003576/// getAutoType - Return the uniqued reference to the 'auto' type which has been
3577/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3578/// canonical deduced-but-dependent 'auto' type.
3579QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
Richard Smith27d807c2013-04-30 13:56:41 +00003580 bool IsDependent) const {
Richard Smith2a7d4812013-05-04 07:00:32 +00003581 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
3582 return getAutoDeductType();
3583
3584 // Look in the folding set for an existing type.
Richard Smithb2bc2e62011-02-21 20:05:19 +00003585 void *InsertPos = 0;
Richard Smith2a7d4812013-05-04 07:00:32 +00003586 llvm::FoldingSetNodeID ID;
3587 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
3588 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3589 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003590
Richard Smith74aeef52013-04-26 16:15:35 +00003591 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smith27d807c2013-04-30 13:56:41 +00003592 IsDecltypeAuto,
3593 IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003594 Types.push_back(AT);
3595 if (InsertPos)
3596 AutoTypes.InsertNode(AT, InsertPos);
3597 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003598}
3599
Eli Friedman0dfb8892011-10-06 23:00:33 +00003600/// getAtomicType - Return the uniqued reference to the atomic type for
3601/// the given value type.
3602QualType ASTContext::getAtomicType(QualType T) const {
3603 // Unique pointers, to guarantee there is only one pointer of a particular
3604 // structure.
3605 llvm::FoldingSetNodeID ID;
3606 AtomicType::Profile(ID, T);
3607
3608 void *InsertPos = 0;
3609 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3610 return QualType(AT, 0);
3611
3612 // If the atomic value type isn't canonical, this won't be a canonical type
3613 // either, so fill in the canonical type field.
3614 QualType Canonical;
3615 if (!T.isCanonical()) {
3616 Canonical = getAtomicType(getCanonicalType(T));
3617
3618 // Get the new insert position for the node we care about.
3619 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3620 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3621 }
3622 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3623 Types.push_back(New);
3624 AtomicTypes.InsertNode(New, InsertPos);
3625 return QualType(New, 0);
3626}
3627
Richard Smith02e85f32011-04-14 22:09:26 +00003628/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3629QualType ASTContext::getAutoDeductType() const {
3630 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00003631 AutoDeductTy = QualType(
3632 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
3633 /*dependent*/false),
3634 0);
Richard Smith02e85f32011-04-14 22:09:26 +00003635 return AutoDeductTy;
3636}
3637
3638/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3639QualType ASTContext::getAutoRRefDeductType() const {
3640 if (AutoRRefDeductTy.isNull())
3641 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3642 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3643 return AutoRRefDeductTy;
3644}
3645
Chris Lattnerfb072462007-01-23 05:45:31 +00003646/// getTagDeclType - Return the unique reference to the type for the
3647/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003648QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003649 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003650 // FIXME: What is the design on getTagDeclType when it requires casting
3651 // away const? mutable?
3652 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003653}
3654
Mike Stump11289f42009-09-09 15:08:12 +00003655/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3656/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3657/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003658CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003659 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003660}
Chris Lattnerfb072462007-01-23 05:45:31 +00003661
Hans Wennborg27541db2011-10-27 08:29:09 +00003662/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3663CanQualType ASTContext::getIntMaxType() const {
3664 return getFromTargetType(Target->getIntMaxType());
3665}
3666
3667/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3668CanQualType ASTContext::getUIntMaxType() const {
3669 return getFromTargetType(Target->getUIntMaxType());
3670}
3671
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003672/// getSignedWCharType - Return the type of "signed wchar_t".
3673/// Used when in C++, as a GCC extension.
3674QualType ASTContext::getSignedWCharType() const {
3675 // FIXME: derive from "Target" ?
3676 return WCharTy;
3677}
3678
3679/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3680/// Used when in C++, as a GCC extension.
3681QualType ASTContext::getUnsignedWCharType() const {
3682 // FIXME: derive from "Target" ?
3683 return UnsignedIntTy;
3684}
3685
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00003686QualType ASTContext::getIntPtrType() const {
3687 return getFromTargetType(Target->getIntPtrType());
3688}
3689
3690QualType ASTContext::getUIntPtrType() const {
3691 return getCorrespondingUnsignedType(getIntPtrType());
3692}
3693
Hans Wennborg27541db2011-10-27 08:29:09 +00003694/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003695/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3696QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003697 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003698}
3699
Eli Friedman4e91899e2012-11-27 02:58:24 +00003700/// \brief Return the unique type for "pid_t" defined in
3701/// <sys/types.h>. We need this to compute the correct type for vfork().
3702QualType ASTContext::getProcessIDType() const {
3703 return getFromTargetType(Target->getProcessIDType());
3704}
3705
Chris Lattnera21ad802008-04-02 05:18:44 +00003706//===----------------------------------------------------------------------===//
3707// Type Operators
3708//===----------------------------------------------------------------------===//
3709
Jay Foad39c79802011-01-12 09:06:06 +00003710CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003711 // Push qualifiers into arrays, and then discard any remaining
3712 // qualifiers.
3713 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003714 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003715 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003716 QualType Result;
3717 if (isa<ArrayType>(Ty)) {
3718 Result = getArrayDecayedType(QualType(Ty,0));
3719 } else if (isa<FunctionType>(Ty)) {
3720 Result = getPointerType(QualType(Ty, 0));
3721 } else {
3722 Result = QualType(Ty, 0);
3723 }
3724
3725 return CanQualType::CreateUnsafe(Result);
3726}
3727
John McCall6c9dd522011-01-18 07:41:22 +00003728QualType ASTContext::getUnqualifiedArrayType(QualType type,
3729 Qualifiers &quals) {
3730 SplitQualType splitType = type.getSplitUnqualifiedType();
3731
3732 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3733 // the unqualified desugared type and then drops it on the floor.
3734 // We then have to strip that sugar back off with
3735 // getUnqualifiedDesugaredType(), which is silly.
3736 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003737 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003738
3739 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003740 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003741 quals = splitType.Quals;
3742 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003743 }
3744
John McCall6c9dd522011-01-18 07:41:22 +00003745 // Otherwise, recurse on the array's element type.
3746 QualType elementType = AT->getElementType();
3747 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3748
3749 // If that didn't change the element type, AT has no qualifiers, so we
3750 // can just use the results in splitType.
3751 if (elementType == unqualElementType) {
3752 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00003753 quals = splitType.Quals;
3754 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00003755 }
3756
3757 // Otherwise, add in the qualifiers from the outermost type, then
3758 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00003759 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003760
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003761 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003762 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003763 CAT->getSizeModifier(), 0);
3764 }
3765
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003766 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003767 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003768 }
3769
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003770 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003771 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003772 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003773 VAT->getSizeModifier(),
3774 VAT->getIndexTypeCVRQualifiers(),
3775 VAT->getBracketsRange());
3776 }
3777
3778 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003779 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003780 DSAT->getSizeModifier(), 0,
3781 SourceRange());
3782}
3783
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003784/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3785/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3786/// they point to and return true. If T1 and T2 aren't pointer types
3787/// or pointer-to-member types, or if they are not similar at this
3788/// level, returns false and leaves T1 and T2 unchanged. Top-level
3789/// qualifiers on T1 and T2 are ignored. This function will typically
3790/// be called in a loop that successively "unwraps" pointer and
3791/// pointer-to-member types to compare them at each level.
3792bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3793 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3794 *T2PtrType = T2->getAs<PointerType>();
3795 if (T1PtrType && T2PtrType) {
3796 T1 = T1PtrType->getPointeeType();
3797 T2 = T2PtrType->getPointeeType();
3798 return true;
3799 }
3800
3801 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3802 *T2MPType = T2->getAs<MemberPointerType>();
3803 if (T1MPType && T2MPType &&
3804 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3805 QualType(T2MPType->getClass(), 0))) {
3806 T1 = T1MPType->getPointeeType();
3807 T2 = T2MPType->getPointeeType();
3808 return true;
3809 }
3810
David Blaikiebbafb8a2012-03-11 07:00:24 +00003811 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003812 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3813 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3814 if (T1OPType && T2OPType) {
3815 T1 = T1OPType->getPointeeType();
3816 T2 = T2OPType->getPointeeType();
3817 return true;
3818 }
3819 }
3820
3821 // FIXME: Block pointers, too?
3822
3823 return false;
3824}
3825
Jay Foad39c79802011-01-12 09:06:06 +00003826DeclarationNameInfo
3827ASTContext::getNameForTemplate(TemplateName Name,
3828 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003829 switch (Name.getKind()) {
3830 case TemplateName::QualifiedTemplate:
3831 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003832 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00003833 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3834 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003835
John McCalld9dfe3a2011-06-30 08:33:18 +00003836 case TemplateName::OverloadedTemplate: {
3837 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3838 // DNInfo work in progress: CHECKME: what about DNLoc?
3839 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3840 }
3841
3842 case TemplateName::DependentTemplate: {
3843 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003844 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00003845 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003846 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3847 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00003848 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003849 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3850 // DNInfo work in progress: FIXME: source locations?
3851 DeclarationNameLoc DNLoc;
3852 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3853 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3854 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00003855 }
3856 }
3857
John McCalld9dfe3a2011-06-30 08:33:18 +00003858 case TemplateName::SubstTemplateTemplateParm: {
3859 SubstTemplateTemplateParmStorage *subst
3860 = Name.getAsSubstTemplateTemplateParm();
3861 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3862 NameLoc);
3863 }
3864
3865 case TemplateName::SubstTemplateTemplateParmPack: {
3866 SubstTemplateTemplateParmPackStorage *subst
3867 = Name.getAsSubstTemplateTemplateParmPack();
3868 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3869 NameLoc);
3870 }
3871 }
3872
3873 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00003874}
3875
Jay Foad39c79802011-01-12 09:06:06 +00003876TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003877 switch (Name.getKind()) {
3878 case TemplateName::QualifiedTemplate:
3879 case TemplateName::Template: {
3880 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003881 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00003882 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003883 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3884
3885 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00003886 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003887 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00003888
John McCalld9dfe3a2011-06-30 08:33:18 +00003889 case TemplateName::OverloadedTemplate:
3890 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00003891
John McCalld9dfe3a2011-06-30 08:33:18 +00003892 case TemplateName::DependentTemplate: {
3893 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3894 assert(DTN && "Non-dependent template names must refer to template decls.");
3895 return DTN->CanonicalTemplateName;
3896 }
3897
3898 case TemplateName::SubstTemplateTemplateParm: {
3899 SubstTemplateTemplateParmStorage *subst
3900 = Name.getAsSubstTemplateTemplateParm();
3901 return getCanonicalTemplateName(subst->getReplacement());
3902 }
3903
3904 case TemplateName::SubstTemplateTemplateParmPack: {
3905 SubstTemplateTemplateParmPackStorage *subst
3906 = Name.getAsSubstTemplateTemplateParmPack();
3907 TemplateTemplateParmDecl *canonParameter
3908 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3909 TemplateArgument canonArgPack
3910 = getCanonicalTemplateArgument(subst->getArgumentPack());
3911 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3912 }
3913 }
3914
3915 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00003916}
3917
Douglas Gregoradee3e32009-11-11 23:06:43 +00003918bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3919 X = getCanonicalTemplateName(X);
3920 Y = getCanonicalTemplateName(Y);
3921 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3922}
3923
Mike Stump11289f42009-09-09 15:08:12 +00003924TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00003925ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00003926 switch (Arg.getKind()) {
3927 case TemplateArgument::Null:
3928 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003929
Douglas Gregora8e02e72009-07-28 23:00:59 +00003930 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00003931 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003932
Douglas Gregor31f55dc2012-04-06 22:40:38 +00003933 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00003934 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
3935 return TemplateArgument(D, Arg.isDeclForReferenceParam());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00003936 }
Mike Stump11289f42009-09-09 15:08:12 +00003937
Eli Friedmanb826a002012-09-26 02:36:12 +00003938 case TemplateArgument::NullPtr:
3939 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
3940 /*isNullPtr*/true);
3941
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003942 case TemplateArgument::Template:
3943 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003944
3945 case TemplateArgument::TemplateExpansion:
3946 return TemplateArgument(getCanonicalTemplateName(
3947 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00003948 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003949
Douglas Gregora8e02e72009-07-28 23:00:59 +00003950 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00003951 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00003952
Douglas Gregora8e02e72009-07-28 23:00:59 +00003953 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00003954 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00003955
Douglas Gregora8e02e72009-07-28 23:00:59 +00003956 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00003957 if (Arg.pack_size() == 0)
3958 return Arg;
3959
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003960 TemplateArgument *CanonArgs
3961 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00003962 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003963 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003964 AEnd = Arg.pack_end();
3965 A != AEnd; (void)++A, ++Idx)
3966 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00003967
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003968 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00003969 }
3970 }
3971
3972 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00003973 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00003974}
3975
Douglas Gregor333489b2009-03-27 23:10:48 +00003976NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00003977ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00003978 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00003979 return 0;
3980
3981 switch (NNS->getKind()) {
3982 case NestedNameSpecifier::Identifier:
3983 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00003984 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00003985 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3986 NNS->getAsIdentifier());
3987
3988 case NestedNameSpecifier::Namespace:
3989 // A namespace is canonical; build a nested-name-specifier with
3990 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00003991 return NestedNameSpecifier::Create(*this, 0,
3992 NNS->getAsNamespace()->getOriginalNamespace());
3993
3994 case NestedNameSpecifier::NamespaceAlias:
3995 // A namespace is canonical; build a nested-name-specifier with
3996 // this namespace and no prefix.
3997 return NestedNameSpecifier::Create(*this, 0,
3998 NNS->getAsNamespaceAlias()->getNamespace()
3999 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00004000
4001 case NestedNameSpecifier::TypeSpec:
4002 case NestedNameSpecifier::TypeSpecWithTemplate: {
4003 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004004
4005 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4006 // break it apart into its prefix and identifier, then reconsititute those
4007 // as the canonical nested-name-specifier. This is required to canonicalize
4008 // a dependent nested-name-specifier involving typedefs of dependent-name
4009 // types, e.g.,
4010 // typedef typename T::type T1;
4011 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00004012 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4013 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00004014 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004015
Eli Friedman5358a0a2012-03-03 04:09:56 +00004016 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4017 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4018 // first place?
John McCall33ddac02011-01-19 10:06:00 +00004019 return NestedNameSpecifier::Create(*this, 0, false,
4020 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00004021 }
4022
4023 case NestedNameSpecifier::Global:
4024 // The global specifier is canonical and unique.
4025 return NNS;
4026 }
4027
David Blaikie8a40f702012-01-17 06:56:22 +00004028 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00004029}
4030
Chris Lattner7adf0762008-08-04 07:31:14 +00004031
Jay Foad39c79802011-01-12 09:06:06 +00004032const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004033 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004034 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00004035 // Handle the common positive case fast.
4036 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4037 return AT;
4038 }
Mike Stump11289f42009-09-09 15:08:12 +00004039
John McCall8ccfcb52009-09-24 19:53:00 +00004040 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00004041 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00004042 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004043
John McCall8ccfcb52009-09-24 19:53:00 +00004044 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00004045 // implements C99 6.7.3p8: "If the specification of an array type includes
4046 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00004047
Chris Lattner7adf0762008-08-04 07:31:14 +00004048 // If we get here, we either have type qualifiers on the type, or we have
4049 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00004050 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00004051
John McCall33ddac02011-01-19 10:06:00 +00004052 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004053 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00004054
Chris Lattner7adf0762008-08-04 07:31:14 +00004055 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00004056 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall33ddac02011-01-19 10:06:00 +00004057 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00004058 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00004059
Chris Lattner7adf0762008-08-04 07:31:14 +00004060 // Otherwise, we have an array and we have qualifiers on it. Push the
4061 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00004062 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00004063
Chris Lattner7adf0762008-08-04 07:31:14 +00004064 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4065 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4066 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004067 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00004068 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4069 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4070 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004071 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00004072
Mike Stump11289f42009-09-09 15:08:12 +00004073 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00004074 = dyn_cast<DependentSizedArrayType>(ATy))
4075 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00004076 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004077 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00004078 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004079 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004080 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00004081
Chris Lattner7adf0762008-08-04 07:31:14 +00004082 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00004083 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004084 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00004085 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004086 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004087 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00004088}
4089
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004090QualType ASTContext::getAdjustedParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004091 // C99 6.7.5.3p7:
4092 // A declaration of a parameter as "array of type" shall be
4093 // adjusted to "qualified pointer to type", where the type
4094 // qualifiers (if any) are those specified within the [ and ] of
4095 // the array type derivation.
4096 if (T->isArrayType())
4097 return getArrayDecayedType(T);
4098
4099 // C99 6.7.5.3p8:
4100 // A declaration of a parameter as "function returning type"
4101 // shall be adjusted to "pointer to function returning type", as
4102 // in 6.3.2.1.
4103 if (T->isFunctionType())
4104 return getPointerType(T);
4105
4106 return T;
4107}
4108
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004109QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004110 T = getVariableArrayDecayedType(T);
4111 T = getAdjustedParameterType(T);
4112 return T.getUnqualifiedType();
4113}
4114
Chris Lattnera21ad802008-04-02 05:18:44 +00004115/// getArrayDecayedType - Return the properly qualified result of decaying the
4116/// specified array type to a pointer. This operation is non-trivial when
4117/// handling typedefs etc. The canonical type of "T" must be an array type,
4118/// this returns a pointer to a properly qualified element of the array.
4119///
4120/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004121QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004122 // Get the element type with 'getAsArrayType' so that we don't lose any
4123 // typedefs in the element type of the array. This also handles propagation
4124 // of type qualifiers from the array type into the element type if present
4125 // (C99 6.7.3p8).
4126 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4127 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004128
Chris Lattner7adf0762008-08-04 07:31:14 +00004129 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004130
4131 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00004132 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00004133}
4134
John McCall33ddac02011-01-19 10:06:00 +00004135QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4136 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00004137}
4138
John McCall33ddac02011-01-19 10:06:00 +00004139QualType ASTContext::getBaseElementType(QualType type) const {
4140 Qualifiers qs;
4141 while (true) {
4142 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004143 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00004144 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00004145
John McCall33ddac02011-01-19 10:06:00 +00004146 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00004147 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00004148 }
Mike Stump11289f42009-09-09 15:08:12 +00004149
John McCall33ddac02011-01-19 10:06:00 +00004150 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00004151}
4152
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004153/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00004154uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004155ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4156 uint64_t ElementCount = 1;
4157 do {
4158 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00004159 CA = dyn_cast_or_null<ConstantArrayType>(
4160 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004161 } while (CA);
4162 return ElementCount;
4163}
4164
Steve Naroff0af91202007-04-27 21:51:21 +00004165/// getFloatingRank - Return a relative rank for floating point types.
4166/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00004167static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00004168 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00004169 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00004170
John McCall9dd450b2009-09-21 23:43:11 +00004171 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4172 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004173 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004174 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00004175 case BuiltinType::Float: return FloatRank;
4176 case BuiltinType::Double: return DoubleRank;
4177 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00004178 }
4179}
4180
Mike Stump11289f42009-09-09 15:08:12 +00004181/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4182/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00004183/// 'typeDomain' is a real floating point or complex type.
4184/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004185QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4186 QualType Domain) const {
4187 FloatingRank EltRank = getFloatingRank(Size);
4188 if (Domain->isComplexType()) {
4189 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004190 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00004191 case FloatRank: return FloatComplexTy;
4192 case DoubleRank: return DoubleComplexTy;
4193 case LongDoubleRank: return LongDoubleComplexTy;
4194 }
Steve Naroff0af91202007-04-27 21:51:21 +00004195 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004196
4197 assert(Domain->isRealFloatingType() && "Unknown domain!");
4198 switch (EltRank) {
Joey Goulydd7f4562013-01-23 11:56:20 +00004199 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004200 case FloatRank: return FloatTy;
4201 case DoubleRank: return DoubleTy;
4202 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00004203 }
David Blaikief47fa302012-01-17 02:30:50 +00004204 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00004205}
4206
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004207/// getFloatingTypeOrder - Compare the rank of the two specified floating
4208/// point types, ignoring the domain of the type (i.e. 'double' ==
4209/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004210/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004211int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00004212 FloatingRank LHSR = getFloatingRank(LHS);
4213 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004214
Chris Lattnerb90739d2008-04-06 23:38:49 +00004215 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004216 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00004217 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004218 return 1;
4219 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00004220}
4221
Chris Lattner76a00cf2008-04-06 22:59:24 +00004222/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4223/// routine will assert if passed a built-in type that isn't an integer or enum,
4224/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00004225unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00004226 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004227
Chris Lattner76a00cf2008-04-06 22:59:24 +00004228 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004229 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004230 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004231 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004232 case BuiltinType::Char_S:
4233 case BuiltinType::Char_U:
4234 case BuiltinType::SChar:
4235 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004236 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004237 case BuiltinType::Short:
4238 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004239 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004240 case BuiltinType::Int:
4241 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004242 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004243 case BuiltinType::Long:
4244 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004245 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004246 case BuiltinType::LongLong:
4247 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004248 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00004249 case BuiltinType::Int128:
4250 case BuiltinType::UInt128:
4251 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00004252 }
4253}
4254
Eli Friedman629ffb92009-08-20 04:21:42 +00004255/// \brief Whether this is a promotable bitfield reference according
4256/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4257///
4258/// \returns the type this bit-field will promote to, or NULL if no
4259/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004260QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004261 if (E->isTypeDependent() || E->isValueDependent())
4262 return QualType();
4263
Eli Friedman629ffb92009-08-20 04:21:42 +00004264 FieldDecl *Field = E->getBitField();
4265 if (!Field)
4266 return QualType();
4267
4268 QualType FT = Field->getType();
4269
Richard Smithcaf33902011-10-10 18:28:20 +00004270 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004271 uint64_t IntSize = getTypeSize(IntTy);
4272 // GCC extension compatibility: if the bit-field size is less than or equal
4273 // to the size of int, it gets promoted no matter what its type is.
4274 // For instance, unsigned long bf : 4 gets promoted to signed int.
4275 if (BitWidth < IntSize)
4276 return IntTy;
4277
4278 if (BitWidth == IntSize)
4279 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4280
4281 // Types bigger than int are not subject to promotions, and therefore act
4282 // like the base type.
4283 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4284 // is ridiculous.
4285 return QualType();
4286}
4287
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004288/// getPromotedIntegerType - Returns the type that Promotable will
4289/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4290/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004291QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004292 assert(!Promotable.isNull());
4293 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004294 if (const EnumType *ET = Promotable->getAs<EnumType>())
4295 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004296
4297 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4298 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4299 // (3.9.1) can be converted to a prvalue of the first of the following
4300 // types that can represent all the values of its underlying type:
4301 // int, unsigned int, long int, unsigned long int, long long int, or
4302 // unsigned long long int [...]
4303 // FIXME: Is there some better way to compute this?
4304 if (BT->getKind() == BuiltinType::WChar_S ||
4305 BT->getKind() == BuiltinType::WChar_U ||
4306 BT->getKind() == BuiltinType::Char16 ||
4307 BT->getKind() == BuiltinType::Char32) {
4308 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4309 uint64_t FromSize = getTypeSize(BT);
4310 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4311 LongLongTy, UnsignedLongLongTy };
4312 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4313 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4314 if (FromSize < ToSize ||
4315 (FromSize == ToSize &&
4316 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4317 return PromoteTypes[Idx];
4318 }
4319 llvm_unreachable("char type should fit into long long");
4320 }
4321 }
4322
4323 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004324 if (Promotable->isSignedIntegerType())
4325 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00004326 uint64_t PromotableSize = getIntWidth(Promotable);
4327 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004328 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4329 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4330}
4331
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004332/// \brief Recurses in pointer/array types until it finds an objc retainable
4333/// type and returns its ownership.
4334Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4335 while (!T.isNull()) {
4336 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4337 return T.getObjCLifetime();
4338 if (T->isArrayType())
4339 T = getBaseElementType(T);
4340 else if (const PointerType *PT = T->getAs<PointerType>())
4341 T = PT->getPointeeType();
4342 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004343 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004344 else
4345 break;
4346 }
4347
4348 return Qualifiers::OCL_None;
4349}
4350
Mike Stump11289f42009-09-09 15:08:12 +00004351/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004352/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004353/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004354int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004355 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4356 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004357 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004358
Chris Lattner76a00cf2008-04-06 22:59:24 +00004359 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4360 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004361
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004362 unsigned LHSRank = getIntegerRank(LHSC);
4363 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004364
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004365 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4366 if (LHSRank == RHSRank) return 0;
4367 return LHSRank > RHSRank ? 1 : -1;
4368 }
Mike Stump11289f42009-09-09 15:08:12 +00004369
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004370 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4371 if (LHSUnsigned) {
4372 // If the unsigned [LHS] type is larger, return it.
4373 if (LHSRank >= RHSRank)
4374 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004375
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004376 // If the signed type can represent all values of the unsigned type, it
4377 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004378 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004379 return -1;
4380 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004381
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004382 // If the unsigned [RHS] type is larger, return it.
4383 if (RHSRank >= LHSRank)
4384 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004385
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004386 // If the signed type can represent all values of the unsigned type, it
4387 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004388 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004389 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004390}
Anders Carlsson98f07902007-08-17 05:31:46 +00004391
Anders Carlsson6d417272009-11-14 21:45:58 +00004392static RecordDecl *
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004393CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
4394 DeclContext *DC, IdentifierInfo *Id) {
4395 SourceLocation Loc;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004396 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004397 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00004398 else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004399 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00004400}
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004401
Mike Stump11289f42009-09-09 15:08:12 +00004402// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00004403QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004404 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00004405 CFConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004406 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004407 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00004408 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004409
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004410 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00004411
Anders Carlsson98f07902007-08-17 05:31:46 +00004412 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004413 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004414 // int flags;
4415 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00004416 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004417 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00004418 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004419 FieldTypes[3] = LongTy;
4420
Anders Carlsson98f07902007-08-17 05:31:46 +00004421 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004422 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00004423 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004424 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00004425 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00004426 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00004427 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004428 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004429 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004430 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004431 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004432 }
4433
Douglas Gregord5058122010-02-11 01:19:42 +00004434 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00004435 }
Mike Stump11289f42009-09-09 15:08:12 +00004436
Anders Carlsson98f07902007-08-17 05:31:46 +00004437 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00004438}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004439
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004440QualType ASTContext::getObjCSuperType() const {
4441 if (ObjCSuperType.isNull()) {
4442 RecordDecl *ObjCSuperTypeDecl =
4443 CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get("objc_super"));
4444 TUDecl->addDecl(ObjCSuperTypeDecl);
4445 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4446 }
4447 return ObjCSuperType;
4448}
4449
Douglas Gregor512b0772009-04-23 22:29:11 +00004450void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004451 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00004452 assert(Rec && "Invalid CFConstantStringType");
4453 CFConstantStringTypeDecl = Rec->getDecl();
4454}
4455
Jay Foad39c79802011-01-12 09:06:06 +00004456QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004457 if (BlockDescriptorType)
4458 return getTagDeclType(BlockDescriptorType);
4459
4460 RecordDecl *T;
4461 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004462 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004463 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00004464 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004465
4466 QualType FieldTypes[] = {
4467 UnsignedLongTy,
4468 UnsignedLongTy,
4469 };
4470
4471 const char *FieldNames[] = {
4472 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004473 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004474 };
4475
4476 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004477 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00004478 SourceLocation(),
4479 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004480 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00004481 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004482 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004483 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004484 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00004485 T->addDecl(Field);
4486 }
4487
Douglas Gregord5058122010-02-11 01:19:42 +00004488 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004489
4490 BlockDescriptorType = T;
4491
4492 return getTagDeclType(BlockDescriptorType);
4493}
4494
Jay Foad39c79802011-01-12 09:06:06 +00004495QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004496 if (BlockDescriptorExtendedType)
4497 return getTagDeclType(BlockDescriptorExtendedType);
4498
4499 RecordDecl *T;
4500 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004501 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004502 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00004503 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004504
4505 QualType FieldTypes[] = {
4506 UnsignedLongTy,
4507 UnsignedLongTy,
4508 getPointerType(VoidPtrTy),
4509 getPointerType(VoidPtrTy)
4510 };
4511
4512 const char *FieldNames[] = {
4513 "reserved",
4514 "Size",
4515 "CopyFuncPtr",
4516 "DestroyFuncPtr"
4517 };
4518
4519 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004520 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004521 SourceLocation(),
4522 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004523 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004524 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004525 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004526 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004527 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004528 T->addDecl(Field);
4529 }
4530
Douglas Gregord5058122010-02-11 01:19:42 +00004531 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004532
4533 BlockDescriptorExtendedType = T;
4534
4535 return getTagDeclType(BlockDescriptorExtendedType);
4536}
4537
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004538/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4539/// requires copy/dispose. Note that this must match the logic
4540/// in buildByrefHelpers.
4541bool ASTContext::BlockRequiresCopying(QualType Ty,
4542 const VarDecl *D) {
4543 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4544 const Expr *copyExpr = getBlockVarCopyInits(D);
4545 if (!copyExpr && record->hasTrivialDestructor()) return false;
4546
Mike Stump94967902009-10-21 18:16:27 +00004547 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004548 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004549
4550 if (!Ty->isObjCRetainableType()) return false;
4551
4552 Qualifiers qs = Ty.getQualifiers();
4553
4554 // If we have lifetime, that dominates.
4555 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4556 assert(getLangOpts().ObjCAutoRefCount);
4557
4558 switch (lifetime) {
4559 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4560
4561 // These are just bits as far as the runtime is concerned.
4562 case Qualifiers::OCL_ExplicitNone:
4563 case Qualifiers::OCL_Autoreleasing:
4564 return false;
4565
4566 // Tell the runtime that this is ARC __weak, called by the
4567 // byref routines.
4568 case Qualifiers::OCL_Weak:
4569 // ARC __strong __block variables need to be retained.
4570 case Qualifiers::OCL_Strong:
4571 return true;
4572 }
4573 llvm_unreachable("fell out of lifetime switch!");
4574 }
4575 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4576 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00004577}
4578
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004579bool ASTContext::getByrefLifetime(QualType Ty,
4580 Qualifiers::ObjCLifetime &LifeTime,
4581 bool &HasByrefExtendedLayout) const {
4582
4583 if (!getLangOpts().ObjC1 ||
4584 getLangOpts().getGC() != LangOptions::NonGC)
4585 return false;
4586
4587 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00004588 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004589 HasByrefExtendedLayout = true;
4590 LifeTime = Qualifiers::OCL_None;
4591 }
4592 else if (getLangOpts().ObjCAutoRefCount)
4593 LifeTime = Ty.getObjCLifetime();
4594 // MRR.
4595 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4596 LifeTime = Qualifiers::OCL_ExplicitNone;
4597 else
4598 LifeTime = Qualifiers::OCL_None;
4599 return true;
4600}
4601
Douglas Gregorbab8a962011-09-08 01:46:34 +00004602TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4603 if (!ObjCInstanceTypeDecl)
4604 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4605 getTranslationUnitDecl(),
4606 SourceLocation(),
4607 SourceLocation(),
4608 &Idents.get("instancetype"),
4609 getTrivialTypeSourceInfo(getObjCIdType()));
4610 return ObjCInstanceTypeDecl;
4611}
4612
Anders Carlsson18acd442007-10-29 06:33:42 +00004613// This returns true if a type has been typedefed to BOOL:
4614// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004615static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004616 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004617 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4618 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004619
Anders Carlssond8499822007-10-29 05:01:08 +00004620 return false;
4621}
4622
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004623/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004624/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004625CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004626 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4627 return CharUnits::Zero();
4628
Ken Dyck40775002010-01-11 17:06:35 +00004629 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004630
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004631 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004632 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004633 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004634 // Treat arrays as pointers, since that's how they're passed in.
4635 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004636 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004637 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004638}
4639
4640static inline
4641std::string charUnitsToString(const CharUnits &CU) {
4642 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004643}
4644
John McCall351762c2011-02-07 10:33:21 +00004645/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004646/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004647std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4648 std::string S;
4649
David Chisnall950a9512009-11-17 19:33:30 +00004650 const BlockDecl *Decl = Expr->getBlockDecl();
4651 QualType BlockTy =
4652 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4653 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004654 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004655 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None,
4656 BlockTy->getAs<FunctionType>()->getResultType(),
4657 S, true /*Extended*/);
4658 else
4659 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(),
4660 S);
David Chisnall950a9512009-11-17 19:33:30 +00004661 // Compute size of all parameters.
4662 // Start with computing size of a pointer in number of bytes.
4663 // FIXME: There might(should) be a better way of doing this computation!
4664 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004665 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4666 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00004667 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00004668 E = Decl->param_end(); PI != E; ++PI) {
4669 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004670 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00004671 if (sz.isZero())
4672 continue;
Ken Dyck40775002010-01-11 17:06:35 +00004673 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004674 ParmOffset += sz;
4675 }
4676 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004677 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004678 // Block pointer and offset.
4679 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004680
4681 // Argument types.
4682 ParmOffset = PtrSize;
4683 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4684 Decl->param_end(); PI != E; ++PI) {
4685 ParmVarDecl *PVDecl = *PI;
4686 QualType PType = PVDecl->getOriginalType();
4687 if (const ArrayType *AT =
4688 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4689 // Use array's original type only if it has known number of
4690 // elements.
4691 if (!isa<ConstantArrayType>(AT))
4692 PType = PVDecl->getType();
4693 } else if (PType->isFunctionType())
4694 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004695 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004696 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4697 S, true /*Extended*/);
4698 else
4699 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004700 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004701 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004702 }
John McCall351762c2011-02-07 10:33:21 +00004703
4704 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004705}
4706
Douglas Gregora9d84932011-05-27 01:19:52 +00004707bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004708 std::string& S) {
4709 // Encode result type.
4710 getObjCEncodingForType(Decl->getResultType(), S);
4711 CharUnits ParmOffset;
4712 // Compute size of all parameters.
4713 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4714 E = Decl->param_end(); PI != E; ++PI) {
4715 QualType PType = (*PI)->getType();
4716 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004717 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004718 continue;
4719
David Chisnall50e4eba2010-12-30 14:05:53 +00004720 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004721 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004722 ParmOffset += sz;
4723 }
4724 S += charUnitsToString(ParmOffset);
4725 ParmOffset = CharUnits::Zero();
4726
4727 // Argument types.
4728 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4729 E = Decl->param_end(); PI != E; ++PI) {
4730 ParmVarDecl *PVDecl = *PI;
4731 QualType PType = PVDecl->getOriginalType();
4732 if (const ArrayType *AT =
4733 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4734 // Use array's original type only if it has known number of
4735 // elements.
4736 if (!isa<ConstantArrayType>(AT))
4737 PType = PVDecl->getType();
4738 } else if (PType->isFunctionType())
4739 PType = PVDecl->getType();
4740 getObjCEncodingForType(PType, S);
4741 S += charUnitsToString(ParmOffset);
4742 ParmOffset += getObjCEncodingTypeSize(PType);
4743 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004744
4745 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004746}
4747
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004748/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4749/// method parameter or return type. If Extended, include class names and
4750/// block object types.
4751void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4752 QualType T, std::string& S,
4753 bool Extended) const {
4754 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4755 getObjCEncodingForTypeQualifier(QT, S);
4756 // Encode parameter type.
4757 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4758 true /*OutermostType*/,
4759 false /*EncodingProperty*/,
4760 false /*StructField*/,
4761 Extended /*EncodeBlockParameters*/,
4762 Extended /*EncodeClassNames*/);
4763}
4764
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004765/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004766/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004767bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004768 std::string& S,
4769 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004770 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004771 // Encode return type.
4772 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4773 Decl->getResultType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004774 // Compute size of all parameters.
4775 // Start with computing size of a pointer in number of bytes.
4776 // FIXME: There might(should) be a better way of doing this computation!
4777 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004778 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004779 // The first two arguments (self and _cmd) are pointers; account for
4780 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004781 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004782 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004783 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004784 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004785 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004786 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004787 continue;
4788
Ken Dyck40775002010-01-11 17:06:35 +00004789 assert (sz.isPositive() &&
4790 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004791 ParmOffset += sz;
4792 }
Ken Dyck40775002010-01-11 17:06:35 +00004793 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004794 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004795 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004796
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004797 // Argument types.
4798 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004799 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004800 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004801 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004802 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004803 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004804 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4805 // Use array's original type only if it has known number of
4806 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004807 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004808 PType = PVDecl->getType();
4809 } else if (PType->isFunctionType())
4810 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004811 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4812 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00004813 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004814 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004815 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004816
4817 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004818}
4819
Daniel Dunbar4932b362008-08-28 04:38:10 +00004820/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004821/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004822/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4823/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004824/// Property attributes are stored as a comma-delimited C string. The simple
4825/// attributes readonly and bycopy are encoded as single characters. The
4826/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4827/// encoded as single characters, followed by an identifier. Property types
4828/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004829/// these attributes are defined by the following enumeration:
4830/// @code
4831/// enum PropertyAttributes {
4832/// kPropertyReadOnly = 'R', // property is read-only.
4833/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4834/// kPropertyByref = '&', // property is a reference to the value last assigned
4835/// kPropertyDynamic = 'D', // property is dynamic
4836/// kPropertyGetter = 'G', // followed by getter selector name
4837/// kPropertySetter = 'S', // followed by setter selector name
4838/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00004839/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004840/// kPropertyWeak = 'W' // 'weak' property
4841/// kPropertyStrong = 'P' // property GC'able
4842/// kPropertyNonAtomic = 'N' // property non-atomic
4843/// };
4844/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00004845void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00004846 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00004847 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004848 // Collect information from the property implementation decl(s).
4849 bool Dynamic = false;
4850 ObjCPropertyImplDecl *SynthesizePID = 0;
4851
4852 // FIXME: Duplicated code due to poor abstraction.
4853 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00004854 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00004855 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4856 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004857 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004858 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004859 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004860 if (PID->getPropertyDecl() == PD) {
4861 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4862 Dynamic = true;
4863 } else {
4864 SynthesizePID = PID;
4865 }
4866 }
4867 }
4868 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00004869 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004870 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004871 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004872 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004873 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004874 if (PID->getPropertyDecl() == PD) {
4875 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4876 Dynamic = true;
4877 } else {
4878 SynthesizePID = PID;
4879 }
4880 }
Mike Stump11289f42009-09-09 15:08:12 +00004881 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00004882 }
4883 }
4884
4885 // FIXME: This is not very efficient.
4886 S = "T";
4887
4888 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004889 // GCC has some special rules regarding encoding of properties which
4890 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00004891 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004892 true /* outermost type */,
4893 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004894
4895 if (PD->isReadOnly()) {
4896 S += ",R";
4897 } else {
4898 switch (PD->getSetterKind()) {
4899 case ObjCPropertyDecl::Assign: break;
4900 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00004901 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00004902 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004903 }
4904 }
4905
4906 // It really isn't clear at all what this means, since properties
4907 // are "dynamic by default".
4908 if (Dynamic)
4909 S += ",D";
4910
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004911 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4912 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00004913
Daniel Dunbar4932b362008-08-28 04:38:10 +00004914 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4915 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00004916 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004917 }
4918
4919 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4920 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00004921 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004922 }
4923
4924 if (SynthesizePID) {
4925 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4926 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00004927 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004928 }
4929
4930 // FIXME: OBJCGC: weak & strong
4931}
4932
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004933/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00004934/// Another legacy compatibility encoding: 32-bit longs are encoded as
4935/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004936/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4937///
4938void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00004939 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00004940 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00004941 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004942 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00004943 else
Jay Foad39c79802011-01-12 09:06:06 +00004944 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004945 PointeeTy = IntTy;
4946 }
4947 }
4948}
4949
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004950void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00004951 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004952 // We follow the behavior of gcc, expanding structures which are
4953 // directly pointed to, and expanding embedded structures. Note that
4954 // these rules are sufficient to prevent recursive encoding of the
4955 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00004956 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00004957 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004958}
4959
John McCall393a78d2012-12-20 02:45:14 +00004960static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
4961 BuiltinType::Kind kind) {
4962 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00004963 case BuiltinType::Void: return 'v';
4964 case BuiltinType::Bool: return 'B';
4965 case BuiltinType::Char_U:
4966 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00004967 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00004968 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00004969 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00004970 case BuiltinType::UInt: return 'I';
4971 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00004972 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004973 case BuiltinType::UInt128: return 'T';
4974 case BuiltinType::ULongLong: return 'Q';
4975 case BuiltinType::Char_S:
4976 case BuiltinType::SChar: return 'c';
4977 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00004978 case BuiltinType::WChar_S:
4979 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00004980 case BuiltinType::Int: return 'i';
4981 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00004982 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004983 case BuiltinType::LongLong: return 'q';
4984 case BuiltinType::Int128: return 't';
4985 case BuiltinType::Float: return 'f';
4986 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00004987 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00004988 case BuiltinType::NullPtr: return '*'; // like char*
4989
4990 case BuiltinType::Half:
4991 // FIXME: potentially need @encodes for these!
4992 return ' ';
4993
4994 case BuiltinType::ObjCId:
4995 case BuiltinType::ObjCClass:
4996 case BuiltinType::ObjCSel:
4997 llvm_unreachable("@encoding ObjC primitive type");
4998
4999 // OpenCL and placeholder types don't need @encodings.
5000 case BuiltinType::OCLImage1d:
5001 case BuiltinType::OCLImage1dArray:
5002 case BuiltinType::OCLImage1dBuffer:
5003 case BuiltinType::OCLImage2d:
5004 case BuiltinType::OCLImage2dArray:
5005 case BuiltinType::OCLImage3d:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005006 case BuiltinType::OCLEvent:
Guy Benyei61054192013-02-07 10:55:47 +00005007 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00005008 case BuiltinType::Dependent:
5009#define BUILTIN_TYPE(KIND, ID)
5010#define PLACEHOLDER_TYPE(KIND, ID) \
5011 case BuiltinType::KIND:
5012#include "clang/AST/BuiltinTypes.def"
5013 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00005014 }
David Blaikie5a6a0202013-01-09 17:48:41 +00005015 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00005016}
5017
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005018static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5019 EnumDecl *Enum = ET->getDecl();
5020
5021 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5022 if (!Enum->isFixed())
5023 return 'i';
5024
5025 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00005026 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5027 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005028}
5029
Jay Foad39c79802011-01-12 09:06:06 +00005030static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00005031 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00005032 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005033 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00005034 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5035 // The GNU runtime requires more information; bitfields are encoded as b,
5036 // then the offset (in bits) of the first element, then the type of the
5037 // bitfield, then the size in bits. For example, in this structure:
5038 //
5039 // struct
5040 // {
5041 // int integer;
5042 // int flags:2;
5043 // };
5044 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5045 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5046 // information is not especially sensible, but we're stuck with it for
5047 // compatibility with GCC, although providing it breaks anything that
5048 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00005049 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005050 const RecordDecl *RD = FD->getParent();
5051 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00005052 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005053 if (const EnumType *ET = T->getAs<EnumType>())
5054 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00005055 else {
5056 const BuiltinType *BT = T->castAs<BuiltinType>();
5057 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5058 }
David Chisnallb190a2c2010-06-04 01:10:52 +00005059 }
Richard Smithcaf33902011-10-10 18:28:20 +00005060 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005061}
5062
Daniel Dunbar07d07852009-10-18 21:17:35 +00005063// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005064void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5065 bool ExpandPointedToStructures,
5066 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00005067 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005068 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005069 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005070 bool StructField,
5071 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005072 bool EncodeClassNames,
5073 bool EncodePointerToObjCTypedef) const {
John McCall393a78d2012-12-20 02:45:14 +00005074 CanQualType CT = getCanonicalType(T);
5075 switch (CT->getTypeClass()) {
5076 case Type::Builtin:
5077 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00005078 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00005079 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00005080 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5081 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5082 else
5083 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00005084 return;
Mike Stump11289f42009-09-09 15:08:12 +00005085
John McCall393a78d2012-12-20 02:45:14 +00005086 case Type::Complex: {
5087 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00005088 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00005089 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00005090 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005091 return;
5092 }
John McCall393a78d2012-12-20 02:45:14 +00005093
5094 case Type::Atomic: {
5095 const AtomicType *AT = T->castAs<AtomicType>();
5096 S += 'A';
5097 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, 0,
5098 false, false);
5099 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00005100 }
John McCall393a78d2012-12-20 02:45:14 +00005101
5102 // encoding for pointer or reference types.
5103 case Type::Pointer:
5104 case Type::LValueReference:
5105 case Type::RValueReference: {
5106 QualType PointeeTy;
5107 if (isa<PointerType>(CT)) {
5108 const PointerType *PT = T->castAs<PointerType>();
5109 if (PT->isObjCSelType()) {
5110 S += ':';
5111 return;
5112 }
5113 PointeeTy = PT->getPointeeType();
5114 } else {
5115 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5116 }
5117
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005118 bool isReadOnly = false;
5119 // For historical/compatibility reasons, the read-only qualifier of the
5120 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5121 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00005122 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00005123 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005124 if (OutermostType && T.isConstQualified()) {
5125 isReadOnly = true;
5126 S += 'r';
5127 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00005128 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005129 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005130 while (P->getAs<PointerType>())
5131 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005132 if (P.isConstQualified()) {
5133 isReadOnly = true;
5134 S += 'r';
5135 }
5136 }
5137 if (isReadOnly) {
5138 // Another legacy compatibility encoding. Some ObjC qualifier and type
5139 // combinations need to be rearranged.
5140 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005141 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00005142 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005143 }
Mike Stump11289f42009-09-09 15:08:12 +00005144
Anders Carlssond8499822007-10-29 05:01:08 +00005145 if (PointeeTy->isCharType()) {
5146 // char pointer types should be encoded as '*' unless it is a
5147 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00005148 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00005149 S += '*';
5150 return;
5151 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005152 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00005153 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5154 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5155 S += '#';
5156 return;
5157 }
5158 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5159 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5160 S += '@';
5161 return;
5162 }
5163 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00005164 }
Anders Carlssond8499822007-10-29 05:01:08 +00005165 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005166 getLegacyIntegralTypeEncoding(PointeeTy);
5167
Mike Stump11289f42009-09-09 15:08:12 +00005168 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005169 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005170 return;
5171 }
John McCall393a78d2012-12-20 02:45:14 +00005172
5173 case Type::ConstantArray:
5174 case Type::IncompleteArray:
5175 case Type::VariableArray: {
5176 const ArrayType *AT = cast<ArrayType>(CT);
5177
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005178 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005179 // Incomplete arrays are encoded as a pointer to the array element.
5180 S += '^';
5181
Mike Stump11289f42009-09-09 15:08:12 +00005182 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005183 false, ExpandStructures, FD);
5184 } else {
5185 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00005186
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005187 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
5188 if (getTypeSize(CAT->getElementType()) == 0)
5189 S += '0';
5190 else
5191 S += llvm::utostr(CAT->getSize().getZExtValue());
5192 } else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005193 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005194 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5195 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00005196 S += '0';
5197 }
Mike Stump11289f42009-09-09 15:08:12 +00005198
5199 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005200 false, ExpandStructures, FD);
5201 S += ']';
5202 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005203 return;
5204 }
Mike Stump11289f42009-09-09 15:08:12 +00005205
John McCall393a78d2012-12-20 02:45:14 +00005206 case Type::FunctionNoProto:
5207 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00005208 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005209 return;
Mike Stump11289f42009-09-09 15:08:12 +00005210
John McCall393a78d2012-12-20 02:45:14 +00005211 case Type::Record: {
5212 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005213 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00005214 // Anonymous structures print as '?'
5215 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5216 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005217 if (ClassTemplateSpecializationDecl *Spec
5218 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5219 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00005220 llvm::raw_string_ostream OS(S);
5221 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005222 TemplateArgs.data(),
5223 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00005224 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005225 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00005226 } else {
5227 S += '?';
5228 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00005229 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005230 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005231 if (!RDecl->isUnion()) {
5232 getObjCEncodingForStructureImpl(RDecl, S, FD);
5233 } else {
5234 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5235 FieldEnd = RDecl->field_end();
5236 Field != FieldEnd; ++Field) {
5237 if (FD) {
5238 S += '"';
5239 S += Field->getNameAsString();
5240 S += '"';
5241 }
Mike Stump11289f42009-09-09 15:08:12 +00005242
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005243 // Special case bit-fields.
5244 if (Field->isBitField()) {
5245 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie40ed2972012-06-06 20:45:41 +00005246 *Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005247 } else {
5248 QualType qt = Field->getType();
5249 getLegacyIntegralTypeEncoding(qt);
5250 getObjCEncodingForTypeImpl(qt, S, false, true,
5251 FD, /*OutermostType*/false,
5252 /*EncodingProperty*/false,
5253 /*StructField*/true);
5254 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005255 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005256 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00005257 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005258 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005259 return;
5260 }
Mike Stump11289f42009-09-09 15:08:12 +00005261
John McCall393a78d2012-12-20 02:45:14 +00005262 case Type::BlockPointer: {
5263 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00005264 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005265 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00005266 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005267
5268 S += '<';
5269 // Block return type
5270 getObjCEncodingForTypeImpl(FT->getResultType(), S,
5271 ExpandPointedToStructures, ExpandStructures,
5272 FD,
5273 false /* OutermostType */,
5274 EncodingProperty,
5275 false /* StructField */,
5276 EncodeBlockParameters,
5277 EncodeClassNames);
5278 // Block self
5279 S += "@?";
5280 // Block parameters
5281 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
5282 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
5283 E = FPT->arg_type_end(); I && (I != E); ++I) {
5284 getObjCEncodingForTypeImpl(*I, S,
5285 ExpandPointedToStructures,
5286 ExpandStructures,
5287 FD,
5288 false /* OutermostType */,
5289 EncodingProperty,
5290 false /* StructField */,
5291 EncodeBlockParameters,
5292 EncodeClassNames);
5293 }
5294 }
5295 S += '>';
5296 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005297 return;
5298 }
Mike Stump11289f42009-09-09 15:08:12 +00005299
John McCall393a78d2012-12-20 02:45:14 +00005300 case Type::ObjCObject:
5301 case Type::ObjCInterface: {
5302 // Ignore protocol qualifiers when mangling at this level.
5303 T = T->castAs<ObjCObjectType>()->getBaseType();
John McCall8b07ec22010-05-15 11:32:37 +00005304
John McCall393a78d2012-12-20 02:45:14 +00005305 // The assumption seems to be that this assert will succeed
5306 // because nested levels will have filtered out 'id' and 'Class'.
5307 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005308 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00005309 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005310 S += '{';
5311 const IdentifierInfo *II = OI->getIdentifier();
5312 S += II->getName();
5313 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005314 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005315 DeepCollectObjCIvars(OI, true, Ivars);
5316 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005317 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005318 if (Field->isBitField())
5319 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005320 else
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005321 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5322 false, false, false, false, false,
5323 EncodePointerToObjCTypedef);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005324 }
5325 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005326 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005327 }
Mike Stump11289f42009-09-09 15:08:12 +00005328
John McCall393a78d2012-12-20 02:45:14 +00005329 case Type::ObjCObjectPointer: {
5330 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005331 if (OPT->isObjCIdType()) {
5332 S += '@';
5333 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005334 }
Mike Stump11289f42009-09-09 15:08:12 +00005335
Steve Narofff0c86112009-10-28 22:03:49 +00005336 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5337 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5338 // Since this is a binary compatibility issue, need to consult with runtime
5339 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005340 S += '#';
5341 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005342 }
Mike Stump11289f42009-09-09 15:08:12 +00005343
Chris Lattnere7cabb92009-07-13 00:10:46 +00005344 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005345 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005346 ExpandPointedToStructures,
5347 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005348 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005349 // Note that we do extended encoding of protocol qualifer list
5350 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005351 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00005352 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5353 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005354 S += '<';
5355 S += (*I)->getNameAsString();
5356 S += '>';
5357 }
5358 S += '"';
5359 }
5360 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005361 }
Mike Stump11289f42009-09-09 15:08:12 +00005362
Chris Lattnere7cabb92009-07-13 00:10:46 +00005363 QualType PointeeTy = OPT->getPointeeType();
5364 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005365 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5366 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005367 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005368 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005369 // {...};
5370 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00005371 getObjCEncodingForTypeImpl(PointeeTy, S,
5372 false, ExpandPointedToStructures,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005373 NULL,
5374 false, false, false, false, false,
5375 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005376 return;
5377 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005378
5379 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005380 if (OPT->getInterfaceDecl() &&
5381 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005382 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00005383 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00005384 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5385 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005386 S += '<';
5387 S += (*I)->getNameAsString();
5388 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005389 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005390 S += '"';
5391 }
5392 return;
5393 }
Mike Stump11289f42009-09-09 15:08:12 +00005394
John McCalla9e6e8d2010-05-17 23:56:34 +00005395 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00005396 // FIXME: we shoul do better than that. 'M' is available.
5397 case Type::MemberPointer:
John McCalla9e6e8d2010-05-17 23:56:34 +00005398 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005399
John McCall393a78d2012-12-20 02:45:14 +00005400 case Type::Vector:
5401 case Type::ExtVector:
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005402 // This matches gcc's encoding, even though technically it is
5403 // insufficient.
5404 // FIXME. We should do a better job than gcc.
5405 return;
John McCall393a78d2012-12-20 02:45:14 +00005406
Richard Smith27d807c2013-04-30 13:56:41 +00005407 case Type::Auto:
5408 // We could see an undeduced auto type here during error recovery.
5409 // Just ignore it.
5410 return;
5411
John McCall393a78d2012-12-20 02:45:14 +00005412#define ABSTRACT_TYPE(KIND, BASE)
5413#define TYPE(KIND, BASE)
5414#define DEPENDENT_TYPE(KIND, BASE) \
5415 case Type::KIND:
5416#define NON_CANONICAL_TYPE(KIND, BASE) \
5417 case Type::KIND:
5418#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5419 case Type::KIND:
5420#include "clang/AST/TypeNodes.def"
5421 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005422 }
John McCall393a78d2012-12-20 02:45:14 +00005423 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00005424}
5425
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005426void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5427 std::string &S,
5428 const FieldDecl *FD,
5429 bool includeVBases) const {
5430 assert(RDecl && "Expected non-null RecordDecl");
5431 assert(!RDecl->isUnion() && "Should not be called for unions");
5432 if (!RDecl->getDefinition())
5433 return;
5434
5435 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5436 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5437 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5438
5439 if (CXXRec) {
5440 for (CXXRecordDecl::base_class_iterator
5441 BI = CXXRec->bases_begin(),
5442 BE = CXXRec->bases_end(); BI != BE; ++BI) {
5443 if (!BI->isVirtual()) {
5444 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005445 if (base->isEmpty())
5446 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005447 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005448 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5449 std::make_pair(offs, base));
5450 }
5451 }
5452 }
5453
5454 unsigned i = 0;
5455 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5456 FieldEnd = RDecl->field_end();
5457 Field != FieldEnd; ++Field, ++i) {
5458 uint64_t offs = layout.getFieldOffset(i);
5459 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie40ed2972012-06-06 20:45:41 +00005460 std::make_pair(offs, *Field));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005461 }
5462
5463 if (CXXRec && includeVBases) {
5464 for (CXXRecordDecl::base_class_iterator
5465 BI = CXXRec->vbases_begin(),
5466 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
5467 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005468 if (base->isEmpty())
5469 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005470 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00005471 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
5472 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5473 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005474 }
5475 }
5476
5477 CharUnits size;
5478 if (CXXRec) {
5479 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5480 } else {
5481 size = layout.getSize();
5482 }
5483
5484 uint64_t CurOffs = 0;
5485 std::multimap<uint64_t, NamedDecl *>::iterator
5486 CurLayObj = FieldOrBaseOffsets.begin();
5487
Douglas Gregorf5d6c742012-04-27 22:30:01 +00005488 if (CXXRec && CXXRec->isDynamicClass() &&
5489 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005490 if (FD) {
5491 S += "\"_vptr$";
5492 std::string recname = CXXRec->getNameAsString();
5493 if (recname.empty()) recname = "?";
5494 S += recname;
5495 S += '"';
5496 }
5497 S += "^^?";
5498 CurOffs += getTypeSize(VoidPtrTy);
5499 }
5500
5501 if (!RDecl->hasFlexibleArrayMember()) {
5502 // Mark the end of the structure.
5503 uint64_t offs = toBits(size);
5504 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5505 std::make_pair(offs, (NamedDecl*)0));
5506 }
5507
5508 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5509 assert(CurOffs <= CurLayObj->first);
5510
5511 if (CurOffs < CurLayObj->first) {
5512 uint64_t padding = CurLayObj->first - CurOffs;
5513 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5514 // packing/alignment of members is different that normal, in which case
5515 // the encoding will be out-of-sync with the real layout.
5516 // If the runtime switches to just consider the size of types without
5517 // taking into account alignment, we could make padding explicit in the
5518 // encoding (e.g. using arrays of chars). The encoding strings would be
5519 // longer then though.
5520 CurOffs += padding;
5521 }
5522
5523 NamedDecl *dcl = CurLayObj->second;
5524 if (dcl == 0)
5525 break; // reached end of structure.
5526
5527 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5528 // We expand the bases without their virtual bases since those are going
5529 // in the initial structure. Note that this differs from gcc which
5530 // expands virtual bases each time one is encountered in the hierarchy,
5531 // making the encoding type bigger than it really is.
5532 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005533 assert(!base->isEmpty());
5534 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005535 } else {
5536 FieldDecl *field = cast<FieldDecl>(dcl);
5537 if (FD) {
5538 S += '"';
5539 S += field->getNameAsString();
5540 S += '"';
5541 }
5542
5543 if (field->isBitField()) {
5544 EncodeBitField(this, S, field->getType(), field);
Richard Smithcaf33902011-10-10 18:28:20 +00005545 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005546 } else {
5547 QualType qt = field->getType();
5548 getLegacyIntegralTypeEncoding(qt);
5549 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5550 /*OutermostType*/false,
5551 /*EncodingProperty*/false,
5552 /*StructField*/true);
5553 CurOffs += getTypeSize(field->getType());
5554 }
5555 }
5556 }
5557}
5558
Mike Stump11289f42009-09-09 15:08:12 +00005559void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005560 std::string& S) const {
5561 if (QT & Decl::OBJC_TQ_In)
5562 S += 'n';
5563 if (QT & Decl::OBJC_TQ_Inout)
5564 S += 'N';
5565 if (QT & Decl::OBJC_TQ_Out)
5566 S += 'o';
5567 if (QT & Decl::OBJC_TQ_Bycopy)
5568 S += 'O';
5569 if (QT & Decl::OBJC_TQ_Byref)
5570 S += 'R';
5571 if (QT & Decl::OBJC_TQ_Oneway)
5572 S += 'V';
5573}
5574
Douglas Gregor3ea72692011-08-12 05:46:01 +00005575TypedefDecl *ASTContext::getObjCIdDecl() const {
5576 if (!ObjCIdDecl) {
5577 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5578 T = getObjCObjectPointerType(T);
5579 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
5580 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5581 getTranslationUnitDecl(),
5582 SourceLocation(), SourceLocation(),
5583 &Idents.get("id"), IdInfo);
5584 }
5585
5586 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00005587}
5588
Douglas Gregor52e02802011-08-12 06:17:30 +00005589TypedefDecl *ASTContext::getObjCSelDecl() const {
5590 if (!ObjCSelDecl) {
5591 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5592 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5593 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5594 getTranslationUnitDecl(),
5595 SourceLocation(), SourceLocation(),
5596 &Idents.get("SEL"), SelInfo);
5597 }
5598 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00005599}
5600
Douglas Gregor0a586182011-08-12 05:59:41 +00005601TypedefDecl *ASTContext::getObjCClassDecl() const {
5602 if (!ObjCClassDecl) {
5603 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5604 T = getObjCObjectPointerType(T);
5605 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5606 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5607 getTranslationUnitDecl(),
5608 SourceLocation(), SourceLocation(),
5609 &Idents.get("Class"), ClassInfo);
5610 }
5611
5612 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00005613}
5614
Douglas Gregord53ae832012-01-17 18:09:05 +00005615ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5616 if (!ObjCProtocolClassDecl) {
5617 ObjCProtocolClassDecl
5618 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5619 SourceLocation(),
5620 &Idents.get("Protocol"),
5621 /*PrevDecl=*/0,
5622 SourceLocation(), true);
5623 }
5624
5625 return ObjCProtocolClassDecl;
5626}
5627
Meador Inge5d3fb222012-06-16 03:34:49 +00005628//===----------------------------------------------------------------------===//
5629// __builtin_va_list Construction Functions
5630//===----------------------------------------------------------------------===//
5631
5632static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5633 // typedef char* __builtin_va_list;
5634 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5635 TypeSourceInfo *TInfo
5636 = Context->getTrivialTypeSourceInfo(CharPtrType);
5637
5638 TypedefDecl *VaListTypeDecl
5639 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5640 Context->getTranslationUnitDecl(),
5641 SourceLocation(), SourceLocation(),
5642 &Context->Idents.get("__builtin_va_list"),
5643 TInfo);
5644 return VaListTypeDecl;
5645}
5646
5647static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5648 // typedef void* __builtin_va_list;
5649 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5650 TypeSourceInfo *TInfo
5651 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5652
5653 TypedefDecl *VaListTypeDecl
5654 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5655 Context->getTranslationUnitDecl(),
5656 SourceLocation(), SourceLocation(),
5657 &Context->Idents.get("__builtin_va_list"),
5658 TInfo);
5659 return VaListTypeDecl;
5660}
5661
Tim Northover9bb857a2013-01-31 12:13:10 +00005662static TypedefDecl *
5663CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
5664 RecordDecl *VaListTagDecl;
5665 if (Context->getLangOpts().CPlusPlus) {
5666 // namespace std { struct __va_list {
5667 NamespaceDecl *NS;
5668 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5669 Context->getTranslationUnitDecl(),
5670 /*Inline*/false, SourceLocation(),
5671 SourceLocation(), &Context->Idents.get("std"),
5672 /*PrevDecl*/0);
5673
5674 VaListTagDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5675 Context->getTranslationUnitDecl(),
5676 SourceLocation(), SourceLocation(),
5677 &Context->Idents.get("__va_list"));
5678 VaListTagDecl->setDeclContext(NS);
5679 } else {
5680 // struct __va_list
5681 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5682 Context->getTranslationUnitDecl(),
5683 &Context->Idents.get("__va_list"));
5684 }
5685
5686 VaListTagDecl->startDefinition();
5687
5688 const size_t NumFields = 5;
5689 QualType FieldTypes[NumFields];
5690 const char *FieldNames[NumFields];
5691
5692 // void *__stack;
5693 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
5694 FieldNames[0] = "__stack";
5695
5696 // void *__gr_top;
5697 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
5698 FieldNames[1] = "__gr_top";
5699
5700 // void *__vr_top;
5701 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5702 FieldNames[2] = "__vr_top";
5703
5704 // int __gr_offs;
5705 FieldTypes[3] = Context->IntTy;
5706 FieldNames[3] = "__gr_offs";
5707
5708 // int __vr_offs;
5709 FieldTypes[4] = Context->IntTy;
5710 FieldNames[4] = "__vr_offs";
5711
5712 // Create fields
5713 for (unsigned i = 0; i < NumFields; ++i) {
5714 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5715 VaListTagDecl,
5716 SourceLocation(),
5717 SourceLocation(),
5718 &Context->Idents.get(FieldNames[i]),
5719 FieldTypes[i], /*TInfo=*/0,
5720 /*BitWidth=*/0,
5721 /*Mutable=*/false,
5722 ICIS_NoInit);
5723 Field->setAccess(AS_public);
5724 VaListTagDecl->addDecl(Field);
5725 }
5726 VaListTagDecl->completeDefinition();
5727 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5728 Context->VaListTagTy = VaListTagType;
5729
5730 // } __builtin_va_list;
5731 TypedefDecl *VaListTypedefDecl
5732 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5733 Context->getTranslationUnitDecl(),
5734 SourceLocation(), SourceLocation(),
5735 &Context->Idents.get("__builtin_va_list"),
5736 Context->getTrivialTypeSourceInfo(VaListTagType));
5737
5738 return VaListTypedefDecl;
5739}
5740
Meador Inge5d3fb222012-06-16 03:34:49 +00005741static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5742 // typedef struct __va_list_tag {
5743 RecordDecl *VaListTagDecl;
5744
5745 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5746 Context->getTranslationUnitDecl(),
5747 &Context->Idents.get("__va_list_tag"));
5748 VaListTagDecl->startDefinition();
5749
5750 const size_t NumFields = 5;
5751 QualType FieldTypes[NumFields];
5752 const char *FieldNames[NumFields];
5753
5754 // unsigned char gpr;
5755 FieldTypes[0] = Context->UnsignedCharTy;
5756 FieldNames[0] = "gpr";
5757
5758 // unsigned char fpr;
5759 FieldTypes[1] = Context->UnsignedCharTy;
5760 FieldNames[1] = "fpr";
5761
5762 // unsigned short reserved;
5763 FieldTypes[2] = Context->UnsignedShortTy;
5764 FieldNames[2] = "reserved";
5765
5766 // void* overflow_arg_area;
5767 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5768 FieldNames[3] = "overflow_arg_area";
5769
5770 // void* reg_save_area;
5771 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5772 FieldNames[4] = "reg_save_area";
5773
5774 // Create fields
5775 for (unsigned i = 0; i < NumFields; ++i) {
5776 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5777 SourceLocation(),
5778 SourceLocation(),
5779 &Context->Idents.get(FieldNames[i]),
5780 FieldTypes[i], /*TInfo=*/0,
5781 /*BitWidth=*/0,
5782 /*Mutable=*/false,
5783 ICIS_NoInit);
5784 Field->setAccess(AS_public);
5785 VaListTagDecl->addDecl(Field);
5786 }
5787 VaListTagDecl->completeDefinition();
5788 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005789 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005790
5791 // } __va_list_tag;
5792 TypedefDecl *VaListTagTypedefDecl
5793 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5794 Context->getTranslationUnitDecl(),
5795 SourceLocation(), SourceLocation(),
5796 &Context->Idents.get("__va_list_tag"),
5797 Context->getTrivialTypeSourceInfo(VaListTagType));
5798 QualType VaListTagTypedefType =
5799 Context->getTypedefType(VaListTagTypedefDecl);
5800
5801 // typedef __va_list_tag __builtin_va_list[1];
5802 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5803 QualType VaListTagArrayType
5804 = Context->getConstantArrayType(VaListTagTypedefType,
5805 Size, ArrayType::Normal, 0);
5806 TypeSourceInfo *TInfo
5807 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5808 TypedefDecl *VaListTypedefDecl
5809 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5810 Context->getTranslationUnitDecl(),
5811 SourceLocation(), SourceLocation(),
5812 &Context->Idents.get("__builtin_va_list"),
5813 TInfo);
5814
5815 return VaListTypedefDecl;
5816}
5817
5818static TypedefDecl *
5819CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5820 // typedef struct __va_list_tag {
5821 RecordDecl *VaListTagDecl;
5822 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5823 Context->getTranslationUnitDecl(),
5824 &Context->Idents.get("__va_list_tag"));
5825 VaListTagDecl->startDefinition();
5826
5827 const size_t NumFields = 4;
5828 QualType FieldTypes[NumFields];
5829 const char *FieldNames[NumFields];
5830
5831 // unsigned gp_offset;
5832 FieldTypes[0] = Context->UnsignedIntTy;
5833 FieldNames[0] = "gp_offset";
5834
5835 // unsigned fp_offset;
5836 FieldTypes[1] = Context->UnsignedIntTy;
5837 FieldNames[1] = "fp_offset";
5838
5839 // void* overflow_arg_area;
5840 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5841 FieldNames[2] = "overflow_arg_area";
5842
5843 // void* reg_save_area;
5844 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5845 FieldNames[3] = "reg_save_area";
5846
5847 // Create fields
5848 for (unsigned i = 0; i < NumFields; ++i) {
5849 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5850 VaListTagDecl,
5851 SourceLocation(),
5852 SourceLocation(),
5853 &Context->Idents.get(FieldNames[i]),
5854 FieldTypes[i], /*TInfo=*/0,
5855 /*BitWidth=*/0,
5856 /*Mutable=*/false,
5857 ICIS_NoInit);
5858 Field->setAccess(AS_public);
5859 VaListTagDecl->addDecl(Field);
5860 }
5861 VaListTagDecl->completeDefinition();
5862 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005863 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005864
5865 // } __va_list_tag;
5866 TypedefDecl *VaListTagTypedefDecl
5867 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5868 Context->getTranslationUnitDecl(),
5869 SourceLocation(), SourceLocation(),
5870 &Context->Idents.get("__va_list_tag"),
5871 Context->getTrivialTypeSourceInfo(VaListTagType));
5872 QualType VaListTagTypedefType =
5873 Context->getTypedefType(VaListTagTypedefDecl);
5874
5875 // typedef __va_list_tag __builtin_va_list[1];
5876 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5877 QualType VaListTagArrayType
5878 = Context->getConstantArrayType(VaListTagTypedefType,
5879 Size, ArrayType::Normal,0);
5880 TypeSourceInfo *TInfo
5881 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5882 TypedefDecl *VaListTypedefDecl
5883 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5884 Context->getTranslationUnitDecl(),
5885 SourceLocation(), SourceLocation(),
5886 &Context->Idents.get("__builtin_va_list"),
5887 TInfo);
5888
5889 return VaListTypedefDecl;
5890}
5891
5892static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5893 // typedef int __builtin_va_list[4];
5894 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5895 QualType IntArrayType
5896 = Context->getConstantArrayType(Context->IntTy,
5897 Size, ArrayType::Normal, 0);
5898 TypedefDecl *VaListTypedefDecl
5899 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5900 Context->getTranslationUnitDecl(),
5901 SourceLocation(), SourceLocation(),
5902 &Context->Idents.get("__builtin_va_list"),
5903 Context->getTrivialTypeSourceInfo(IntArrayType));
5904
5905 return VaListTypedefDecl;
5906}
5907
Logan Chien57086ce2012-10-10 06:56:20 +00005908static TypedefDecl *
5909CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
5910 RecordDecl *VaListDecl;
5911 if (Context->getLangOpts().CPlusPlus) {
5912 // namespace std { struct __va_list {
5913 NamespaceDecl *NS;
5914 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5915 Context->getTranslationUnitDecl(),
5916 /*Inline*/false, SourceLocation(),
5917 SourceLocation(), &Context->Idents.get("std"),
5918 /*PrevDecl*/0);
5919
5920 VaListDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5921 Context->getTranslationUnitDecl(),
5922 SourceLocation(), SourceLocation(),
5923 &Context->Idents.get("__va_list"));
5924
5925 VaListDecl->setDeclContext(NS);
5926
5927 } else {
5928 // struct __va_list {
5929 VaListDecl = CreateRecordDecl(*Context, TTK_Struct,
5930 Context->getTranslationUnitDecl(),
5931 &Context->Idents.get("__va_list"));
5932 }
5933
5934 VaListDecl->startDefinition();
5935
5936 // void * __ap;
5937 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5938 VaListDecl,
5939 SourceLocation(),
5940 SourceLocation(),
5941 &Context->Idents.get("__ap"),
5942 Context->getPointerType(Context->VoidTy),
5943 /*TInfo=*/0,
5944 /*BitWidth=*/0,
5945 /*Mutable=*/false,
5946 ICIS_NoInit);
5947 Field->setAccess(AS_public);
5948 VaListDecl->addDecl(Field);
5949
5950 // };
5951 VaListDecl->completeDefinition();
5952
5953 // typedef struct __va_list __builtin_va_list;
5954 TypeSourceInfo *TInfo
5955 = Context->getTrivialTypeSourceInfo(Context->getRecordType(VaListDecl));
5956
5957 TypedefDecl *VaListTypeDecl
5958 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5959 Context->getTranslationUnitDecl(),
5960 SourceLocation(), SourceLocation(),
5961 &Context->Idents.get("__builtin_va_list"),
5962 TInfo);
5963
5964 return VaListTypeDecl;
5965}
5966
Meador Inge5d3fb222012-06-16 03:34:49 +00005967static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
5968 TargetInfo::BuiltinVaListKind Kind) {
5969 switch (Kind) {
5970 case TargetInfo::CharPtrBuiltinVaList:
5971 return CreateCharPtrBuiltinVaListDecl(Context);
5972 case TargetInfo::VoidPtrBuiltinVaList:
5973 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00005974 case TargetInfo::AArch64ABIBuiltinVaList:
5975 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00005976 case TargetInfo::PowerABIBuiltinVaList:
5977 return CreatePowerABIBuiltinVaListDecl(Context);
5978 case TargetInfo::X86_64ABIBuiltinVaList:
5979 return CreateX86_64ABIBuiltinVaListDecl(Context);
5980 case TargetInfo::PNaClABIBuiltinVaList:
5981 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00005982 case TargetInfo::AAPCSABIBuiltinVaList:
5983 return CreateAAPCSABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00005984 }
5985
5986 llvm_unreachable("Unhandled __builtin_va_list type kind");
5987}
5988
5989TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
5990 if (!BuiltinVaListDecl)
5991 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
5992
5993 return BuiltinVaListDecl;
5994}
5995
Meador Ingecfb60902012-07-01 15:57:25 +00005996QualType ASTContext::getVaListTagType() const {
5997 // Force the creation of VaListTagTy by building the __builtin_va_list
5998 // declaration.
5999 if (VaListTagTy.isNull())
6000 (void) getBuiltinVaListDecl();
6001
6002 return VaListTagTy;
6003}
6004
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006005void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00006006 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00006007 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00006008
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006009 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00006010}
6011
John McCalld28ae272009-12-02 08:04:21 +00006012/// \brief Retrieve the template name that corresponds to a non-empty
6013/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00006014TemplateName
6015ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6016 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00006017 unsigned size = End - Begin;
6018 assert(size > 1 && "set is not overloaded!");
6019
6020 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6021 size * sizeof(FunctionTemplateDecl*));
6022 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6023
6024 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00006025 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00006026 NamedDecl *D = *I;
6027 assert(isa<FunctionTemplateDecl>(D) ||
6028 (isa<UsingShadowDecl>(D) &&
6029 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6030 *Storage++ = D;
6031 }
6032
6033 return TemplateName(OT);
6034}
6035
Douglas Gregordc572a32009-03-30 22:58:21 +00006036/// \brief Retrieve the template name that represents a qualified
6037/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00006038TemplateName
6039ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6040 bool TemplateKeyword,
6041 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00006042 assert(NNS && "Missing nested-name-specifier in qualified template name");
6043
Douglas Gregorc42075a2010-02-04 18:10:26 +00006044 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00006045 llvm::FoldingSetNodeID ID;
6046 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6047
6048 void *InsertPos = 0;
6049 QualifiedTemplateName *QTN =
6050 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6051 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00006052 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6053 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00006054 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6055 }
6056
6057 return TemplateName(QTN);
6058}
6059
6060/// \brief Retrieve the template name that represents a dependent
6061/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00006062TemplateName
6063ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6064 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00006065 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00006066 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00006067
6068 llvm::FoldingSetNodeID ID;
6069 DependentTemplateName::Profile(ID, NNS, Name);
6070
6071 void *InsertPos = 0;
6072 DependentTemplateName *QTN =
6073 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6074
6075 if (QTN)
6076 return TemplateName(QTN);
6077
6078 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6079 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006080 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6081 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00006082 } else {
6083 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00006084 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6085 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006086 DependentTemplateName *CheckQTN =
6087 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6088 assert(!CheckQTN && "Dependent type name canonicalization broken");
6089 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00006090 }
6091
6092 DependentTemplateNames.InsertNode(QTN, InsertPos);
6093 return TemplateName(QTN);
6094}
6095
Douglas Gregor71395fa2009-11-04 00:56:37 +00006096/// \brief Retrieve the template name that represents a dependent
6097/// template name such as \c MetaFun::template operator+.
6098TemplateName
6099ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00006100 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00006101 assert((!NNS || NNS->isDependent()) &&
6102 "Nested name specifier must be dependent");
6103
6104 llvm::FoldingSetNodeID ID;
6105 DependentTemplateName::Profile(ID, NNS, Operator);
6106
6107 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00006108 DependentTemplateName *QTN
6109 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006110
6111 if (QTN)
6112 return TemplateName(QTN);
6113
6114 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6115 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006116 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6117 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006118 } else {
6119 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00006120 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6121 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006122
6123 DependentTemplateName *CheckQTN
6124 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6125 assert(!CheckQTN && "Dependent template name canonicalization broken");
6126 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00006127 }
6128
6129 DependentTemplateNames.InsertNode(QTN, InsertPos);
6130 return TemplateName(QTN);
6131}
6132
Douglas Gregor5590be02011-01-15 06:45:20 +00006133TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00006134ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6135 TemplateName replacement) const {
6136 llvm::FoldingSetNodeID ID;
6137 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
6138
6139 void *insertPos = 0;
6140 SubstTemplateTemplateParmStorage *subst
6141 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6142
6143 if (!subst) {
6144 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6145 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6146 }
6147
6148 return TemplateName(subst);
6149}
6150
6151TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00006152ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6153 const TemplateArgument &ArgPack) const {
6154 ASTContext &Self = const_cast<ASTContext &>(*this);
6155 llvm::FoldingSetNodeID ID;
6156 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
6157
6158 void *InsertPos = 0;
6159 SubstTemplateTemplateParmPackStorage *Subst
6160 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6161
6162 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00006163 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00006164 ArgPack.pack_size(),
6165 ArgPack.pack_begin());
6166 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6167 }
6168
6169 return TemplateName(Subst);
6170}
6171
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006172/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00006173/// TargetInfo, produce the corresponding type. The unsigned @p Type
6174/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00006175CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006176 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00006177 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006178 case TargetInfo::SignedShort: return ShortTy;
6179 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6180 case TargetInfo::SignedInt: return IntTy;
6181 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6182 case TargetInfo::SignedLong: return LongTy;
6183 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6184 case TargetInfo::SignedLongLong: return LongLongTy;
6185 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6186 }
6187
David Blaikie83d382b2011-09-23 05:06:16 +00006188 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006189}
Ted Kremenek77c51b22008-07-24 23:58:27 +00006190
6191//===----------------------------------------------------------------------===//
6192// Type Predicates.
6193//===----------------------------------------------------------------------===//
6194
Fariborz Jahanian96207692009-02-18 21:49:28 +00006195/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6196/// garbage collection attribute.
6197///
John McCall553d45a2011-01-12 00:34:59 +00006198Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006199 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00006200 return Qualifiers::GCNone;
6201
David Blaikiebbafb8a2012-03-11 07:00:24 +00006202 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00006203 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6204
6205 // Default behaviour under objective-C's gc is for ObjC pointers
6206 // (or pointers to them) be treated as though they were declared
6207 // as __strong.
6208 if (GCAttrs == Qualifiers::GCNone) {
6209 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6210 return Qualifiers::Strong;
6211 else if (Ty->isPointerType())
6212 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6213 } else {
6214 // It's not valid to set GC attributes on anything that isn't a
6215 // pointer.
6216#ifndef NDEBUG
6217 QualType CT = Ty->getCanonicalTypeInternal();
6218 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6219 CT = AT->getElementType();
6220 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6221#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00006222 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00006223 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00006224}
6225
Chris Lattner49af6a42008-04-07 06:51:04 +00006226//===----------------------------------------------------------------------===//
6227// Type Compatibility Testing
6228//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00006229
Mike Stump11289f42009-09-09 15:08:12 +00006230/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006231/// compatible.
6232static bool areCompatVectorTypes(const VectorType *LHS,
6233 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00006234 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00006235 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00006236 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00006237}
6238
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006239bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6240 QualType SecondVec) {
6241 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6242 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6243
6244 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6245 return true;
6246
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006247 // Treat Neon vector types and most AltiVec vector types as if they are the
6248 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006249 const VectorType *First = FirstVec->getAs<VectorType>();
6250 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006251 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006252 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006253 First->getVectorKind() != VectorType::AltiVecPixel &&
6254 First->getVectorKind() != VectorType::AltiVecBool &&
6255 Second->getVectorKind() != VectorType::AltiVecPixel &&
6256 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006257 return true;
6258
6259 return false;
6260}
6261
Steve Naroff8e6aee52009-07-23 01:01:38 +00006262//===----------------------------------------------------------------------===//
6263// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6264//===----------------------------------------------------------------------===//
6265
6266/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6267/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00006268bool
6269ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6270 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00006271 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006272 return true;
6273 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
6274 E = rProto->protocol_end(); PI != E; ++PI)
6275 if (ProtocolCompatibleWithProtocol(lProto, *PI))
6276 return true;
6277 return false;
6278}
6279
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006280/// QualifiedIdConformsQualifiedId - compare id<pr,...> with id<pr1,...>
Steve Naroff8e6aee52009-07-23 01:01:38 +00006281/// return true if lhs's protocols conform to rhs's protocol; false
6282/// otherwise.
6283bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
6284 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
6285 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
6286 return false;
6287}
6288
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006289/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6290/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006291bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6292 QualType rhs) {
6293 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6294 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6295 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6296
6297 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6298 E = lhsQID->qual_end(); I != E; ++I) {
6299 bool match = false;
6300 ObjCProtocolDecl *lhsProto = *I;
6301 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6302 E = rhsOPT->qual_end(); J != E; ++J) {
6303 ObjCProtocolDecl *rhsProto = *J;
6304 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6305 match = true;
6306 break;
6307 }
6308 }
6309 if (!match)
6310 return false;
6311 }
6312 return true;
6313}
6314
Steve Naroff8e6aee52009-07-23 01:01:38 +00006315/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6316/// ObjCQualifiedIDType.
6317bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6318 bool compare) {
6319 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00006320 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006321 lhs->isObjCIdType() || lhs->isObjCClassType())
6322 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006323 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006324 rhs->isObjCIdType() || rhs->isObjCClassType())
6325 return true;
6326
6327 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00006328 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006329
Steve Naroff8e6aee52009-07-23 01:01:38 +00006330 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00006331
Steve Naroff8e6aee52009-07-23 01:01:38 +00006332 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00006333 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006334 // make sure we check the class hierarchy.
6335 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6336 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6337 E = lhsQID->qual_end(); I != E; ++I) {
6338 // when comparing an id<P> on lhs with a static type on rhs,
6339 // see if static class implements all of id's protocols, directly or
6340 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00006341 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006342 return false;
6343 }
6344 }
6345 // If there are no qualifiers and no interface, we have an 'id'.
6346 return true;
6347 }
Mike Stump11289f42009-09-09 15:08:12 +00006348 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006349 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6350 E = lhsQID->qual_end(); I != E; ++I) {
6351 ObjCProtocolDecl *lhsProto = *I;
6352 bool match = false;
6353
6354 // when comparing an id<P> on lhs with a static type on rhs,
6355 // see if static class implements all of id's protocols, directly or
6356 // through its super class and categories.
6357 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6358 E = rhsOPT->qual_end(); J != E; ++J) {
6359 ObjCProtocolDecl *rhsProto = *J;
6360 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6361 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6362 match = true;
6363 break;
6364 }
6365 }
Mike Stump11289f42009-09-09 15:08:12 +00006366 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006367 // make sure we check the class hierarchy.
6368 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6369 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6370 E = lhsQID->qual_end(); I != E; ++I) {
6371 // when comparing an id<P> on lhs with a static type on rhs,
6372 // see if static class implements all of id's protocols, directly or
6373 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00006374 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006375 match = true;
6376 break;
6377 }
6378 }
6379 }
6380 if (!match)
6381 return false;
6382 }
Mike Stump11289f42009-09-09 15:08:12 +00006383
Steve Naroff8e6aee52009-07-23 01:01:38 +00006384 return true;
6385 }
Mike Stump11289f42009-09-09 15:08:12 +00006386
Steve Naroff8e6aee52009-07-23 01:01:38 +00006387 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6388 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6389
Mike Stump11289f42009-09-09 15:08:12 +00006390 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00006391 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006392 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006393 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
6394 E = lhsOPT->qual_end(); I != E; ++I) {
6395 ObjCProtocolDecl *lhsProto = *I;
6396 bool match = false;
6397
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006398 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00006399 // see if static class implements all of id's protocols, directly or
6400 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006401 // First, lhs protocols in the qualifier list must be found, direct
6402 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006403 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6404 E = rhsQID->qual_end(); J != E; ++J) {
6405 ObjCProtocolDecl *rhsProto = *J;
6406 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6407 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6408 match = true;
6409 break;
6410 }
6411 }
6412 if (!match)
6413 return false;
6414 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006415
6416 // Static class's protocols, or its super class or category protocols
6417 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6418 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6419 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6420 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6421 // This is rather dubious but matches gcc's behavior. If lhs has
6422 // no type qualifier and its class has no static protocol(s)
6423 // assume that it is mismatch.
6424 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6425 return false;
6426 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6427 LHSInheritedProtocols.begin(),
6428 E = LHSInheritedProtocols.end(); I != E; ++I) {
6429 bool match = false;
6430 ObjCProtocolDecl *lhsProto = (*I);
6431 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6432 E = rhsQID->qual_end(); J != E; ++J) {
6433 ObjCProtocolDecl *rhsProto = *J;
6434 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6435 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6436 match = true;
6437 break;
6438 }
6439 }
6440 if (!match)
6441 return false;
6442 }
6443 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00006444 return true;
6445 }
6446 return false;
6447}
6448
Eli Friedman47f77112008-08-22 00:56:42 +00006449/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006450/// compatible for assignment from RHS to LHS. This handles validation of any
6451/// protocol qualifiers on the LHS or RHS.
6452///
Steve Naroff7cae42b2009-07-10 23:34:53 +00006453bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6454 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00006455 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6456 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6457
Steve Naroff1329fa02009-07-15 18:40:39 +00006458 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00006459 if (LHS->isObjCUnqualifiedIdOrClass() ||
6460 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00006461 return true;
6462
John McCall8b07ec22010-05-15 11:32:37 +00006463 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00006464 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6465 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00006466 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006467
6468 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6469 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6470 QualType(RHSOPT,0));
6471
John McCall8b07ec22010-05-15 11:32:37 +00006472 // If we have 2 user-defined types, fall into that path.
6473 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00006474 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006475
Steve Naroff8e6aee52009-07-23 01:01:38 +00006476 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006477}
6478
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006479/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00006480/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006481/// arguments in block literals. When passed as arguments, passing 'A*' where
6482/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6483/// not OK. For the return type, the opposite is not OK.
6484bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6485 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006486 const ObjCObjectPointerType *RHSOPT,
6487 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006488 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006489 return true;
6490
6491 if (LHSOPT->isObjCBuiltinType()) {
6492 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6493 }
6494
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006495 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006496 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6497 QualType(RHSOPT,0),
6498 false);
6499
6500 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6501 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6502 if (LHS && RHS) { // We have 2 user-defined types.
6503 if (LHS != RHS) {
6504 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006505 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006506 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006507 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006508 }
6509 else
6510 return true;
6511 }
6512 return false;
6513}
6514
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006515/// getIntersectionOfProtocols - This routine finds the intersection of set
6516/// of protocols inherited from two distinct objective-c pointer objects.
6517/// It is used to build composite qualifier list of the composite type of
6518/// the conditional expression involving two objective-c pointer objects.
6519static
6520void getIntersectionOfProtocols(ASTContext &Context,
6521 const ObjCObjectPointerType *LHSOPT,
6522 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006523 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006524
John McCall8b07ec22010-05-15 11:32:37 +00006525 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6526 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6527 assert(LHS->getInterface() && "LHS must have an interface base");
6528 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006529
6530 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6531 unsigned LHSNumProtocols = LHS->getNumProtocols();
6532 if (LHSNumProtocols > 0)
6533 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6534 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006535 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006536 Context.CollectInheritedProtocols(LHS->getInterface(),
6537 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006538 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6539 LHSInheritedProtocols.end());
6540 }
6541
6542 unsigned RHSNumProtocols = RHS->getNumProtocols();
6543 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00006544 ObjCProtocolDecl **RHSProtocols =
6545 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006546 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6547 if (InheritedProtocolSet.count(RHSProtocols[i]))
6548 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00006549 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006550 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006551 Context.CollectInheritedProtocols(RHS->getInterface(),
6552 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006553 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6554 RHSInheritedProtocols.begin(),
6555 E = RHSInheritedProtocols.end(); I != E; ++I)
6556 if (InheritedProtocolSet.count((*I)))
6557 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006558 }
6559}
6560
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006561/// areCommonBaseCompatible - Returns common base class of the two classes if
6562/// one found. Note that this is O'2 algorithm. But it will be called as the
6563/// last type comparison in a ?-exp of ObjC pointer types before a
6564/// warning is issued. So, its invokation is extremely rare.
6565QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00006566 const ObjCObjectPointerType *Lptr,
6567 const ObjCObjectPointerType *Rptr) {
6568 const ObjCObjectType *LHS = Lptr->getObjectType();
6569 const ObjCObjectType *RHS = Rptr->getObjectType();
6570 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6571 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00006572 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006573 return QualType();
6574
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006575 do {
John McCall8b07ec22010-05-15 11:32:37 +00006576 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006577 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006578 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00006579 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6580
6581 QualType Result = QualType(LHS, 0);
6582 if (!Protocols.empty())
6583 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6584 Result = getObjCObjectPointerType(Result);
6585 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006586 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006587 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006588
6589 return QualType();
6590}
6591
John McCall8b07ec22010-05-15 11:32:37 +00006592bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6593 const ObjCObjectType *RHS) {
6594 assert(LHS->getInterface() && "LHS is not an interface type");
6595 assert(RHS->getInterface() && "RHS is not an interface type");
6596
Chris Lattner49af6a42008-04-07 06:51:04 +00006597 // Verify that the base decls are compatible: the RHS must be a subclass of
6598 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00006599 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00006600 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006601
Chris Lattner49af6a42008-04-07 06:51:04 +00006602 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6603 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00006604 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00006605 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006606
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006607 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6608 // more detailed analysis is required.
6609 if (RHS->getNumProtocols() == 0) {
6610 // OK, if LHS is a superclass of RHS *and*
6611 // this superclass is assignment compatible with LHS.
6612 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006613 bool IsSuperClass =
6614 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6615 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006616 // OK if conversion of LHS to SuperClass results in narrowing of types
6617 // ; i.e., SuperClass may implement at least one of the protocols
6618 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6619 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6620 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006621 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006622 // If super class has no protocols, it is not a match.
6623 if (SuperClassInheritedProtocols.empty())
6624 return false;
6625
6626 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6627 LHSPE = LHS->qual_end();
6628 LHSPI != LHSPE; LHSPI++) {
6629 bool SuperImplementsProtocol = false;
6630 ObjCProtocolDecl *LHSProto = (*LHSPI);
6631
6632 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6633 SuperClassInheritedProtocols.begin(),
6634 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6635 ObjCProtocolDecl *SuperClassProto = (*I);
6636 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6637 SuperImplementsProtocol = true;
6638 break;
6639 }
6640 }
6641 if (!SuperImplementsProtocol)
6642 return false;
6643 }
6644 return true;
6645 }
6646 return false;
6647 }
Mike Stump11289f42009-09-09 15:08:12 +00006648
John McCall8b07ec22010-05-15 11:32:37 +00006649 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6650 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00006651 LHSPI != LHSPE; LHSPI++) {
6652 bool RHSImplementsProtocol = false;
6653
6654 // If the RHS doesn't implement the protocol on the left, the types
6655 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00006656 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6657 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00006658 RHSPI != RHSPE; RHSPI++) {
6659 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00006660 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00006661 break;
6662 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006663 }
6664 // FIXME: For better diagnostics, consider passing back the protocol name.
6665 if (!RHSImplementsProtocol)
6666 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00006667 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006668 // The RHS implements all protocols listed on the LHS.
6669 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00006670}
6671
Steve Naroffb7605152009-02-12 17:52:19 +00006672bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6673 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00006674 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6675 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006676
Steve Naroff7cae42b2009-07-10 23:34:53 +00006677 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00006678 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006679
6680 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6681 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00006682}
6683
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006684bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6685 return canAssignObjCInterfaces(
6686 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6687 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6688}
6689
Mike Stump11289f42009-09-09 15:08:12 +00006690/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00006691/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00006692/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00006693/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006694bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6695 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006696 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00006697 return hasSameType(LHS, RHS);
6698
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006699 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00006700}
6701
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006702bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00006703 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006704}
6705
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006706bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6707 return !mergeTypes(LHS, RHS, true).isNull();
6708}
6709
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006710/// mergeTransparentUnionType - if T is a transparent union type and a member
6711/// of T is compatible with SubType, return the merged type, else return
6712/// QualType()
6713QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6714 bool OfBlockPointer,
6715 bool Unqualified) {
6716 if (const RecordType *UT = T->getAsUnionType()) {
6717 RecordDecl *UD = UT->getDecl();
6718 if (UD->hasAttr<TransparentUnionAttr>()) {
6719 for (RecordDecl::field_iterator it = UD->field_begin(),
6720 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00006721 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006722 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6723 if (!MT.isNull())
6724 return MT;
6725 }
6726 }
6727 }
6728
6729 return QualType();
6730}
6731
6732/// mergeFunctionArgumentTypes - merge two types which appear as function
6733/// argument types
6734QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
6735 bool OfBlockPointer,
6736 bool Unqualified) {
6737 // GNU extension: two types are compatible if they appear as a function
6738 // argument, one of the types is a transparent union type and the other
6739 // type is compatible with a union member
6740 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6741 Unqualified);
6742 if (!lmerge.isNull())
6743 return lmerge;
6744
6745 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6746 Unqualified);
6747 if (!rmerge.isNull())
6748 return rmerge;
6749
6750 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6751}
6752
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006753QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006754 bool OfBlockPointer,
6755 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00006756 const FunctionType *lbase = lhs->getAs<FunctionType>();
6757 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006758 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6759 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00006760 bool allLTypes = true;
6761 bool allRTypes = true;
6762
6763 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006764 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00006765 if (OfBlockPointer) {
6766 QualType RHS = rbase->getResultType();
6767 QualType LHS = lbase->getResultType();
6768 bool UnqualifiedResult = Unqualified;
6769 if (!UnqualifiedResult)
6770 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006771 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00006772 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006773 else
John McCall8c6b56f2010-12-15 01:06:38 +00006774 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6775 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006776 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006777
6778 if (Unqualified)
6779 retType = retType.getUnqualifiedType();
6780
6781 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6782 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6783 if (Unqualified) {
6784 LRetType = LRetType.getUnqualifiedType();
6785 RRetType = RRetType.getUnqualifiedType();
6786 }
6787
6788 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006789 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006790 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006791 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006792
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00006793 // FIXME: double check this
6794 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6795 // rbase->getRegParmAttr() != 0 &&
6796 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00006797 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6798 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00006799
Douglas Gregor8c940862010-01-18 17:14:39 +00006800 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00006801 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00006802 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006803
John McCall8c6b56f2010-12-15 01:06:38 +00006804 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00006805 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6806 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00006807 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6808 return QualType();
6809
John McCall31168b02011-06-15 23:02:42 +00006810 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6811 return QualType();
6812
John McCall8c6b56f2010-12-15 01:06:38 +00006813 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6814 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00006815
Rafael Espindola8778c282012-11-29 16:09:03 +00006816 if (lbaseInfo.getNoReturn() != NoReturn)
6817 allLTypes = false;
6818 if (rbaseInfo.getNoReturn() != NoReturn)
6819 allRTypes = false;
6820
John McCall31168b02011-06-15 23:02:42 +00006821 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00006822
Eli Friedman47f77112008-08-22 00:56:42 +00006823 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006824 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6825 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006826 unsigned lproto_nargs = lproto->getNumArgs();
6827 unsigned rproto_nargs = rproto->getNumArgs();
6828
6829 // Compatible functions must have the same number of arguments
6830 if (lproto_nargs != rproto_nargs)
6831 return QualType();
6832
6833 // Variadic and non-variadic functions aren't compatible
6834 if (lproto->isVariadic() != rproto->isVariadic())
6835 return QualType();
6836
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00006837 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6838 return QualType();
6839
Fariborz Jahanian97676972011-09-28 21:52:05 +00006840 if (LangOpts.ObjCAutoRefCount &&
6841 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6842 return QualType();
6843
Eli Friedman47f77112008-08-22 00:56:42 +00006844 // Check argument compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006845 SmallVector<QualType, 10> types;
Eli Friedman47f77112008-08-22 00:56:42 +00006846 for (unsigned i = 0; i < lproto_nargs; i++) {
6847 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
6848 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006849 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
6850 OfBlockPointer,
6851 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006852 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006853
6854 if (Unqualified)
6855 argtype = argtype.getUnqualifiedType();
6856
Eli Friedman47f77112008-08-22 00:56:42 +00006857 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006858 if (Unqualified) {
6859 largtype = largtype.getUnqualifiedType();
6860 rargtype = rargtype.getUnqualifiedType();
6861 }
6862
Chris Lattner465fa322008-10-05 17:34:18 +00006863 if (getCanonicalType(argtype) != getCanonicalType(largtype))
6864 allLTypes = false;
6865 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
6866 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00006867 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00006868
Eli Friedman47f77112008-08-22 00:56:42 +00006869 if (allLTypes) return lhs;
6870 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006871
6872 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
6873 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00006874 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006875 }
6876
6877 if (lproto) allRTypes = false;
6878 if (rproto) allLTypes = false;
6879
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006880 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00006881 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006882 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006883 if (proto->isVariadic()) return QualType();
6884 // Check that the types are compatible with the types that
6885 // would result from default argument promotions (C99 6.7.5.3p15).
6886 // The only types actually affected are promotable integer
6887 // types and floats, which would be passed as a different
6888 // type depending on whether the prototype is visible.
6889 unsigned proto_nargs = proto->getNumArgs();
6890 for (unsigned i = 0; i < proto_nargs; ++i) {
6891 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00006892
Eli Friedman448ce402012-08-30 00:44:15 +00006893 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00006894 // to pass enum values.
Eli Friedman448ce402012-08-30 00:44:15 +00006895 if (const EnumType *Enum = argTy->getAs<EnumType>()) {
6896 argTy = Enum->getDecl()->getIntegerType();
6897 if (argTy.isNull())
6898 return QualType();
6899 }
Douglas Gregor2973d402010-02-03 19:27:29 +00006900
Eli Friedman47f77112008-08-22 00:56:42 +00006901 if (argTy->isPromotableIntegerType() ||
6902 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
6903 return QualType();
6904 }
6905
6906 if (allLTypes) return lhs;
6907 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006908
6909 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
6910 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00006911 return getFunctionType(retType,
6912 ArrayRef<QualType>(proto->arg_type_begin(),
6913 proto->getNumArgs()),
6914 EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006915 }
6916
6917 if (allLTypes) return lhs;
6918 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00006919 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00006920}
6921
John McCall433c2e62013-03-21 00:10:07 +00006922/// Given that we have an enum type and a non-enum type, try to merge them.
6923static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
6924 QualType other, bool isBlockReturnType) {
6925 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
6926 // a signed integer type, or an unsigned integer type.
6927 // Compatibility is based on the underlying type, not the promotion
6928 // type.
6929 QualType underlyingType = ET->getDecl()->getIntegerType();
6930 if (underlyingType.isNull()) return QualType();
6931 if (Context.hasSameType(underlyingType, other))
6932 return other;
6933
6934 // In block return types, we're more permissive and accept any
6935 // integral type of the same size.
6936 if (isBlockReturnType && other->isIntegerType() &&
6937 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
6938 return other;
6939
6940 return QualType();
6941}
6942
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006943QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006944 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006945 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00006946 // C++ [expr]: If an expression initially has the type "reference to T", the
6947 // type is adjusted to "T" prior to any further analysis, the expression
6948 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006949 // expression is an lvalue unless the reference is an rvalue reference and
6950 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00006951 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
6952 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006953
6954 if (Unqualified) {
6955 LHS = LHS.getUnqualifiedType();
6956 RHS = RHS.getUnqualifiedType();
6957 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00006958
Eli Friedman47f77112008-08-22 00:56:42 +00006959 QualType LHSCan = getCanonicalType(LHS),
6960 RHSCan = getCanonicalType(RHS);
6961
6962 // If two types are identical, they are compatible.
6963 if (LHSCan == RHSCan)
6964 return LHS;
6965
John McCall8ccfcb52009-09-24 19:53:00 +00006966 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006967 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6968 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00006969 if (LQuals != RQuals) {
6970 // If any of these qualifiers are different, we have a type
6971 // mismatch.
6972 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00006973 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
6974 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00006975 return QualType();
6976
6977 // Exactly one GC qualifier difference is allowed: __strong is
6978 // okay if the other type has no GC qualifier but is an Objective
6979 // C object pointer (i.e. implicitly strong by default). We fix
6980 // this by pretending that the unqualified type was actually
6981 // qualified __strong.
6982 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6983 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6984 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6985
6986 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6987 return QualType();
6988
6989 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
6990 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
6991 }
6992 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
6993 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
6994 }
Eli Friedman47f77112008-08-22 00:56:42 +00006995 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00006996 }
6997
6998 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00006999
Eli Friedmandcca6332009-06-01 01:22:52 +00007000 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7001 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00007002
Chris Lattnerfd652912008-01-14 05:45:46 +00007003 // We want to consider the two function types to be the same for these
7004 // comparisons, just force one to the other.
7005 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7006 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00007007
7008 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00007009 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7010 LHSClass = Type::ConstantArray;
7011 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7012 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00007013
John McCall8b07ec22010-05-15 11:32:37 +00007014 // ObjCInterfaces are just specialized ObjCObjects.
7015 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7016 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7017
Nate Begemance4d7fc2008-04-18 23:10:10 +00007018 // Canonicalize ExtVector -> Vector.
7019 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7020 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00007021
Chris Lattner95554662008-04-07 05:43:21 +00007022 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007023 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00007024 // Note that we only have special rules for turning block enum
7025 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00007026 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007027 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007028 }
John McCall9dd450b2009-09-21 23:43:11 +00007029 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007030 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007031 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007032 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00007033 if (OfBlockPointer && !BlockReturnType) {
7034 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7035 return LHS;
7036 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7037 return RHS;
7038 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007039
Eli Friedman47f77112008-08-22 00:56:42 +00007040 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00007041 }
Eli Friedman47f77112008-08-22 00:56:42 +00007042
Steve Naroffc6edcbd2008-01-09 22:43:08 +00007043 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007044 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007045#define TYPE(Class, Base)
7046#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00007047#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007048#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7049#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7050#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00007051 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007052
Richard Smith27d807c2013-04-30 13:56:41 +00007053 case Type::Auto:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007054 case Type::LValueReference:
7055 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007056 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00007057 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007058
John McCall8b07ec22010-05-15 11:32:37 +00007059 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007060 case Type::IncompleteArray:
7061 case Type::VariableArray:
7062 case Type::FunctionProto:
7063 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00007064 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007065
Chris Lattnerfd652912008-01-14 05:45:46 +00007066 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00007067 {
7068 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007069 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7070 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007071 if (Unqualified) {
7072 LHSPointee = LHSPointee.getUnqualifiedType();
7073 RHSPointee = RHSPointee.getUnqualifiedType();
7074 }
7075 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7076 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007077 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00007078 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007079 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00007080 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007081 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007082 return getPointerType(ResultType);
7083 }
Steve Naroff68e167d2008-12-10 17:49:55 +00007084 case Type::BlockPointer:
7085 {
7086 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007087 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7088 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007089 if (Unqualified) {
7090 LHSPointee = LHSPointee.getUnqualifiedType();
7091 RHSPointee = RHSPointee.getUnqualifiedType();
7092 }
7093 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7094 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00007095 if (ResultType.isNull()) return QualType();
7096 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7097 return LHS;
7098 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7099 return RHS;
7100 return getBlockPointerType(ResultType);
7101 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00007102 case Type::Atomic:
7103 {
7104 // Merge two pointer types, while trying to preserve typedef info
7105 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7106 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7107 if (Unqualified) {
7108 LHSValue = LHSValue.getUnqualifiedType();
7109 RHSValue = RHSValue.getUnqualifiedType();
7110 }
7111 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7112 Unqualified);
7113 if (ResultType.isNull()) return QualType();
7114 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7115 return LHS;
7116 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7117 return RHS;
7118 return getAtomicType(ResultType);
7119 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007120 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00007121 {
7122 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7123 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7124 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7125 return QualType();
7126
7127 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7128 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007129 if (Unqualified) {
7130 LHSElem = LHSElem.getUnqualifiedType();
7131 RHSElem = RHSElem.getUnqualifiedType();
7132 }
7133
7134 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007135 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00007136 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7137 return LHS;
7138 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7139 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00007140 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7141 ArrayType::ArraySizeModifier(), 0);
7142 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7143 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007144 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7145 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00007146 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7147 return LHS;
7148 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7149 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007150 if (LVAT) {
7151 // FIXME: This isn't correct! But tricky to implement because
7152 // the array's size has to be the size of LHS, but the type
7153 // has to be different.
7154 return LHS;
7155 }
7156 if (RVAT) {
7157 // FIXME: This isn't correct! But tricky to implement because
7158 // the array's size has to be the size of RHS, but the type
7159 // has to be different.
7160 return RHS;
7161 }
Eli Friedman3e62c212008-08-22 01:48:21 +00007162 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7163 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00007164 return getIncompleteArrayType(ResultType,
7165 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007166 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007167 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007168 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007169 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007170 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00007171 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00007172 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007173 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00007174 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00007175 case Type::Complex:
7176 // Distinct complex types are incompatible.
7177 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007178 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00007179 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00007180 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7181 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00007182 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00007183 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00007184 case Type::ObjCObject: {
7185 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00007186 // FIXME: This should be type compatibility, e.g. whether
7187 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00007188 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7189 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7190 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00007191 return LHS;
7192
Eli Friedman47f77112008-08-22 00:56:42 +00007193 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00007194 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007195 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007196 if (OfBlockPointer) {
7197 if (canAssignObjCInterfacesInBlockPointer(
7198 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007199 RHS->getAs<ObjCObjectPointerType>(),
7200 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00007201 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007202 return QualType();
7203 }
John McCall9dd450b2009-09-21 23:43:11 +00007204 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7205 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007206 return LHS;
7207
Steve Naroffc68cfcf2008-12-10 22:14:21 +00007208 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00007209 }
Steve Naroff32e44c02007-10-15 20:41:53 +00007210 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007211
David Blaikie8a40f702012-01-17 06:56:22 +00007212 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00007213}
Ted Kremenekfc581a92007-10-31 17:10:13 +00007214
Fariborz Jahanian97676972011-09-28 21:52:05 +00007215bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7216 const FunctionProtoType *FromFunctionType,
7217 const FunctionProtoType *ToFunctionType) {
7218 if (FromFunctionType->hasAnyConsumedArgs() !=
7219 ToFunctionType->hasAnyConsumedArgs())
7220 return false;
7221 FunctionProtoType::ExtProtoInfo FromEPI =
7222 FromFunctionType->getExtProtoInfo();
7223 FunctionProtoType::ExtProtoInfo ToEPI =
7224 ToFunctionType->getExtProtoInfo();
7225 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
7226 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
7227 ArgIdx != NumArgs; ++ArgIdx) {
7228 if (FromEPI.ConsumedArguments[ArgIdx] !=
7229 ToEPI.ConsumedArguments[ArgIdx])
7230 return false;
7231 }
7232 return true;
7233}
7234
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007235/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7236/// 'RHS' attributes and returns the merged version; including for function
7237/// return types.
7238QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7239 QualType LHSCan = getCanonicalType(LHS),
7240 RHSCan = getCanonicalType(RHS);
7241 // If two types are identical, they are compatible.
7242 if (LHSCan == RHSCan)
7243 return LHS;
7244 if (RHSCan->isFunctionType()) {
7245 if (!LHSCan->isFunctionType())
7246 return QualType();
7247 QualType OldReturnType =
7248 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
7249 QualType NewReturnType =
7250 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
7251 QualType ResReturnType =
7252 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7253 if (ResReturnType.isNull())
7254 return QualType();
7255 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7256 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7257 // In either case, use OldReturnType to build the new function type.
7258 const FunctionType *F = LHS->getAs<FunctionType>();
7259 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00007260 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7261 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007262 QualType ResultType
Jordan Rose5c382722013-03-08 21:51:21 +00007263 = getFunctionType(OldReturnType,
7264 ArrayRef<QualType>(FPT->arg_type_begin(),
7265 FPT->getNumArgs()),
7266 EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007267 return ResultType;
7268 }
7269 }
7270 return QualType();
7271 }
7272
7273 // If the qualifiers are different, the types can still be merged.
7274 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7275 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7276 if (LQuals != RQuals) {
7277 // If any of these qualifiers are different, we have a type mismatch.
7278 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7279 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7280 return QualType();
7281
7282 // Exactly one GC qualifier difference is allowed: __strong is
7283 // okay if the other type has no GC qualifier but is an Objective
7284 // C object pointer (i.e. implicitly strong by default). We fix
7285 // this by pretending that the unqualified type was actually
7286 // qualified __strong.
7287 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7288 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7289 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7290
7291 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7292 return QualType();
7293
7294 if (GC_L == Qualifiers::Strong)
7295 return LHS;
7296 if (GC_R == Qualifiers::Strong)
7297 return RHS;
7298 return QualType();
7299 }
7300
7301 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7302 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7303 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7304 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7305 if (ResQT == LHSBaseQT)
7306 return LHS;
7307 if (ResQT == RHSBaseQT)
7308 return RHS;
7309 }
7310 return QualType();
7311}
7312
Chris Lattner4ba0cef2008-04-07 07:01:58 +00007313//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007314// Integer Predicates
7315//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00007316
Jay Foad39c79802011-01-12 09:06:06 +00007317unsigned ASTContext::getIntWidth(QualType T) const {
John McCall424cec92011-01-19 06:33:43 +00007318 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00007319 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00007320 if (T->isBooleanType())
7321 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00007322 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007323 return (unsigned)getTypeSize(T);
7324}
7325
Abramo Bagnara13640492012-09-09 10:21:24 +00007326QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007327 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00007328
7329 // Turn <4 x signed int> -> <4 x unsigned int>
7330 if (const VectorType *VTy = T->getAs<VectorType>())
7331 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00007332 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00007333
7334 // For enums, we return the unsigned version of the base type.
7335 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007336 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00007337
7338 const BuiltinType *BTy = T->getAs<BuiltinType>();
7339 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007340 switch (BTy->getKind()) {
7341 case BuiltinType::Char_S:
7342 case BuiltinType::SChar:
7343 return UnsignedCharTy;
7344 case BuiltinType::Short:
7345 return UnsignedShortTy;
7346 case BuiltinType::Int:
7347 return UnsignedIntTy;
7348 case BuiltinType::Long:
7349 return UnsignedLongTy;
7350 case BuiltinType::LongLong:
7351 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00007352 case BuiltinType::Int128:
7353 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007354 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007355 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007356 }
7357}
7358
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00007359ASTMutationListener::~ASTMutationListener() { }
7360
Chris Lattnerecd79c62009-06-14 00:45:47 +00007361
7362//===----------------------------------------------------------------------===//
7363// Builtin Type Computation
7364//===----------------------------------------------------------------------===//
7365
7366/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00007367/// pointer over the consumed characters. This returns the resultant type. If
7368/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7369/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7370/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007371///
7372/// RequiresICE is filled in on return to indicate whether the value is required
7373/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00007374static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00007375 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007376 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00007377 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00007378 // Modifiers.
7379 int HowLong = 0;
7380 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007381 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00007382
Chris Lattnerdc226c22010-10-01 22:42:38 +00007383 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00007384 bool Done = false;
7385 while (!Done) {
7386 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00007387 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00007388 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007389 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00007390 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007391 case 'S':
7392 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7393 assert(!Signed && "Can't use 'S' modifier multiple times!");
7394 Signed = true;
7395 break;
7396 case 'U':
7397 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7398 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7399 Unsigned = true;
7400 break;
7401 case 'L':
7402 assert(HowLong <= 2 && "Can't have LLLL modifier");
7403 ++HowLong;
7404 break;
7405 }
7406 }
7407
7408 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00007409
Chris Lattnerecd79c62009-06-14 00:45:47 +00007410 // Read the base type.
7411 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00007412 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007413 case 'v':
7414 assert(HowLong == 0 && !Signed && !Unsigned &&
7415 "Bad modifiers used with 'v'!");
7416 Type = Context.VoidTy;
7417 break;
7418 case 'f':
7419 assert(HowLong == 0 && !Signed && !Unsigned &&
7420 "Bad modifiers used with 'f'!");
7421 Type = Context.FloatTy;
7422 break;
7423 case 'd':
7424 assert(HowLong < 2 && !Signed && !Unsigned &&
7425 "Bad modifiers used with 'd'!");
7426 if (HowLong)
7427 Type = Context.LongDoubleTy;
7428 else
7429 Type = Context.DoubleTy;
7430 break;
7431 case 's':
7432 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7433 if (Unsigned)
7434 Type = Context.UnsignedShortTy;
7435 else
7436 Type = Context.ShortTy;
7437 break;
7438 case 'i':
7439 if (HowLong == 3)
7440 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7441 else if (HowLong == 2)
7442 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7443 else if (HowLong == 1)
7444 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7445 else
7446 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7447 break;
7448 case 'c':
7449 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7450 if (Signed)
7451 Type = Context.SignedCharTy;
7452 else if (Unsigned)
7453 Type = Context.UnsignedCharTy;
7454 else
7455 Type = Context.CharTy;
7456 break;
7457 case 'b': // boolean
7458 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7459 Type = Context.BoolTy;
7460 break;
7461 case 'z': // size_t.
7462 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7463 Type = Context.getSizeType();
7464 break;
7465 case 'F':
7466 Type = Context.getCFConstantStringType();
7467 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00007468 case 'G':
7469 Type = Context.getObjCIdType();
7470 break;
7471 case 'H':
7472 Type = Context.getObjCSelType();
7473 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00007474 case 'M':
7475 Type = Context.getObjCSuperType();
7476 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007477 case 'a':
7478 Type = Context.getBuiltinVaListType();
7479 assert(!Type.isNull() && "builtin va list type not initialized!");
7480 break;
7481 case 'A':
7482 // This is a "reference" to a va_list; however, what exactly
7483 // this means depends on how va_list is defined. There are two
7484 // different kinds of va_list: ones passed by value, and ones
7485 // passed by reference. An example of a by-value va_list is
7486 // x86, where va_list is a char*. An example of by-ref va_list
7487 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7488 // we want this argument to be a char*&; for x86-64, we want
7489 // it to be a __va_list_tag*.
7490 Type = Context.getBuiltinVaListType();
7491 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007492 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00007493 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007494 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00007495 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007496 break;
7497 case 'V': {
7498 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007499 unsigned NumElements = strtoul(Str, &End, 10);
7500 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007501 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00007502
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007503 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7504 RequiresICE, false);
7505 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00007506
7507 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00007508 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00007509 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007510 break;
7511 }
Douglas Gregorfed66992012-06-07 18:08:25 +00007512 case 'E': {
7513 char *End;
7514
7515 unsigned NumElements = strtoul(Str, &End, 10);
7516 assert(End != Str && "Missing vector size");
7517
7518 Str = End;
7519
7520 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7521 false);
7522 Type = Context.getExtVectorType(ElementType, NumElements);
7523 break;
7524 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007525 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007526 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7527 false);
7528 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007529 Type = Context.getComplexType(ElementType);
7530 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00007531 }
7532 case 'Y' : {
7533 Type = Context.getPointerDiffType();
7534 break;
7535 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00007536 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00007537 Type = Context.getFILEType();
7538 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007539 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007540 return QualType();
7541 }
Mike Stump2adb4da2009-07-28 23:47:15 +00007542 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00007543 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00007544 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00007545 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00007546 else
7547 Type = Context.getjmp_bufType();
7548
Mike Stump2adb4da2009-07-28 23:47:15 +00007549 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007550 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00007551 return QualType();
7552 }
7553 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00007554 case 'K':
7555 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7556 Type = Context.getucontext_tType();
7557
7558 if (Type.isNull()) {
7559 Error = ASTContext::GE_Missing_ucontext;
7560 return QualType();
7561 }
7562 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00007563 case 'p':
7564 Type = Context.getProcessIDType();
7565 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00007566 }
Mike Stump11289f42009-09-09 15:08:12 +00007567
Chris Lattnerdc226c22010-10-01 22:42:38 +00007568 // If there are modifiers and if we're allowed to parse them, go for it.
7569 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007570 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00007571 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007572 default: Done = true; --Str; break;
7573 case '*':
7574 case '&': {
7575 // Both pointers and references can have their pointee types
7576 // qualified with an address space.
7577 char *End;
7578 unsigned AddrSpace = strtoul(Str, &End, 10);
7579 if (End != Str && AddrSpace != 0) {
7580 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7581 Str = End;
7582 }
7583 if (c == '*')
7584 Type = Context.getPointerType(Type);
7585 else
7586 Type = Context.getLValueReferenceType(Type);
7587 break;
7588 }
7589 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7590 case 'C':
7591 Type = Type.withConst();
7592 break;
7593 case 'D':
7594 Type = Context.getVolatileType(Type);
7595 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00007596 case 'R':
7597 Type = Type.withRestrict();
7598 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007599 }
7600 }
Chris Lattner84733392010-10-01 07:13:18 +00007601
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007602 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00007603 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00007604
Chris Lattnerecd79c62009-06-14 00:45:47 +00007605 return Type;
7606}
7607
7608/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00007609QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007610 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00007611 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007612 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00007613
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007614 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00007615
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007616 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007617 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007618 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7619 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007620 if (Error != GE_None)
7621 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007622
7623 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7624
Chris Lattnerecd79c62009-06-14 00:45:47 +00007625 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007626 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007627 if (Error != GE_None)
7628 return QualType();
7629
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007630 // If this argument is required to be an IntegerConstantExpression and the
7631 // caller cares, fill in the bitmask we return.
7632 if (RequiresICE && IntegerConstantArgs)
7633 *IntegerConstantArgs |= 1 << ArgTypes.size();
7634
Chris Lattnerecd79c62009-06-14 00:45:47 +00007635 // Do array -> pointer decay. The builtin should use the decayed type.
7636 if (Ty->isArrayType())
7637 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00007638
Chris Lattnerecd79c62009-06-14 00:45:47 +00007639 ArgTypes.push_back(Ty);
7640 }
7641
7642 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7643 "'.' should only occur at end of builtin type list!");
7644
John McCall991eb4b2010-12-21 00:44:39 +00007645 FunctionType::ExtInfo EI;
7646 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7647
7648 bool Variadic = (TypeStr[0] == '.');
7649
7650 // We really shouldn't be making a no-proto type here, especially in C++.
7651 if (ArgTypes.empty() && Variadic)
7652 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00007653
John McCalldb40c7f2010-12-14 08:05:40 +00007654 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00007655 EPI.ExtInfo = EI;
7656 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00007657
Jordan Rose5c382722013-03-08 21:51:21 +00007658 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007659}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00007660
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007661GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
7662 GVALinkage External = GVA_StrongExternal;
7663
7664 Linkage L = FD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007665 switch (L) {
7666 case NoLinkage:
7667 case InternalLinkage:
7668 case UniqueExternalLinkage:
7669 return GVA_Internal;
7670
7671 case ExternalLinkage:
7672 switch (FD->getTemplateSpecializationKind()) {
7673 case TSK_Undeclared:
7674 case TSK_ExplicitSpecialization:
7675 External = GVA_StrongExternal;
7676 break;
7677
7678 case TSK_ExplicitInstantiationDefinition:
7679 return GVA_ExplicitTemplateInstantiation;
7680
7681 case TSK_ExplicitInstantiationDeclaration:
7682 case TSK_ImplicitInstantiation:
7683 External = GVA_TemplateInstantiation;
7684 break;
7685 }
7686 }
7687
7688 if (!FD->isInlined())
7689 return External;
7690
David Blaikiebbafb8a2012-03-11 07:00:24 +00007691 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007692 // GNU or C99 inline semantics. Determine whether this symbol should be
7693 // externally visible.
7694 if (FD->isInlineDefinitionExternallyVisible())
7695 return External;
7696
7697 // C99 inline semantics, where the symbol is not externally visible.
7698 return GVA_C99Inline;
7699 }
7700
7701 // C++0x [temp.explicit]p9:
7702 // [ Note: The intent is that an inline function that is the subject of
7703 // an explicit instantiation declaration will still be implicitly
7704 // instantiated when used so that the body can be considered for
7705 // inlining, but that no out-of-line copy of the inline function would be
7706 // generated in the translation unit. -- end note ]
7707 if (FD->getTemplateSpecializationKind()
7708 == TSK_ExplicitInstantiationDeclaration)
7709 return GVA_C99Inline;
7710
7711 return GVA_CXXInline;
7712}
7713
7714GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
7715 // If this is a static data member, compute the kind of template
7716 // specialization. Otherwise, this variable is not part of a
7717 // template.
7718 TemplateSpecializationKind TSK = TSK_Undeclared;
7719 if (VD->isStaticDataMember())
7720 TSK = VD->getTemplateSpecializationKind();
7721
7722 Linkage L = VD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007723
7724 switch (L) {
7725 case NoLinkage:
7726 case InternalLinkage:
7727 case UniqueExternalLinkage:
7728 return GVA_Internal;
7729
7730 case ExternalLinkage:
7731 switch (TSK) {
7732 case TSK_Undeclared:
7733 case TSK_ExplicitSpecialization:
7734 return GVA_StrongExternal;
7735
7736 case TSK_ExplicitInstantiationDeclaration:
7737 llvm_unreachable("Variable should not be instantiated");
7738 // Fall through to treat this like any other instantiation.
7739
7740 case TSK_ExplicitInstantiationDefinition:
7741 return GVA_ExplicitTemplateInstantiation;
7742
7743 case TSK_ImplicitInstantiation:
7744 return GVA_TemplateInstantiation;
7745 }
7746 }
7747
David Blaikie8a40f702012-01-17 06:56:22 +00007748 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007749}
7750
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00007751bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007752 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7753 if (!VD->isFileVarDecl())
7754 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00007755 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7756 // We never need to emit an uninstantiated function template.
7757 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
7758 return false;
7759 } else
7760 return false;
7761
7762 // If this is a member of a class template, we do not need to emit it.
7763 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007764 return false;
7765
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007766 // Weak references don't produce any output by themselves.
7767 if (D->hasAttr<WeakRefAttr>())
7768 return false;
7769
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007770 // Aliases and used decls are required.
7771 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7772 return true;
7773
7774 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7775 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00007776 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00007777 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007778
7779 // Constructors and destructors are required.
7780 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7781 return true;
7782
John McCall6bd2a892013-01-25 22:31:03 +00007783 // The key function for a class is required. This rule only comes
7784 // into play when inline functions can be key functions, though.
7785 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7786 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7787 const CXXRecordDecl *RD = MD->getParent();
7788 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7789 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
7790 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7791 return true;
7792 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007793 }
7794 }
7795
7796 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7797
7798 // static, static inline, always_inline, and extern inline functions can
7799 // always be deferred. Normal inline functions can be deferred in C99/C++.
7800 // Implicit template instantiations can also be deferred in C++.
7801 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev79de4d42012-02-02 06:06:34 +00007802 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007803 return false;
7804 return true;
7805 }
Douglas Gregor87d81242011-09-10 00:22:34 +00007806
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007807 const VarDecl *VD = cast<VarDecl>(D);
7808 assert(VD->isFileVarDecl() && "Expected file scoped var");
7809
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007810 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7811 return false;
7812
Richard Smitha0e5e542012-11-12 21:38:00 +00007813 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007814 GVALinkage L = GetGVALinkageForVariable(VD);
Richard Smitha0e5e542012-11-12 21:38:00 +00007815 if (L != GVA_Internal && L != GVA_TemplateInstantiation)
7816 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007817
Richard Smitha0e5e542012-11-12 21:38:00 +00007818 // Variables that have destruction with side-effects are required.
7819 if (VD->getType().isDestructedType())
7820 return true;
7821
7822 // Variables that have initialization with side-effects are required.
7823 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
7824 return true;
7825
7826 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007827}
Charles Davis53c59df2010-08-16 03:33:14 +00007828
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007829CallingConv ASTContext::getDefaultCXXMethodCallConv(bool isVariadic) {
Charles Davis99202b32010-11-09 18:04:24 +00007830 // Pass through to the C++ ABI object
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007831 return ABI->getDefaultMethodCallConv(isVariadic);
7832}
7833
7834CallingConv ASTContext::getCanonicalCallConv(CallingConv CC) const {
John McCall359b8852013-01-25 22:30:49 +00007835 if (CC == CC_C && !LangOpts.MRTD &&
7836 getTargetInfo().getCXXABI().isMemberFunctionCCDefault())
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007837 return CC_Default;
7838 return CC;
Charles Davis99202b32010-11-09 18:04:24 +00007839}
7840
Jay Foad39c79802011-01-12 09:06:06 +00007841bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00007842 // Pass through to the C++ ABI object
7843 return ABI->isNearlyEmpty(RD);
7844}
7845
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007846MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00007847 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00007848 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00007849 case TargetCXXABI::GenericItanium:
7850 case TargetCXXABI::GenericARM:
7851 case TargetCXXABI::iOS:
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007852 return createItaniumMangleContext(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00007853 case TargetCXXABI::Microsoft:
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007854 return createMicrosoftMangleContext(*this, getDiagnostics());
7855 }
David Blaikie83d382b2011-09-23 05:06:16 +00007856 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007857}
7858
Charles Davis53c59df2010-08-16 03:33:14 +00007859CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007860
7861size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek7d39c9a2011-07-27 18:41:12 +00007862 return ASTRecordLayouts.getMemorySize()
7863 + llvm::capacity_in_bytes(ObjCLayouts)
7864 + llvm::capacity_in_bytes(KeyFunctions)
7865 + llvm::capacity_in_bytes(ObjCImpls)
7866 + llvm::capacity_in_bytes(BlockVarCopyInits)
7867 + llvm::capacity_in_bytes(DeclAttrs)
7868 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
7869 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
7870 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
7871 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
7872 + llvm::capacity_in_bytes(OverriddenMethods)
7873 + llvm::capacity_in_bytes(Types)
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007874 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet57928252011-08-14 14:28:49 +00007875 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007876}
Ted Kremenek540017e2011-10-06 05:00:56 +00007877
David Blaikie095deba2012-11-14 01:52:05 +00007878void ASTContext::addUnnamedTag(const TagDecl *Tag) {
7879 // FIXME: This mangling should be applied to function local classes too
7880 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl() ||
7881 !isa<CXXRecordDecl>(Tag->getParent()) || Tag->getLinkage() != ExternalLinkage)
7882 return;
7883
7884 std::pair<llvm::DenseMap<const DeclContext *, unsigned>::iterator, bool> P =
7885 UnnamedMangleContexts.insert(std::make_pair(Tag->getParent(), 0));
7886 UnnamedMangleNumbers.insert(std::make_pair(Tag, P.first->second++));
7887}
7888
7889int ASTContext::getUnnamedTagManglingNumber(const TagDecl *Tag) const {
7890 llvm::DenseMap<const TagDecl *, unsigned>::const_iterator I =
7891 UnnamedMangleNumbers.find(Tag);
7892 return I != UnnamedMangleNumbers.end() ? I->second : -1;
7893}
7894
Douglas Gregor63798542012-02-20 19:44:39 +00007895unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
7896 CXXRecordDecl *Lambda = CallOperator->getParent();
7897 return LambdaMangleContexts[Lambda->getDeclContext()]
7898 .getManglingNumber(CallOperator);
7899}
7900
7901
Ted Kremenek540017e2011-10-06 05:00:56 +00007902void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
7903 ParamIndices[D] = index;
7904}
7905
7906unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
7907 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
7908 assert(I != ParamIndices.end() &&
7909 "ParmIndices lacks entry set by ParmVarDecl");
7910 return I->second;
7911}