blob: f9622455c0fc9a524ccafabff5cc43a7d3e87657 [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 Jahanian40abf342013-01-25 22:48:32 +0000445 else if (const TypedefDecl *TD = dyn_cast<TypedefDecl>(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 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000454 return NULL;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000455 }
456
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000457 // If the RawComment was attached to other redeclaration of this Decl, we
458 // should parse the comment in context of that other Decl. This is important
459 // because comments can contain references to parameter names which can be
460 // different across redeclarations.
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000461 if (D != OriginalDecl)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000462 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000463
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000464 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000465 ParsedComments[Canonical] = FC;
466 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000467}
468
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000469void
470ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
471 TemplateTemplateParmDecl *Parm) {
472 ID.AddInteger(Parm->getDepth());
473 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000474 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000475
476 TemplateParameterList *Params = Parm->getTemplateParameters();
477 ID.AddInteger(Params->size());
478 for (TemplateParameterList::const_iterator P = Params->begin(),
479 PEnd = Params->end();
480 P != PEnd; ++P) {
481 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
482 ID.AddInteger(0);
483 ID.AddBoolean(TTP->isParameterPack());
484 continue;
485 }
486
487 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
488 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000489 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000490 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000491 if (NTTP->isExpandedParameterPack()) {
492 ID.AddBoolean(true);
493 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000494 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
495 QualType T = NTTP->getExpansionType(I);
496 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
497 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000498 } else
499 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000500 continue;
501 }
502
503 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
504 ID.AddInteger(2);
505 Profile(ID, TTP);
506 }
507}
508
509TemplateTemplateParmDecl *
510ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000511 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000512 // Check if we already have a canonical template template parameter.
513 llvm::FoldingSetNodeID ID;
514 CanonicalTemplateTemplateParm::Profile(ID, TTP);
515 void *InsertPos = 0;
516 CanonicalTemplateTemplateParm *Canonical
517 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
518 if (Canonical)
519 return Canonical->getParam();
520
521 // Build a canonical template parameter list.
522 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000523 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000524 CanonParams.reserve(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 CanonParams.push_back(
530 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000531 SourceLocation(),
532 SourceLocation(),
533 TTP->getDepth(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000534 TTP->getIndex(), 0, false,
535 TTP->isParameterPack()));
536 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000537 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
538 QualType T = getCanonicalType(NTTP->getType());
539 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
540 NonTypeTemplateParmDecl *Param;
541 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000542 SmallVector<QualType, 2> ExpandedTypes;
543 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000544 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
545 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
546 ExpandedTInfos.push_back(
547 getTrivialTypeSourceInfo(ExpandedTypes.back()));
548 }
549
550 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000551 SourceLocation(),
552 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000553 NTTP->getDepth(),
554 NTTP->getPosition(), 0,
555 T,
556 TInfo,
557 ExpandedTypes.data(),
558 ExpandedTypes.size(),
559 ExpandedTInfos.data());
560 } else {
561 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000562 SourceLocation(),
563 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000564 NTTP->getDepth(),
565 NTTP->getPosition(), 0,
566 T,
567 NTTP->isParameterPack(),
568 TInfo);
569 }
570 CanonParams.push_back(Param);
571
572 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000573 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
574 cast<TemplateTemplateParmDecl>(*P)));
575 }
576
577 TemplateTemplateParmDecl *CanonTTP
578 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
579 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000580 TTP->getPosition(),
581 TTP->isParameterPack(),
582 0,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000583 TemplateParameterList::Create(*this, SourceLocation(),
584 SourceLocation(),
585 CanonParams.data(),
586 CanonParams.size(),
587 SourceLocation()));
588
589 // Get the new insert position for the node we care about.
590 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
591 assert(Canonical == 0 && "Shouldn't be in the map!");
592 (void)Canonical;
593
594 // Create the canonical template template parameter entry.
595 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
596 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
597 return CanonTTP;
598}
599
Charles Davis53c59df2010-08-16 03:33:14 +0000600CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000601 if (!LangOpts.CPlusPlus) return 0;
602
John McCall359b8852013-01-25 22:30:49 +0000603 switch (T.getCXXABI().getKind()) {
604 case TargetCXXABI::GenericARM:
605 case TargetCXXABI::iOS:
John McCall86353412010-08-21 22:46:04 +0000606 return CreateARMCXXABI(*this);
Tim Northover9bb857a2013-01-31 12:13:10 +0000607 case TargetCXXABI::GenericAArch64: // Same as Itanium at this level
John McCall359b8852013-01-25 22:30:49 +0000608 case TargetCXXABI::GenericItanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000609 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000610 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000611 return CreateMicrosoftCXXABI(*this);
612 }
David Blaikie8a40f702012-01-17 06:56:22 +0000613 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000614}
615
Douglas Gregore8bbc122011-09-02 00:18:52 +0000616static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000617 const LangOptions &LOpts) {
618 if (LOpts.FakeAddressSpaceMap) {
619 // The fake address space map must have a distinct entry for each
620 // language-specific address space.
621 static const unsigned FakeAddrSpaceMap[] = {
622 1, // opencl_global
623 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000624 3, // opencl_constant
625 4, // cuda_device
626 5, // cuda_constant
627 6 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000628 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000629 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000630 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000631 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000632 }
633}
634
Douglas Gregor7018d5b2011-09-01 20:23:19 +0000635ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000636 const TargetInfo *t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000637 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000638 Builtin::Context &builtins,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000639 unsigned size_reserve,
640 bool DelayInitialization)
641 : FunctionProtoTypes(this_()),
642 TemplateSpecializationTypes(this_()),
643 DependentTemplateSpecializationTypes(this_()),
644 SubstTemplateTemplateParmPacks(this_()),
645 GlobalNestedNameSpecifier(0),
646 Int128Decl(0), UInt128Decl(0),
Meador Inge5d3fb222012-06-16 03:34:49 +0000647 BuiltinVaListDecl(0),
Douglas Gregord53ae832012-01-17 18:09:05 +0000648 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Fariborz Jahanianf2578572012-08-30 18:49:41 +0000649 BOOLDecl(0),
Douglas Gregorbab8a962011-09-08 01:46:34 +0000650 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000651 FILEDecl(0),
Rafael Espindola6cfa82b2011-11-13 21:51:09 +0000652 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
653 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
654 cudaConfigureCallDecl(0),
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000655 NullTypeSourceInfo(QualType()),
656 FirstLocalImport(), LastLocalImport(),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000657 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000658 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000659 Idents(idents), Selectors(sels),
660 BuiltinInfo(builtins),
661 DeclarationNames(*this),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000662 ExternalSource(0), Listener(0),
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000663 Comments(SM), CommentsLoaded(false),
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000664 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000665 LastSDM(0, 0),
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +0000666 UniqueBlockByRefTypeID(0)
Douglas Gregore8bbc122011-09-02 00:18:52 +0000667{
Mike Stump11289f42009-09-09 15:08:12 +0000668 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000669 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000670
671 if (!DelayInitialization) {
672 assert(t && "No target supplied for ASTContext initialization");
673 InitBuiltinTypes(*t);
674 }
Daniel Dunbar221fa942008-08-11 04:54:23 +0000675}
676
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000677ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000678 // Release the DenseMaps associated with DeclContext objects.
679 // FIXME: Is this the ideal solution?
680 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000681
Douglas Gregor5b11d492010-07-25 17:53:33 +0000682 // Call all of the deallocation functions.
683 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
684 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor1a809332010-05-23 18:26:36 +0000685
Ted Kremenek076baeb2010-06-08 23:00:58 +0000686 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000687 // because they can contain DenseMaps.
688 for (llvm::DenseMap<const ObjCContainerDecl*,
689 const ASTRecordLayout*>::iterator
690 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
691 // Increment in loop to prevent using deallocated memory.
692 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
693 R->Destroy(*this);
694
Ted Kremenek076baeb2010-06-08 23:00:58 +0000695 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
696 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
697 // Increment in loop to prevent using deallocated memory.
698 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
699 R->Destroy(*this);
700 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000701
702 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
703 AEnd = DeclAttrs.end();
704 A != AEnd; ++A)
705 A->second->~AttrVec();
706}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000707
Douglas Gregor1a809332010-05-23 18:26:36 +0000708void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
709 Deallocations.push_back(std::make_pair(Callback, Data));
710}
711
Mike Stump11289f42009-09-09 15:08:12 +0000712void
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000713ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000714 ExternalSource.reset(Source.take());
715}
716
Chris Lattner4eb445d2007-01-26 01:27:23 +0000717void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000718 llvm::errs() << "\n*** AST Context Stats:\n";
719 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000720
Douglas Gregora30d0462009-05-26 14:40:08 +0000721 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000722#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000723#define ABSTRACT_TYPE(Name, Parent)
724#include "clang/AST/TypeNodes.def"
725 0 // Extra
726 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000727
Chris Lattner4eb445d2007-01-26 01:27:23 +0000728 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
729 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000730 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000731 }
732
Douglas Gregora30d0462009-05-26 14:40:08 +0000733 unsigned Idx = 0;
734 unsigned TotalBytes = 0;
735#define TYPE(Name, Parent) \
736 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000737 llvm::errs() << " " << counts[Idx] << " " << #Name \
738 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000739 TotalBytes += counts[Idx] * sizeof(Name##Type); \
740 ++Idx;
741#define ABSTRACT_TYPE(Name, Parent)
742#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000743
Chandler Carruth3c147a72011-07-04 05:32:14 +0000744 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
745
Douglas Gregor7454c562010-07-02 20:37:36 +0000746 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000747 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
748 << NumImplicitDefaultConstructors
749 << " implicit default constructors created\n";
750 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
751 << NumImplicitCopyConstructors
752 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000753 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000754 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
755 << NumImplicitMoveConstructors
756 << " implicit move constructors created\n";
757 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
758 << NumImplicitCopyAssignmentOperators
759 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000760 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000761 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
762 << NumImplicitMoveAssignmentOperators
763 << " implicit move assignment operators created\n";
764 llvm::errs() << NumImplicitDestructorsDeclared << "/"
765 << NumImplicitDestructors
766 << " implicit destructors created\n";
767
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000768 if (ExternalSource.get()) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000769 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000770 ExternalSource->PrintStats();
771 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000772
Douglas Gregor5b11d492010-07-25 17:53:33 +0000773 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000774}
775
Douglas Gregor801c99d2011-08-12 06:49:56 +0000776TypedefDecl *ASTContext::getInt128Decl() const {
777 if (!Int128Decl) {
778 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
779 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
780 getTranslationUnitDecl(),
781 SourceLocation(),
782 SourceLocation(),
783 &Idents.get("__int128_t"),
784 TInfo);
785 }
786
787 return Int128Decl;
788}
789
790TypedefDecl *ASTContext::getUInt128Decl() const {
791 if (!UInt128Decl) {
792 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
793 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
794 getTranslationUnitDecl(),
795 SourceLocation(),
796 SourceLocation(),
797 &Idents.get("__uint128_t"),
798 TInfo);
799 }
800
801 return UInt128Decl;
802}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000803
John McCall48f2d582009-10-23 23:03:21 +0000804void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000805 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000806 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000807 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000808}
809
Douglas Gregore8bbc122011-09-02 00:18:52 +0000810void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
811 assert((!this->Target || this->Target == &Target) &&
812 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000813 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000814
Douglas Gregore8bbc122011-09-02 00:18:52 +0000815 this->Target = &Target;
816
817 ABI.reset(createCXXABI(Target));
818 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
819
Chris Lattner970e54e2006-11-12 00:37:36 +0000820 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000821 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000822
Chris Lattner970e54e2006-11-12 00:37:36 +0000823 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000824 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000825 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000826 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000827 InitBuiltinType(CharTy, BuiltinType::Char_S);
828 else
829 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000830 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000831 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
832 InitBuiltinType(ShortTy, BuiltinType::Short);
833 InitBuiltinType(IntTy, BuiltinType::Int);
834 InitBuiltinType(LongTy, BuiltinType::Long);
835 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000836
Chris Lattner970e54e2006-11-12 00:37:36 +0000837 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000838 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
839 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
840 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
841 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
842 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000843
Chris Lattner970e54e2006-11-12 00:37:36 +0000844 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000845 InitBuiltinType(FloatTy, BuiltinType::Float);
846 InitBuiltinType(DoubleTy, BuiltinType::Double);
847 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000848
Chris Lattnerf122cef2009-04-30 02:43:43 +0000849 // GNU extension, 128-bit integers.
850 InitBuiltinType(Int128Ty, BuiltinType::Int128);
851 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
852
Abramo Bagnara06782942012-09-09 10:13:32 +0000853 if (LangOpts.CPlusPlus && LangOpts.WChar) { // C++ 3.9.1p5
Eli Friedman786d0872011-04-30 19:24:24 +0000854 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattnerad3467e2010-12-25 23:25:43 +0000855 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
856 else // -fshort-wchar makes wchar_t be unsigned.
857 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
Abramo Bagnara06782942012-09-09 10:13:32 +0000858 } else // C99 (or C++ using -fno-wchar)
Chris Lattner007cb022009-02-26 23:43:47 +0000859 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000860
James Molloy36365542012-05-04 10:55:22 +0000861 WIntTy = getFromTargetType(Target.getWIntType());
862
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000863 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
864 InitBuiltinType(Char16Ty, BuiltinType::Char16);
865 else // C99
866 Char16Ty = getFromTargetType(Target.getChar16Type());
867
868 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
869 InitBuiltinType(Char32Ty, BuiltinType::Char32);
870 else // C99
871 Char32Ty = getFromTargetType(Target.getChar32Type());
872
Douglas Gregor4619e432008-12-05 23:32:09 +0000873 // Placeholder type for type-dependent expressions whose type is
874 // completely unknown. No code should ever check a type against
875 // DependentTy and users should never see it; however, it is here to
876 // help diagnose failures to properly check for type-dependent
877 // expressions.
878 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000879
John McCall36e7fe32010-10-12 00:20:44 +0000880 // Placeholder type for functions.
881 InitBuiltinType(OverloadTy, BuiltinType::Overload);
882
John McCall0009fcc2011-04-26 20:42:42 +0000883 // Placeholder type for bound members.
884 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
885
John McCall526ab472011-10-25 17:37:35 +0000886 // Placeholder type for pseudo-objects.
887 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
888
John McCall31996342011-04-07 08:22:57 +0000889 // "any" type; useful for debugger-like clients.
890 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
891
John McCall8a6b59a2011-10-17 18:09:15 +0000892 // Placeholder type for unbridged ARC casts.
893 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
894
Eli Friedman34866c72012-08-31 00:14:07 +0000895 // Placeholder type for builtin functions.
896 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
897
Chris Lattner970e54e2006-11-12 00:37:36 +0000898 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000899 FloatComplexTy = getComplexType(FloatTy);
900 DoubleComplexTy = getComplexType(DoubleTy);
901 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000902
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000903 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000904 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
905 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000906 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000907
908 if (LangOpts.OpenCL) {
909 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
910 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
911 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
912 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
913 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
914 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +0000915
Guy Benyei61054192013-02-07 10:55:47 +0000916 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +0000917 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000918 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000919
920 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +0000921 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
922 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000923
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000924 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +0000925
926 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000927
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000928 // void * type
929 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000930
931 // nullptr type (C++0x 2.14.7)
932 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000933
934 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
935 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +0000936
937 // Builtin type used to help define __builtin_va_list.
938 VaListTagTy = QualType();
Chris Lattner970e54e2006-11-12 00:37:36 +0000939}
940
David Blaikie9c902b52011-09-25 23:23:43 +0000941DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000942 return SourceMgr.getDiagnostics();
943}
944
Douglas Gregor561eceb2010-08-30 16:49:28 +0000945AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
946 AttrVec *&Result = DeclAttrs[D];
947 if (!Result) {
948 void *Mem = Allocate(sizeof(AttrVec));
949 Result = new (Mem) AttrVec;
950 }
951
952 return *Result;
953}
954
955/// \brief Erase the attributes corresponding to the given declaration.
956void ASTContext::eraseDeclAttrs(const Decl *D) {
957 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
958 if (Pos != DeclAttrs.end()) {
959 Pos->second->~AttrVec();
960 DeclAttrs.erase(Pos);
961 }
962}
963
Douglas Gregor86d142a2009-10-08 07:24:58 +0000964MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000965ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000966 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000967 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000968 = InstantiatedFromStaticDataMember.find(Var);
969 if (Pos == InstantiatedFromStaticDataMember.end())
970 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000971
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000972 return Pos->second;
973}
974
Mike Stump11289f42009-09-09 15:08:12 +0000975void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000976ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000977 TemplateSpecializationKind TSK,
978 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000979 assert(Inst->isStaticDataMember() && "Not a static data member");
980 assert(Tmpl->isStaticDataMember() && "Not a static data member");
981 assert(!InstantiatedFromStaticDataMember[Inst] &&
982 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000983 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000984 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000985}
986
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000987FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
988 const FunctionDecl *FD){
989 assert(FD && "Specialization is 0");
990 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +0000991 = ClassScopeSpecializationPattern.find(FD);
992 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000993 return 0;
994
995 return Pos->second;
996}
997
998void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
999 FunctionDecl *Pattern) {
1000 assert(FD && "Specialization is 0");
1001 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001002 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001003}
1004
John McCalle61f2ba2009-11-18 02:36:19 +00001005NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +00001006ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +00001007 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +00001008 = InstantiatedFromUsingDecl.find(UUD);
1009 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001010 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001011
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001012 return Pos->second;
1013}
1014
1015void
John McCallb96ec562009-12-04 22:46:56 +00001016ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1017 assert((isa<UsingDecl>(Pattern) ||
1018 isa<UnresolvedUsingValueDecl>(Pattern) ||
1019 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1020 "pattern decl is not a using decl");
1021 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1022 InstantiatedFromUsingDecl[Inst] = Pattern;
1023}
1024
1025UsingShadowDecl *
1026ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1027 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1028 = InstantiatedFromUsingShadowDecl.find(Inst);
1029 if (Pos == InstantiatedFromUsingShadowDecl.end())
1030 return 0;
1031
1032 return Pos->second;
1033}
1034
1035void
1036ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1037 UsingShadowDecl *Pattern) {
1038 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1039 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001040}
1041
Anders Carlsson5da84842009-09-01 04:26:58 +00001042FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1043 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1044 = InstantiatedFromUnnamedFieldDecl.find(Field);
1045 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1046 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001047
Anders Carlsson5da84842009-09-01 04:26:58 +00001048 return Pos->second;
1049}
1050
1051void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1052 FieldDecl *Tmpl) {
1053 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1054 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1055 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1056 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001057
Anders Carlsson5da84842009-09-01 04:26:58 +00001058 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1059}
1060
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +00001061bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
1062 const FieldDecl *LastFD) const {
1063 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001064 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +00001065}
1066
Fariborz Jahanianeb397412011-05-02 17:20:56 +00001067bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
1068 const FieldDecl *LastFD) const {
1069 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001070 FD->getBitWidthValue(*this) == 0 &&
1071 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanianeb397412011-05-02 17:20:56 +00001072}
1073
Fariborz Jahanian84335f72011-05-04 18:51:37 +00001074bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
1075 const FieldDecl *LastFD) const {
1076 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001077 FD->getBitWidthValue(*this) &&
1078 LastFD->getBitWidthValue(*this));
Fariborz Jahanian84335f72011-05-04 18:51:37 +00001079}
1080
Chad Rosierf01a7dd2011-08-04 23:34:15 +00001081bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +00001082 const FieldDecl *LastFD) const {
1083 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001084 LastFD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +00001085}
1086
Chad Rosierf01a7dd2011-08-04 23:34:15 +00001087bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +00001088 const FieldDecl *LastFD) const {
1089 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001090 FD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +00001091}
1092
Douglas Gregor832940b2010-03-02 23:58:15 +00001093ASTContext::overridden_cxx_method_iterator
1094ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1095 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001096 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001097 if (Pos == OverriddenMethods.end())
1098 return 0;
1099
1100 return Pos->second.begin();
1101}
1102
1103ASTContext::overridden_cxx_method_iterator
1104ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1105 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001106 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001107 if (Pos == OverriddenMethods.end())
1108 return 0;
1109
1110 return Pos->second.end();
1111}
1112
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001113unsigned
1114ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1115 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001116 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001117 if (Pos == OverriddenMethods.end())
1118 return 0;
1119
1120 return Pos->second.size();
1121}
1122
Douglas Gregor832940b2010-03-02 23:58:15 +00001123void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1124 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001125 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001126 OverriddenMethods[Method].push_back(Overridden);
1127}
1128
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001129void ASTContext::getOverriddenMethods(
1130 const NamedDecl *D,
1131 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001132 assert(D);
1133
1134 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001135 Overridden.append(overridden_methods_begin(CXXMethod),
1136 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001137 return;
1138 }
1139
1140 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1141 if (!Method)
1142 return;
1143
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001144 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1145 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001146 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001147}
1148
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001149void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1150 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1151 assert(!Import->isFromASTFile() && "Non-local import declaration");
1152 if (!FirstLocalImport) {
1153 FirstLocalImport = Import;
1154 LastLocalImport = Import;
1155 return;
1156 }
1157
1158 LastLocalImport->NextLocalImport = Import;
1159 LastLocalImport = Import;
1160}
1161
Chris Lattner53cfe802007-07-18 17:52:12 +00001162//===----------------------------------------------------------------------===//
1163// Type Sizing and Analysis
1164//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001165
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001166/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1167/// scalar floating point type.
1168const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001169 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001170 assert(BT && "Not a floating point type!");
1171 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001172 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001173 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001174 case BuiltinType::Float: return Target->getFloatFormat();
1175 case BuiltinType::Double: return Target->getDoubleFormat();
1176 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001177 }
1178}
1179
Ken Dyck160146e2010-01-27 17:10:57 +00001180/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +00001181/// specified decl. Note that bitfields do not have a valid alignment, so
1182/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001183/// If @p RefAsPointee, references are treated like their underlying type
1184/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad39c79802011-01-12 09:06:06 +00001185CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001186 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001187
John McCall94268702010-10-08 18:24:19 +00001188 bool UseAlignAttrOnly = false;
1189 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1190 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001191
John McCall94268702010-10-08 18:24:19 +00001192 // __attribute__((aligned)) can increase or decrease alignment
1193 // *except* on a struct or struct member, where it only increases
1194 // alignment unless 'packed' is also specified.
1195 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001196 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001197 // ignore that possibility; Sema should diagnose it.
1198 if (isa<FieldDecl>(D)) {
1199 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1200 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1201 } else {
1202 UseAlignAttrOnly = true;
1203 }
1204 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001205 else if (isa<FieldDecl>(D))
1206 UseAlignAttrOnly =
1207 D->hasAttr<PackedAttr>() ||
1208 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001209
John McCall4e819612011-01-20 07:57:12 +00001210 // If we're using the align attribute only, just ignore everything
1211 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001212 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001213 // do nothing
1214
John McCall94268702010-10-08 18:24:19 +00001215 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001216 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001217 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001218 if (RefAsPointee)
1219 T = RT->getPointeeType();
1220 else
1221 T = getPointerType(RT->getPointeeType());
1222 }
1223 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +00001224 // Adjust alignments of declarations with array type by the
1225 // large-array alignment on the target.
Douglas Gregore8bbc122011-09-02 00:18:52 +00001226 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall33ddac02011-01-19 10:06:00 +00001227 const ArrayType *arrayType;
1228 if (MinWidth && (arrayType = getAsArrayType(T))) {
1229 if (isa<VariableArrayType>(arrayType))
Douglas Gregore8bbc122011-09-02 00:18:52 +00001230 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall33ddac02011-01-19 10:06:00 +00001231 else if (isa<ConstantArrayType>(arrayType) &&
1232 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregore8bbc122011-09-02 00:18:52 +00001233 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedman19a546c2009-02-22 02:56:25 +00001234
John McCall33ddac02011-01-19 10:06:00 +00001235 // Walk through any array types while we're at it.
1236 T = getBaseElementType(arrayType);
1237 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001238 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedman19a546c2009-02-22 02:56:25 +00001239 }
John McCall4e819612011-01-20 07:57:12 +00001240
1241 // Fields can be subject to extra alignment constraints, like if
1242 // the field is packed, the struct is packed, or the struct has a
1243 // a max-field-alignment constraint (#pragma pack). So calculate
1244 // the actual alignment of the field within the struct, and then
1245 // (as we're expected to) constrain that by the alignment of the type.
1246 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
1247 // So calculate the alignment of the field.
1248 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
1249
1250 // Start with the record's overall alignment.
Ken Dyck7ad11e72011-02-15 02:32:40 +00001251 unsigned fieldAlign = toBits(layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001252
1253 // Use the GCD of that and the offset within the record.
1254 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
1255 if (offset > 0) {
1256 // Alignment is always a power of 2, so the GCD will be a power of 2,
1257 // which means we get to do this crazy thing instead of Euclid's.
1258 uint64_t lowBitOfOffset = offset & (~offset + 1);
1259 if (lowBitOfOffset < fieldAlign)
1260 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
1261 }
1262
1263 Align = std::min(Align, fieldAlign);
Charles Davis3fc51072010-02-23 04:52:00 +00001264 }
Chris Lattner68061312009-01-24 21:53:27 +00001265 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001266
Ken Dyckcc56c542011-01-15 18:38:59 +00001267 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001268}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001269
John McCallf1249922012-08-21 04:10:00 +00001270// getTypeInfoDataSizeInChars - Return the size of a type, in
1271// chars. If the type is a record, its data size is returned. This is
1272// the size of the memcpy that's performed when assigning this type
1273// using a trivial copy/move assignment operator.
1274std::pair<CharUnits, CharUnits>
1275ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1276 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1277
1278 // In C++, objects can sometimes be allocated into the tail padding
1279 // of a base-class subobject. We decide whether that's possible
1280 // during class layout, so here we can just trust the layout results.
1281 if (getLangOpts().CPlusPlus) {
1282 if (const RecordType *RT = T->getAs<RecordType>()) {
1283 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1284 sizeAndAlign.first = layout.getDataSize();
1285 }
1286 }
1287
1288 return sizeAndAlign;
1289}
1290
John McCall87fe5d52010-05-20 01:18:31 +00001291std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001292ASTContext::getTypeInfoInChars(const Type *T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001293 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +00001294 return std::make_pair(toCharUnitsFromBits(Info.first),
1295 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +00001296}
1297
1298std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001299ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001300 return getTypeInfoInChars(T.getTypePtr());
1301}
1302
Daniel Dunbarc6475872012-03-09 04:12:54 +00001303std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1304 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1305 if (it != MemoizedTypeInfo.end())
1306 return it->second;
1307
1308 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1309 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1310 return Info;
1311}
1312
1313/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1314/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001315///
1316/// FIXME: Pointers into different addr spaces could have different sizes and
1317/// alignment requirements: getPointerInfo should take an AddrSpace, this
1318/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +00001319std::pair<uint64_t, unsigned>
Daniel Dunbarc6475872012-03-09 04:12:54 +00001320ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +00001321 uint64_t Width=0;
1322 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001323 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001324#define TYPE(Class, Base)
1325#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001326#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001327#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1328#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001329 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001330
Chris Lattner355332d2007-07-13 22:27:08 +00001331 case Type::FunctionNoProto:
1332 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001333 // GCC extension: alignof(function) = 32 bits
1334 Width = 0;
1335 Align = 32;
1336 break;
1337
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001338 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001339 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001340 Width = 0;
1341 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1342 break;
1343
Steve Naroff5c131802007-08-30 01:06:46 +00001344 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001345 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001346
Chris Lattner37e05872008-03-05 18:54:05 +00001347 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001348 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarc6475872012-03-09 04:12:54 +00001349 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1350 "Overflow in array type bit size evaluation");
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001351 Width = EltInfo.first*Size;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001352 Align = EltInfo.second;
Argyrios Kyrtzidisae40e4e2011-04-26 21:05:39 +00001353 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001354 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001355 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001356 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001357 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001358 const VectorType *VT = cast<VectorType>(T);
1359 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1360 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001361 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001362 // If the alignment is not a power of 2, round up to the next power of 2.
1363 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001364 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001365 Align = llvm::NextPowerOf2(Align);
1366 Width = llvm::RoundUpToAlignment(Width, Align);
1367 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001368 // Adjust the alignment based on the target max.
1369 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1370 if (TargetVectorAlign && TargetVectorAlign < Align)
1371 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001372 break;
1373 }
Chris Lattner647fb222007-07-18 18:26:58 +00001374
Chris Lattner7570e9c2008-03-08 08:52:55 +00001375 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001376 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001377 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001378 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001379 // GCC extension: alignof(void) = 8 bits.
1380 Width = 0;
1381 Align = 8;
1382 break;
1383
Chris Lattner6a4f7452007-12-19 19:23:28 +00001384 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001385 Width = Target->getBoolWidth();
1386 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001387 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001388 case BuiltinType::Char_S:
1389 case BuiltinType::Char_U:
1390 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001391 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001392 Width = Target->getCharWidth();
1393 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001394 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001395 case BuiltinType::WChar_S:
1396 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001397 Width = Target->getWCharWidth();
1398 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001399 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001400 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001401 Width = Target->getChar16Width();
1402 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001403 break;
1404 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001405 Width = Target->getChar32Width();
1406 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001407 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001408 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001409 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001410 Width = Target->getShortWidth();
1411 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001412 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001413 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001414 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001415 Width = Target->getIntWidth();
1416 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001417 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001418 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001419 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001420 Width = Target->getLongWidth();
1421 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001422 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001423 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001424 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001425 Width = Target->getLongLongWidth();
1426 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001427 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001428 case BuiltinType::Int128:
1429 case BuiltinType::UInt128:
1430 Width = 128;
1431 Align = 128; // int128_t is 128-bit aligned on all targets.
1432 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001433 case BuiltinType::Half:
1434 Width = Target->getHalfWidth();
1435 Align = Target->getHalfAlign();
1436 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001437 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001438 Width = Target->getFloatWidth();
1439 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001440 break;
1441 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001442 Width = Target->getDoubleWidth();
1443 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001444 break;
1445 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001446 Width = Target->getLongDoubleWidth();
1447 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001448 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001449 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001450 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1451 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001452 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001453 case BuiltinType::ObjCId:
1454 case BuiltinType::ObjCClass:
1455 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001456 Width = Target->getPointerWidth(0);
1457 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001458 break;
Guy Benyei61054192013-02-07 10:55:47 +00001459 case BuiltinType::OCLSampler:
1460 // Samplers are modeled as integers.
1461 Width = Target->getIntWidth();
1462 Align = Target->getIntAlign();
1463 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001464 case BuiltinType::OCLEvent:
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001465 case BuiltinType::OCLImage1d:
1466 case BuiltinType::OCLImage1dArray:
1467 case BuiltinType::OCLImage1dBuffer:
1468 case BuiltinType::OCLImage2d:
1469 case BuiltinType::OCLImage2dArray:
1470 case BuiltinType::OCLImage3d:
1471 // Currently these types are pointers to opaque types.
1472 Width = Target->getPointerWidth(0);
1473 Align = Target->getPointerAlign(0);
1474 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001475 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001476 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001477 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001478 Width = Target->getPointerWidth(0);
1479 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001480 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001481 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001482 unsigned AS = getTargetAddressSpace(
1483 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001484 Width = Target->getPointerWidth(AS);
1485 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001486 break;
1487 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001488 case Type::LValueReference:
1489 case Type::RValueReference: {
1490 // alignof and sizeof should never enter this code path here, so we go
1491 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001492 unsigned AS = getTargetAddressSpace(
1493 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001494 Width = Target->getPointerWidth(AS);
1495 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001496 break;
1497 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001498 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001499 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001500 Width = Target->getPointerWidth(AS);
1501 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001502 break;
1503 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001504 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001505 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Reid Kleckner3a52abf2013-03-28 20:02:56 +00001506 llvm::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001507 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001508 }
Chris Lattner647fb222007-07-18 18:26:58 +00001509 case Type::Complex: {
1510 // Complex types have the same alignment as their elements, but twice the
1511 // size.
Mike Stump11289f42009-09-09 15:08:12 +00001512 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +00001513 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +00001514 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +00001515 Align = EltInfo.second;
1516 break;
1517 }
John McCall8b07ec22010-05-15 11:32:37 +00001518 case Type::ObjCObject:
1519 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001520 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001521 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001522 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001523 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001524 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001525 break;
1526 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001527 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001528 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001529 const TagType *TT = cast<TagType>(T);
1530
1531 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001532 Width = 8;
1533 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001534 break;
1535 }
Mike Stump11289f42009-09-09 15:08:12 +00001536
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001537 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +00001538 return getTypeInfo(ET->getDecl()->getIntegerType());
1539
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001540 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +00001541 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001542 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001543 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +00001544 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001545 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001546
Chris Lattner63d2b362009-10-22 05:17:15 +00001547 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001548 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1549 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001550
Richard Smith30482bc2011-02-20 03:19:35 +00001551 case Type::Auto: {
1552 const AutoType *A = cast<AutoType>(T);
1553 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001554 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001555 }
1556
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001557 case Type::Paren:
1558 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1559
Douglas Gregoref462e62009-04-30 17:32:17 +00001560 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001561 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +00001562 std::pair<uint64_t, unsigned> Info
1563 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001564 // If the typedef has an aligned attribute on it, it overrides any computed
1565 // alignment we have. This violates the GCC documentation (which says that
1566 // attribute(aligned) can only round up) but matches its implementation.
1567 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1568 Align = AttrAlign;
1569 else
1570 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +00001571 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +00001572 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001573 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001574
1575 case Type::TypeOfExpr:
1576 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1577 .getTypePtr());
1578
1579 case Type::TypeOf:
1580 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1581
Anders Carlsson81df7b82009-06-24 19:06:50 +00001582 case Type::Decltype:
1583 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1584 .getTypePtr());
1585
Alexis Hunte852b102011-05-24 22:41:36 +00001586 case Type::UnaryTransform:
1587 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1588
Abramo Bagnara6150c882010-05-11 21:36:43 +00001589 case Type::Elaborated:
1590 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001591
John McCall81904512011-01-06 01:58:22 +00001592 case Type::Attributed:
1593 return getTypeInfo(
1594 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1595
Richard Smith3f1b5d02011-05-05 21:57:07 +00001596 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00001597 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +00001598 "Cannot request the size of a dependent type");
Richard Smith3f1b5d02011-05-05 21:57:07 +00001599 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1600 // A type alias template specialization may refer to a typedef with the
1601 // aligned attribute on it.
1602 if (TST->isTypeAlias())
1603 return getTypeInfo(TST->getAliasedType().getTypePtr());
1604 else
1605 return getTypeInfo(getCanonicalType(T));
1606 }
1607
Eli Friedman0dfb8892011-10-06 23:00:33 +00001608 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00001609 // Start with the base type information.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001610 std::pair<uint64_t, unsigned> Info
1611 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1612 Width = Info.first;
1613 Align = Info.second;
John McCalla8ec7eb2013-03-07 21:37:17 +00001614
1615 // If the size of the type doesn't exceed the platform's max
1616 // atomic promotion width, make the size and alignment more
1617 // favorable to atomic operations:
1618 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1619 // Round the size up to a power of 2.
1620 if (!llvm::isPowerOf2_64(Width))
1621 Width = llvm::NextPowerOf2(Width);
1622
1623 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001624 Align = static_cast<unsigned>(Width);
1625 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001626 }
1627
Douglas Gregoref462e62009-04-30 17:32:17 +00001628 }
Mike Stump11289f42009-09-09 15:08:12 +00001629
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001630 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +00001631 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001632}
1633
Ken Dyckcc56c542011-01-15 18:38:59 +00001634/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1635CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1636 return CharUnits::fromQuantity(BitSize / getCharWidth());
1637}
1638
Ken Dyckb0fcc592011-02-11 01:54:29 +00001639/// toBits - Convert a size in characters to a size in characters.
1640int64_t ASTContext::toBits(CharUnits CharSize) const {
1641 return CharSize.getQuantity() * getCharWidth();
1642}
1643
Ken Dyck8c89d592009-12-22 14:23:30 +00001644/// getTypeSizeInChars - Return the size of the specified type, in characters.
1645/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001646CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001647 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001648}
Jay Foad39c79802011-01-12 09:06:06 +00001649CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001650 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001651}
1652
Ken Dycka6046ab2010-01-26 17:25:18 +00001653/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001654/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001655CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001656 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001657}
Jay Foad39c79802011-01-12 09:06:06 +00001658CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001659 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001660}
1661
Chris Lattnera3402cd2009-01-27 18:08:34 +00001662/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1663/// type for the current target in bits. This can be different than the ABI
1664/// alignment in cases where it is beneficial for performance to overalign
1665/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001666unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +00001667 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +00001668
1669 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +00001670 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001671 T = CT->getElementType().getTypePtr();
1672 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001673 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1674 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman7ab09572009-05-25 21:27:19 +00001675 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1676
Chris Lattnera3402cd2009-01-27 18:08:34 +00001677 return ABIAlign;
1678}
1679
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001680/// DeepCollectObjCIvars -
1681/// This routine first collects all declared, but not synthesized, ivars in
1682/// super class and then collects all ivars, including those synthesized for
1683/// current class. This routine is used for implementation of current class
1684/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001685///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001686void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1687 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001688 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001689 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1690 DeepCollectObjCIvars(SuperClass, false, Ivars);
1691 if (!leafClass) {
1692 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1693 E = OI->ivar_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001694 Ivars.push_back(*I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001695 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001696 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001697 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001698 Iv= Iv->getNextIvar())
1699 Ivars.push_back(Iv);
1700 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001701}
1702
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001703/// CollectInheritedProtocols - Collect all protocols in current class and
1704/// those inherited by it.
1705void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001706 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001707 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001708 // We can use protocol_iterator here instead of
1709 // all_referenced_protocol_iterator since we are walking all categories.
1710 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1711 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001712 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001713 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001714 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001715 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001716 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001717 CollectInheritedProtocols(*P, Protocols);
1718 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001719 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001720
1721 // Categories of this Interface.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001722 for (ObjCInterfaceDecl::visible_categories_iterator
1723 Cat = OI->visible_categories_begin(),
1724 CatEnd = OI->visible_categories_end();
1725 Cat != CatEnd; ++Cat) {
1726 CollectInheritedProtocols(*Cat, Protocols);
1727 }
1728
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001729 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1730 while (SD) {
1731 CollectInheritedProtocols(SD, Protocols);
1732 SD = SD->getSuperClass();
1733 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001734 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001735 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001736 PE = OC->protocol_end(); P != PE; ++P) {
1737 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001738 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001739 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1740 PE = Proto->protocol_end(); P != PE; ++P)
1741 CollectInheritedProtocols(*P, Protocols);
1742 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001743 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001744 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1745 PE = OP->protocol_end(); P != PE; ++P) {
1746 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001747 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001748 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1749 PE = Proto->protocol_end(); P != PE; ++P)
1750 CollectInheritedProtocols(*P, Protocols);
1751 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001752 }
1753}
1754
Jay Foad39c79802011-01-12 09:06:06 +00001755unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001756 unsigned count = 0;
1757 // Count ivars declared in class extension.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001758 for (ObjCInterfaceDecl::known_extensions_iterator
1759 Ext = OI->known_extensions_begin(),
1760 ExtEnd = OI->known_extensions_end();
1761 Ext != ExtEnd; ++Ext) {
1762 count += Ext->ivar_size();
1763 }
1764
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001765 // Count ivar defined in this class's implementation. This
1766 // includes synthesized ivars.
1767 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001768 count += ImplDecl->ivar_size();
1769
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001770 return count;
1771}
1772
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001773bool ASTContext::isSentinelNullExpr(const Expr *E) {
1774 if (!E)
1775 return false;
1776
1777 // nullptr_t is always treated as null.
1778 if (E->getType()->isNullPtrType()) return true;
1779
1780 if (E->getType()->isAnyPointerType() &&
1781 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1782 Expr::NPC_ValueDependentIsNull))
1783 return true;
1784
1785 // Unfortunately, __null has type 'int'.
1786 if (isa<GNUNullExpr>(E)) return true;
1787
1788 return false;
1789}
1790
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001791/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1792ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1793 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1794 I = ObjCImpls.find(D);
1795 if (I != ObjCImpls.end())
1796 return cast<ObjCImplementationDecl>(I->second);
1797 return 0;
1798}
1799/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1800ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1801 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1802 I = ObjCImpls.find(D);
1803 if (I != ObjCImpls.end())
1804 return cast<ObjCCategoryImplDecl>(I->second);
1805 return 0;
1806}
1807
1808/// \brief Set the implementation of ObjCInterfaceDecl.
1809void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1810 ObjCImplementationDecl *ImplD) {
1811 assert(IFaceD && ImplD && "Passed null params");
1812 ObjCImpls[IFaceD] = ImplD;
1813}
1814/// \brief Set the implementation of ObjCCategoryDecl.
1815void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1816 ObjCCategoryImplDecl *ImplD) {
1817 assert(CatD && ImplD && "Passed null params");
1818 ObjCImpls[CatD] = ImplD;
1819}
1820
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001821const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
1822 const NamedDecl *ND) const {
1823 if (const ObjCInterfaceDecl *ID =
1824 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001825 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001826 if (const ObjCCategoryDecl *CD =
1827 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001828 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001829 if (const ObjCImplDecl *IMD =
1830 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001831 return IMD->getClassInterface();
1832
1833 return 0;
1834}
1835
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001836/// \brief Get the copy initialization expression of VarDecl,or NULL if
1837/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001838Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001839 assert(VD && "Passed null params");
1840 assert(VD->hasAttr<BlocksAttr>() &&
1841 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001842 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001843 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001844 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1845}
1846
1847/// \brief Set the copy inialization expression of a block var decl.
1848void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1849 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001850 assert(VD->hasAttr<BlocksAttr>() &&
1851 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001852 BlockVarCopyInits[VD] = Init;
1853}
1854
John McCallbcd03502009-12-07 02:54:59 +00001855TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001856 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001857 if (!DataSize)
1858 DataSize = TypeLoc::getFullDataSizeForType(T);
1859 else
1860 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001861 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001862
John McCallbcd03502009-12-07 02:54:59 +00001863 TypeSourceInfo *TInfo =
1864 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1865 new (TInfo) TypeSourceInfo(T);
1866 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001867}
1868
John McCallbcd03502009-12-07 02:54:59 +00001869TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001870 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001871 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001872 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001873 return DI;
1874}
1875
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001876const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001877ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001878 return getObjCLayout(D, 0);
1879}
1880
1881const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001882ASTContext::getASTObjCImplementationLayout(
1883 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001884 return getObjCLayout(D->getClassInterface(), D);
1885}
1886
Chris Lattner983a8bb2007-07-13 22:13:22 +00001887//===----------------------------------------------------------------------===//
1888// Type creation/memoization methods
1889//===----------------------------------------------------------------------===//
1890
Jay Foad39c79802011-01-12 09:06:06 +00001891QualType
John McCall33ddac02011-01-19 10:06:00 +00001892ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1893 unsigned fastQuals = quals.getFastQualifiers();
1894 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001895
1896 // Check if we've already instantiated this type.
1897 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001898 ExtQuals::Profile(ID, baseType, quals);
1899 void *insertPos = 0;
1900 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1901 assert(eq->getQualifiers() == quals);
1902 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001903 }
1904
John McCall33ddac02011-01-19 10:06:00 +00001905 // If the base type is not canonical, make the appropriate canonical type.
1906 QualType canon;
1907 if (!baseType->isCanonicalUnqualified()) {
1908 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00001909 canonSplit.Quals.addConsistentQualifiers(quals);
1910 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00001911
1912 // Re-find the insert position.
1913 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1914 }
1915
1916 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1917 ExtQualNodes.InsertNode(eq, insertPos);
1918 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001919}
1920
Jay Foad39c79802011-01-12 09:06:06 +00001921QualType
1922ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001923 QualType CanT = getCanonicalType(T);
1924 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001925 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001926
John McCall8ccfcb52009-09-24 19:53:00 +00001927 // If we are composing extended qualifiers together, merge together
1928 // into one ExtQuals node.
1929 QualifierCollector Quals;
1930 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001931
John McCall8ccfcb52009-09-24 19:53:00 +00001932 // If this type already has an address space specified, it cannot get
1933 // another one.
1934 assert(!Quals.hasAddressSpace() &&
1935 "Type cannot be in multiple addr spaces!");
1936 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001937
John McCall8ccfcb52009-09-24 19:53:00 +00001938 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001939}
1940
Chris Lattnerd60183d2009-02-18 22:53:11 +00001941QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001942 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001943 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001944 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001945 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001946
John McCall53fa7142010-12-24 02:08:15 +00001947 if (const PointerType *ptr = T->getAs<PointerType>()) {
1948 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001949 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001950 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1951 return getPointerType(ResultType);
1952 }
1953 }
Mike Stump11289f42009-09-09 15:08:12 +00001954
John McCall8ccfcb52009-09-24 19:53:00 +00001955 // If we are composing extended qualifiers together, merge together
1956 // into one ExtQuals node.
1957 QualifierCollector Quals;
1958 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001959
John McCall8ccfcb52009-09-24 19:53:00 +00001960 // If this type already has an ObjCGC specified, it cannot get
1961 // another one.
1962 assert(!Quals.hasObjCGCAttr() &&
1963 "Type cannot have multiple ObjCGCs!");
1964 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001965
John McCall8ccfcb52009-09-24 19:53:00 +00001966 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001967}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001968
John McCall4f5019e2010-12-19 02:44:49 +00001969const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1970 FunctionType::ExtInfo Info) {
1971 if (T->getExtInfo() == Info)
1972 return T;
1973
1974 QualType Result;
1975 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1976 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1977 } else {
1978 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1979 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1980 EPI.ExtInfo = Info;
Jordan Rose5c382722013-03-08 21:51:21 +00001981 Result = getFunctionType(FPT->getResultType(),
1982 ArrayRef<QualType>(FPT->arg_type_begin(),
1983 FPT->getNumArgs()),
1984 EPI);
John McCall4f5019e2010-12-19 02:44:49 +00001985 }
1986
1987 return cast<FunctionType>(Result.getTypePtr());
1988}
1989
Chris Lattnerc6395932007-06-22 20:56:16 +00001990/// getComplexType - Return the uniqued reference to the type for a complex
1991/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001992QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00001993 // Unique pointers, to guarantee there is only one pointer of a particular
1994 // structure.
1995 llvm::FoldingSetNodeID ID;
1996 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001997
Chris Lattnerc6395932007-06-22 20:56:16 +00001998 void *InsertPos = 0;
1999 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2000 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002001
Chris Lattnerc6395932007-06-22 20:56:16 +00002002 // If the pointee type isn't canonical, this won't be a canonical type either,
2003 // so fill in the canonical type field.
2004 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002005 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002006 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002007
Chris Lattnerc6395932007-06-22 20:56:16 +00002008 // Get the new insert position for the node we care about.
2009 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002010 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002011 }
John McCall90d1c2d2009-09-24 23:30:46 +00002012 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002013 Types.push_back(New);
2014 ComplexTypes.InsertNode(New, InsertPos);
2015 return QualType(New, 0);
2016}
2017
Chris Lattner970e54e2006-11-12 00:37:36 +00002018/// getPointerType - Return the uniqued reference to the type for a pointer to
2019/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002020QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002021 // Unique pointers, to guarantee there is only one pointer of a particular
2022 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002023 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002024 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002025
Chris Lattner67521df2007-01-27 01:29:36 +00002026 void *InsertPos = 0;
2027 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002028 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002029
Chris Lattner7ccecb92006-11-12 08:50:50 +00002030 // If the pointee type isn't canonical, this won't be a canonical type either,
2031 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002032 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002033 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002034 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002035
Bob Wilsonc8541f22013-03-15 17:12:43 +00002036 // Get the new insert position for the node we care about.
2037 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2038 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2039 }
John McCall90d1c2d2009-09-24 23:30:46 +00002040 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002041 Types.push_back(New);
2042 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002043 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002044}
2045
Mike Stump11289f42009-09-09 15:08:12 +00002046/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002047/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002048QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002049 assert(T->isFunctionType() && "block of function types only");
2050 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002051 // structure.
2052 llvm::FoldingSetNodeID ID;
2053 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002054
Steve Naroffec33ed92008-08-27 16:04:49 +00002055 void *InsertPos = 0;
2056 if (BlockPointerType *PT =
2057 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2058 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002059
2060 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002061 // type either so fill in the canonical type field.
2062 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002063 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002064 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002065
Steve Naroffec33ed92008-08-27 16:04:49 +00002066 // Get the new insert position for the node we care about.
2067 BlockPointerType *NewIP =
2068 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002069 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002070 }
John McCall90d1c2d2009-09-24 23:30:46 +00002071 BlockPointerType *New
2072 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002073 Types.push_back(New);
2074 BlockPointerTypes.InsertNode(New, InsertPos);
2075 return QualType(New, 0);
2076}
2077
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002078/// getLValueReferenceType - Return the uniqued reference to the type for an
2079/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002080QualType
2081ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002082 assert(getCanonicalType(T) != OverloadTy &&
2083 "Unresolved overloaded function type");
2084
Bill Wendling3708c182007-05-27 10:15:43 +00002085 // Unique pointers, to guarantee there is only one pointer of a particular
2086 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002087 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002088 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002089
2090 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002091 if (LValueReferenceType *RT =
2092 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002093 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002094
John McCallfc93cf92009-10-22 22:37:11 +00002095 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2096
Bill Wendling3708c182007-05-27 10:15:43 +00002097 // If the referencee type isn't canonical, this won't be a canonical type
2098 // either, so fill in the canonical type field.
2099 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002100 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2101 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2102 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002103
Bill Wendling3708c182007-05-27 10:15:43 +00002104 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002105 LValueReferenceType *NewIP =
2106 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002107 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002108 }
2109
John McCall90d1c2d2009-09-24 23:30:46 +00002110 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002111 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2112 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002113 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002114 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002115
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002116 return QualType(New, 0);
2117}
2118
2119/// getRValueReferenceType - Return the uniqued reference to the type for an
2120/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002121QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002122 // Unique pointers, to guarantee there is only one pointer of a particular
2123 // structure.
2124 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002125 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002126
2127 void *InsertPos = 0;
2128 if (RValueReferenceType *RT =
2129 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2130 return QualType(RT, 0);
2131
John McCallfc93cf92009-10-22 22:37:11 +00002132 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2133
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002134 // If the referencee type isn't canonical, this won't be a canonical type
2135 // either, so fill in the canonical type field.
2136 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002137 if (InnerRef || !T.isCanonical()) {
2138 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2139 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002140
2141 // Get the new insert position for the node we care about.
2142 RValueReferenceType *NewIP =
2143 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002144 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002145 }
2146
John McCall90d1c2d2009-09-24 23:30:46 +00002147 RValueReferenceType *New
2148 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002149 Types.push_back(New);
2150 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002151 return QualType(New, 0);
2152}
2153
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002154/// getMemberPointerType - Return the uniqued reference to the type for a
2155/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002156QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002157 // Unique pointers, to guarantee there is only one pointer of a particular
2158 // structure.
2159 llvm::FoldingSetNodeID ID;
2160 MemberPointerType::Profile(ID, T, Cls);
2161
2162 void *InsertPos = 0;
2163 if (MemberPointerType *PT =
2164 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2165 return QualType(PT, 0);
2166
2167 // If the pointee or class type isn't canonical, this won't be a canonical
2168 // type either, so fill in the canonical type field.
2169 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002170 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002171 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2172
2173 // Get the new insert position for the node we care about.
2174 MemberPointerType *NewIP =
2175 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002176 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002177 }
John McCall90d1c2d2009-09-24 23:30:46 +00002178 MemberPointerType *New
2179 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002180 Types.push_back(New);
2181 MemberPointerTypes.InsertNode(New, InsertPos);
2182 return QualType(New, 0);
2183}
2184
Mike Stump11289f42009-09-09 15:08:12 +00002185/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002186/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002187QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002188 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002189 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002190 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002191 assert((EltTy->isDependentType() ||
2192 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002193 "Constant array of VLAs is illegal!");
2194
Chris Lattnere2df3f92009-05-13 04:12:56 +00002195 // Convert the array size into a canonical width matching the pointer size for
2196 // the target.
2197 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002198 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002199 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002200
Chris Lattner23b7eb62007-06-15 23:05:46 +00002201 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002202 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002203
Chris Lattner36f8e652007-01-27 08:31:04 +00002204 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002205 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002206 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002207 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002208
John McCall33ddac02011-01-19 10:06:00 +00002209 // If the element type isn't canonical or has qualifiers, this won't
2210 // be a canonical type either, so fill in the canonical type field.
2211 QualType Canon;
2212 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2213 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002214 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002215 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002216 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002217
Chris Lattner36f8e652007-01-27 08:31:04 +00002218 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002219 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002220 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002221 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002222 }
Mike Stump11289f42009-09-09 15:08:12 +00002223
John McCall90d1c2d2009-09-24 23:30:46 +00002224 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002225 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002226 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002227 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002228 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002229}
2230
John McCall06549462011-01-18 08:40:38 +00002231/// getVariableArrayDecayedType - Turns the given type, which may be
2232/// variably-modified, into the corresponding type with all the known
2233/// sizes replaced with [*].
2234QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2235 // Vastly most common case.
2236 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002237
John McCall06549462011-01-18 08:40:38 +00002238 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002239
John McCall06549462011-01-18 08:40:38 +00002240 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002241 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002242 switch (ty->getTypeClass()) {
2243#define TYPE(Class, Base)
2244#define ABSTRACT_TYPE(Class, Base)
2245#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2246#include "clang/AST/TypeNodes.def"
2247 llvm_unreachable("didn't desugar past all non-canonical types?");
2248
2249 // These types should never be variably-modified.
2250 case Type::Builtin:
2251 case Type::Complex:
2252 case Type::Vector:
2253 case Type::ExtVector:
2254 case Type::DependentSizedExtVector:
2255 case Type::ObjCObject:
2256 case Type::ObjCInterface:
2257 case Type::ObjCObjectPointer:
2258 case Type::Record:
2259 case Type::Enum:
2260 case Type::UnresolvedUsing:
2261 case Type::TypeOfExpr:
2262 case Type::TypeOf:
2263 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002264 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002265 case Type::DependentName:
2266 case Type::InjectedClassName:
2267 case Type::TemplateSpecialization:
2268 case Type::DependentTemplateSpecialization:
2269 case Type::TemplateTypeParm:
2270 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002271 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002272 case Type::PackExpansion:
2273 llvm_unreachable("type should never be variably-modified");
2274
2275 // These types can be variably-modified but should never need to
2276 // further decay.
2277 case Type::FunctionNoProto:
2278 case Type::FunctionProto:
2279 case Type::BlockPointer:
2280 case Type::MemberPointer:
2281 return type;
2282
2283 // These types can be variably-modified. All these modifications
2284 // preserve structure except as noted by comments.
2285 // TODO: if we ever care about optimizing VLAs, there are no-op
2286 // optimizations available here.
2287 case Type::Pointer:
2288 result = getPointerType(getVariableArrayDecayedType(
2289 cast<PointerType>(ty)->getPointeeType()));
2290 break;
2291
2292 case Type::LValueReference: {
2293 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2294 result = getLValueReferenceType(
2295 getVariableArrayDecayedType(lv->getPointeeType()),
2296 lv->isSpelledAsLValue());
2297 break;
2298 }
2299
2300 case Type::RValueReference: {
2301 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2302 result = getRValueReferenceType(
2303 getVariableArrayDecayedType(lv->getPointeeType()));
2304 break;
2305 }
2306
Eli Friedman0dfb8892011-10-06 23:00:33 +00002307 case Type::Atomic: {
2308 const AtomicType *at = cast<AtomicType>(ty);
2309 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2310 break;
2311 }
2312
John McCall06549462011-01-18 08:40:38 +00002313 case Type::ConstantArray: {
2314 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2315 result = getConstantArrayType(
2316 getVariableArrayDecayedType(cat->getElementType()),
2317 cat->getSize(),
2318 cat->getSizeModifier(),
2319 cat->getIndexTypeCVRQualifiers());
2320 break;
2321 }
2322
2323 case Type::DependentSizedArray: {
2324 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2325 result = getDependentSizedArrayType(
2326 getVariableArrayDecayedType(dat->getElementType()),
2327 dat->getSizeExpr(),
2328 dat->getSizeModifier(),
2329 dat->getIndexTypeCVRQualifiers(),
2330 dat->getBracketsRange());
2331 break;
2332 }
2333
2334 // Turn incomplete types into [*] types.
2335 case Type::IncompleteArray: {
2336 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2337 result = getVariableArrayType(
2338 getVariableArrayDecayedType(iat->getElementType()),
2339 /*size*/ 0,
2340 ArrayType::Normal,
2341 iat->getIndexTypeCVRQualifiers(),
2342 SourceRange());
2343 break;
2344 }
2345
2346 // Turn VLA types into [*] types.
2347 case Type::VariableArray: {
2348 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2349 result = getVariableArrayType(
2350 getVariableArrayDecayedType(vat->getElementType()),
2351 /*size*/ 0,
2352 ArrayType::Star,
2353 vat->getIndexTypeCVRQualifiers(),
2354 vat->getBracketsRange());
2355 break;
2356 }
2357 }
2358
2359 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002360 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002361}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002362
Steve Naroffcadebd02007-08-30 18:14:25 +00002363/// getVariableArrayType - Returns a non-unique reference to the type for a
2364/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002365QualType ASTContext::getVariableArrayType(QualType EltTy,
2366 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002367 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002368 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002369 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002370 // Since we don't unique expressions, it isn't possible to unique VLA's
2371 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002372 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002373
John McCall33ddac02011-01-19 10:06:00 +00002374 // Be sure to pull qualifiers off the element type.
2375 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2376 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002377 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002378 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002379 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002380 }
2381
John McCall90d1c2d2009-09-24 23:30:46 +00002382 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002383 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002384
2385 VariableArrayTypes.push_back(New);
2386 Types.push_back(New);
2387 return QualType(New, 0);
2388}
2389
Douglas Gregor4619e432008-12-05 23:32:09 +00002390/// getDependentSizedArrayType - Returns a non-unique reference to
2391/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002392/// type.
John McCall33ddac02011-01-19 10:06:00 +00002393QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2394 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002395 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002396 unsigned elementTypeQuals,
2397 SourceRange brackets) const {
2398 assert((!numElements || numElements->isTypeDependent() ||
2399 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002400 "Size must be type- or value-dependent!");
2401
John McCall33ddac02011-01-19 10:06:00 +00002402 // Dependently-sized array types that do not have a specified number
2403 // of elements will have their sizes deduced from a dependent
2404 // initializer. We do no canonicalization here at all, which is okay
2405 // because they can't be used in most locations.
2406 if (!numElements) {
2407 DependentSizedArrayType *newType
2408 = new (*this, TypeAlignment)
2409 DependentSizedArrayType(*this, elementType, QualType(),
2410 numElements, ASM, elementTypeQuals,
2411 brackets);
2412 Types.push_back(newType);
2413 return QualType(newType, 0);
2414 }
2415
2416 // Otherwise, we actually build a new type every time, but we
2417 // also build a canonical type.
2418
2419 SplitQualType canonElementType = getCanonicalType(elementType).split();
2420
2421 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002422 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002423 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002424 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002425 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002426
John McCall33ddac02011-01-19 10:06:00 +00002427 // Look for an existing type with these properties.
2428 DependentSizedArrayType *canonTy =
2429 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002430
John McCall33ddac02011-01-19 10:06:00 +00002431 // If we don't have one, build one.
2432 if (!canonTy) {
2433 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002434 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002435 QualType(), numElements, ASM, elementTypeQuals,
2436 brackets);
2437 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2438 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002439 }
2440
John McCall33ddac02011-01-19 10:06:00 +00002441 // Apply qualifiers from the element type to the array.
2442 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002443 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002444
John McCall33ddac02011-01-19 10:06:00 +00002445 // If we didn't need extra canonicalization for the element type,
2446 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00002447 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00002448 return canon;
2449
2450 // Otherwise, we need to build a type which follows the spelling
2451 // of the element type.
2452 DependentSizedArrayType *sugaredType
2453 = new (*this, TypeAlignment)
2454 DependentSizedArrayType(*this, elementType, canon, numElements,
2455 ASM, elementTypeQuals, brackets);
2456 Types.push_back(sugaredType);
2457 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002458}
2459
John McCall33ddac02011-01-19 10:06:00 +00002460QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002461 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002462 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002463 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002464 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002465
John McCall33ddac02011-01-19 10:06:00 +00002466 void *insertPos = 0;
2467 if (IncompleteArrayType *iat =
2468 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2469 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002470
2471 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002472 // either, so fill in the canonical type field. We also have to pull
2473 // qualifiers off the element type.
2474 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002475
John McCall33ddac02011-01-19 10:06:00 +00002476 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2477 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002478 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002479 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002480 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002481
2482 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002483 IncompleteArrayType *existing =
2484 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2485 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002486 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002487
John McCall33ddac02011-01-19 10:06:00 +00002488 IncompleteArrayType *newType = new (*this, TypeAlignment)
2489 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002490
John McCall33ddac02011-01-19 10:06:00 +00002491 IncompleteArrayTypes.InsertNode(newType, insertPos);
2492 Types.push_back(newType);
2493 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002494}
2495
Steve Naroff91fcddb2007-07-18 18:00:27 +00002496/// getVectorType - Return the unique reference to a vector type of
2497/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002498QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002499 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002500 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002501
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002502 // Check if we've already instantiated a vector of this type.
2503 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002504 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002505
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002506 void *InsertPos = 0;
2507 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2508 return QualType(VTP, 0);
2509
2510 // If the element type isn't canonical, this won't be a canonical type either,
2511 // so fill in the canonical type field.
2512 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002513 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002514 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002515
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002516 // Get the new insert position for the node we care about.
2517 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002518 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002519 }
John McCall90d1c2d2009-09-24 23:30:46 +00002520 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002521 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002522 VectorTypes.InsertNode(New, InsertPos);
2523 Types.push_back(New);
2524 return QualType(New, 0);
2525}
2526
Nate Begemance4d7fc2008-04-18 23:10:10 +00002527/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002528/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002529QualType
2530ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002531 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002532
Steve Naroff91fcddb2007-07-18 18:00:27 +00002533 // Check if we've already instantiated a vector of this type.
2534 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002535 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002536 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002537 void *InsertPos = 0;
2538 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2539 return QualType(VTP, 0);
2540
2541 // If the element type isn't canonical, this won't be a canonical type either,
2542 // so fill in the canonical type field.
2543 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002544 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002545 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002546
Steve Naroff91fcddb2007-07-18 18:00:27 +00002547 // Get the new insert position for the node we care about.
2548 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002549 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002550 }
John McCall90d1c2d2009-09-24 23:30:46 +00002551 ExtVectorType *New = new (*this, TypeAlignment)
2552 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002553 VectorTypes.InsertNode(New, InsertPos);
2554 Types.push_back(New);
2555 return QualType(New, 0);
2556}
2557
Jay Foad39c79802011-01-12 09:06:06 +00002558QualType
2559ASTContext::getDependentSizedExtVectorType(QualType vecType,
2560 Expr *SizeExpr,
2561 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002562 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002563 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002564 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002565
Douglas Gregor352169a2009-07-31 03:54:25 +00002566 void *InsertPos = 0;
2567 DependentSizedExtVectorType *Canon
2568 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2569 DependentSizedExtVectorType *New;
2570 if (Canon) {
2571 // We already have a canonical version of this array type; use it as
2572 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002573 New = new (*this, TypeAlignment)
2574 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2575 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002576 } else {
2577 QualType CanonVecTy = getCanonicalType(vecType);
2578 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002579 New = new (*this, TypeAlignment)
2580 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2581 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002582
2583 DependentSizedExtVectorType *CanonCheck
2584 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2585 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2586 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002587 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2588 } else {
2589 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2590 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002591 New = new (*this, TypeAlignment)
2592 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002593 }
2594 }
Mike Stump11289f42009-09-09 15:08:12 +00002595
Douglas Gregor758a8692009-06-17 21:51:59 +00002596 Types.push_back(New);
2597 return QualType(New, 0);
2598}
2599
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002600/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002601///
Jay Foad39c79802011-01-12 09:06:06 +00002602QualType
2603ASTContext::getFunctionNoProtoType(QualType ResultTy,
2604 const FunctionType::ExtInfo &Info) const {
Roman Divacky65b88cd2011-03-01 17:40:53 +00002605 const CallingConv DefaultCC = Info.getCC();
2606 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2607 CC_X86StdCall : DefaultCC;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002608 // Unique functions, to guarantee there is only one function of a particular
2609 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002610 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002611 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002612
Chris Lattner47955de2007-01-27 08:37:20 +00002613 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002614 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002615 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002616 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002617
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002618 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00002619 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00002620 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002621 Canonical =
2622 getFunctionNoProtoType(getCanonicalType(ResultTy),
2623 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00002624
Chris Lattner47955de2007-01-27 08:37:20 +00002625 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002626 FunctionNoProtoType *NewIP =
2627 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002628 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002629 }
Mike Stump11289f42009-09-09 15:08:12 +00002630
Roman Divacky65b88cd2011-03-01 17:40:53 +00002631 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002632 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002633 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002634 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002635 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002636 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002637}
2638
Douglas Gregorcd780372013-01-17 23:36:45 +00002639/// \brief Determine whether \p T is canonical as the result type of a function.
2640static bool isCanonicalResultType(QualType T) {
2641 return T.isCanonical() &&
2642 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2643 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2644}
2645
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002646/// getFunctionType - Return a normal function type with a typed argument
2647/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00002648QualType
Jordan Rose5c382722013-03-08 21:51:21 +00002649ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad39c79802011-01-12 09:06:06 +00002650 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rose5c382722013-03-08 21:51:21 +00002651 size_t NumArgs = ArgArray.size();
2652
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002653 // Unique functions, to guarantee there is only one function of a particular
2654 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002655 llvm::FoldingSetNodeID ID;
Jordan Rose5c382722013-03-08 21:51:21 +00002656 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
2657 *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002658
2659 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002660 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002661 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002662 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002663
2664 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002665 bool isCanonical =
Douglas Gregorcd780372013-01-17 23:36:45 +00002666 EPI.ExceptionSpecType == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smith5e580292012-02-10 09:58:53 +00002667 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002668 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002669 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002670 isCanonical = false;
2671
Roman Divacky65b88cd2011-03-01 17:40:53 +00002672 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2673 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2674 CC_X86StdCall : DefaultCC;
John McCalldb40c7f2010-12-14 08:05:40 +00002675
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002676 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002677 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002678 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00002679 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002680 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002681 CanonicalArgs.reserve(NumArgs);
2682 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002683 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002684
John McCalldb40c7f2010-12-14 08:05:40 +00002685 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002686 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002687 CanonicalEPI.ExceptionSpecType = EST_None;
2688 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002689 CanonicalEPI.ExtInfo
2690 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2691
Douglas Gregorcd780372013-01-17 23:36:45 +00002692 // Result types do not have ARC lifetime qualifiers.
2693 QualType CanResultTy = getCanonicalType(ResultTy);
2694 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2695 Qualifiers Qs = CanResultTy.getQualifiers();
2696 Qs.removeObjCLifetime();
2697 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2698 }
2699
Jordan Rose5c382722013-03-08 21:51:21 +00002700 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002701
Chris Lattnerfd4de792007-01-27 01:15:32 +00002702 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002703 FunctionProtoType *NewIP =
2704 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002705 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002706 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002707
John McCall31168b02011-06-15 23:02:42 +00002708 // FunctionProtoType objects are allocated with extra bytes after
2709 // them for three variable size arrays at the end:
2710 // - parameter types
2711 // - exception types
2712 // - consumed-arguments flags
2713 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00002714 // expression, or information used to resolve the exception
2715 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00002716 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002717 NumArgs * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002718 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002719 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002720 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002721 Size += sizeof(Expr*);
Richard Smithf623c962012-04-17 00:58:00 +00002722 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00002723 Size += 2 * sizeof(FunctionDecl*);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002724 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2725 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002726 }
John McCall31168b02011-06-15 23:02:42 +00002727 if (EPI.ConsumedArguments)
2728 Size += NumArgs * sizeof(bool);
2729
John McCalldb40c7f2010-12-14 08:05:40 +00002730 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002731 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2732 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Jordan Rose5c382722013-03-08 21:51:21 +00002733 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002734 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002735 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002736 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002737}
Chris Lattneref51c202006-11-10 07:17:23 +00002738
John McCalle78aac42010-03-10 03:28:59 +00002739#ifndef NDEBUG
2740static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2741 if (!isa<CXXRecordDecl>(D)) return false;
2742 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2743 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2744 return true;
2745 if (RD->getDescribedClassTemplate() &&
2746 !isa<ClassTemplateSpecializationDecl>(RD))
2747 return true;
2748 return false;
2749}
2750#endif
2751
2752/// getInjectedClassNameType - Return the unique reference to the
2753/// injected class name type for the specified templated declaration.
2754QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002755 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002756 assert(NeedsInjectedClassNameType(Decl));
2757 if (Decl->TypeForDecl) {
2758 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00002759 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00002760 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2761 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2762 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2763 } else {
John McCall424cec92011-01-19 06:33:43 +00002764 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002765 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002766 Decl->TypeForDecl = newType;
2767 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002768 }
2769 return QualType(Decl->TypeForDecl, 0);
2770}
2771
Douglas Gregor83a586e2008-04-13 21:07:44 +00002772/// getTypeDeclType - Return the unique reference to the type for the
2773/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002774QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002775 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002776 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002777
Richard Smithdda56e42011-04-15 14:24:37 +00002778 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002779 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002780
John McCall96f0b5f2010-03-10 06:48:02 +00002781 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2782 "Template type parameter types are always available.");
2783
John McCall81e38502010-02-16 03:57:14 +00002784 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002785 assert(!Record->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002786 "struct/union has previous declaration");
2787 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002788 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002789 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002790 assert(!Enum->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002791 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002792 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002793 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002794 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002795 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2796 Decl->TypeForDecl = newType;
2797 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002798 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002799 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002800
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002801 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002802}
2803
Chris Lattner32d920b2007-01-26 02:01:53 +00002804/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002805/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002806QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002807ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2808 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002809 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002810
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002811 if (Canonical.isNull())
2812 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002813 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002814 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002815 Decl->TypeForDecl = newType;
2816 Types.push_back(newType);
2817 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002818}
2819
Jay Foad39c79802011-01-12 09:06:06 +00002820QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002821 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2822
Douglas Gregorec9fd132012-01-14 16:38:05 +00002823 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002824 if (PrevDecl->TypeForDecl)
2825 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2826
John McCall424cec92011-01-19 06:33:43 +00002827 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2828 Decl->TypeForDecl = newType;
2829 Types.push_back(newType);
2830 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002831}
2832
Jay Foad39c79802011-01-12 09:06:06 +00002833QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002834 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2835
Douglas Gregorec9fd132012-01-14 16:38:05 +00002836 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002837 if (PrevDecl->TypeForDecl)
2838 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2839
John McCall424cec92011-01-19 06:33:43 +00002840 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2841 Decl->TypeForDecl = newType;
2842 Types.push_back(newType);
2843 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002844}
2845
John McCall81904512011-01-06 01:58:22 +00002846QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2847 QualType modifiedType,
2848 QualType equivalentType) {
2849 llvm::FoldingSetNodeID id;
2850 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2851
2852 void *insertPos = 0;
2853 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2854 if (type) return QualType(type, 0);
2855
2856 QualType canon = getCanonicalType(equivalentType);
2857 type = new (*this, TypeAlignment)
2858 AttributedType(canon, attrKind, modifiedType, equivalentType);
2859
2860 Types.push_back(type);
2861 AttributedTypes.InsertNode(type, insertPos);
2862
2863 return QualType(type, 0);
2864}
2865
2866
John McCallcebee162009-10-18 09:09:24 +00002867/// \brief Retrieve a substitution-result type.
2868QualType
2869ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00002870 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00002871 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00002872 && "replacement types must always be canonical");
2873
2874 llvm::FoldingSetNodeID ID;
2875 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2876 void *InsertPos = 0;
2877 SubstTemplateTypeParmType *SubstParm
2878 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2879
2880 if (!SubstParm) {
2881 SubstParm = new (*this, TypeAlignment)
2882 SubstTemplateTypeParmType(Parm, Replacement);
2883 Types.push_back(SubstParm);
2884 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2885 }
2886
2887 return QualType(SubstParm, 0);
2888}
2889
Douglas Gregorada4b792011-01-14 02:55:32 +00002890/// \brief Retrieve a
2891QualType ASTContext::getSubstTemplateTypeParmPackType(
2892 const TemplateTypeParmType *Parm,
2893 const TemplateArgument &ArgPack) {
2894#ifndef NDEBUG
2895 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2896 PEnd = ArgPack.pack_end();
2897 P != PEnd; ++P) {
2898 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2899 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2900 }
2901#endif
2902
2903 llvm::FoldingSetNodeID ID;
2904 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2905 void *InsertPos = 0;
2906 if (SubstTemplateTypeParmPackType *SubstParm
2907 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2908 return QualType(SubstParm, 0);
2909
2910 QualType Canon;
2911 if (!Parm->isCanonicalUnqualified()) {
2912 Canon = getCanonicalType(QualType(Parm, 0));
2913 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2914 ArgPack);
2915 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2916 }
2917
2918 SubstTemplateTypeParmPackType *SubstParm
2919 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2920 ArgPack);
2921 Types.push_back(SubstParm);
2922 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2923 return QualType(SubstParm, 0);
2924}
2925
Douglas Gregoreff93e02009-02-05 23:33:38 +00002926/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00002927/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00002928/// name.
Mike Stump11289f42009-09-09 15:08:12 +00002929QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00002930 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00002931 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00002932 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00002933 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002934 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002935 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00002936 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2937
2938 if (TypeParm)
2939 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002940
Chandler Carruth08836322011-05-01 00:51:33 +00002941 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00002942 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00002943 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002944
2945 TemplateTypeParmType *TypeCheck
2946 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2947 assert(!TypeCheck && "Template type parameter canonical type broken");
2948 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002949 } else
John McCall90d1c2d2009-09-24 23:30:46 +00002950 TypeParm = new (*this, TypeAlignment)
2951 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002952
2953 Types.push_back(TypeParm);
2954 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2955
2956 return QualType(TypeParm, 0);
2957}
2958
John McCalle78aac42010-03-10 03:28:59 +00002959TypeSourceInfo *
2960ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2961 SourceLocation NameLoc,
2962 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002963 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002964 assert(!Name.getAsDependentTemplateName() &&
2965 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002966 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00002967
2968 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00002969 TemplateSpecializationTypeLoc TL =
2970 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002971 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00002972 TL.setTemplateNameLoc(NameLoc);
2973 TL.setLAngleLoc(Args.getLAngleLoc());
2974 TL.setRAngleLoc(Args.getRAngleLoc());
2975 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2976 TL.setArgLocInfo(i, Args[i].getLocInfo());
2977 return DI;
2978}
2979
Mike Stump11289f42009-09-09 15:08:12 +00002980QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002981ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002982 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002983 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002984 assert(!Template.getAsDependentTemplateName() &&
2985 "No dependent template names here!");
2986
John McCall6b51f282009-11-23 01:53:49 +00002987 unsigned NumArgs = Args.size();
2988
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002989 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00002990 ArgVec.reserve(NumArgs);
2991 for (unsigned i = 0; i != NumArgs; ++i)
2992 ArgVec.push_back(Args[i].getArgument());
2993
John McCall2408e322010-04-27 00:57:59 +00002994 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002995 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00002996}
2997
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002998#ifndef NDEBUG
2999static bool hasAnyPackExpansions(const TemplateArgument *Args,
3000 unsigned NumArgs) {
3001 for (unsigned I = 0; I != NumArgs; ++I)
3002 if (Args[I].isPackExpansion())
3003 return true;
3004
3005 return true;
3006}
3007#endif
3008
John McCall0ad16662009-10-29 08:12:44 +00003009QualType
3010ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00003011 const TemplateArgument *Args,
3012 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003013 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003014 assert(!Template.getAsDependentTemplateName() &&
3015 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003016 // Look through qualified template names.
3017 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3018 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003019
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003020 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003021 Template.getAsTemplateDecl() &&
3022 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003023 QualType CanonType;
3024 if (!Underlying.isNull())
3025 CanonType = getCanonicalType(Underlying);
3026 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003027 // We can get here with an alias template when the specialization contains
3028 // a pack expansion that does not match up with a parameter pack.
3029 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3030 "Caller must compute aliased type");
3031 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003032 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3033 NumArgs);
3034 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003035
Douglas Gregora8e02e72009-07-28 23:00:59 +00003036 // Allocate the (non-canonical) template specialization type, but don't
3037 // try to unique it: these types typically have location information that
3038 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003039 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3040 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003041 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003042 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003043 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003044 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3045 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003046
Douglas Gregor8bf42052009-02-09 18:46:07 +00003047 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003048 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003049}
3050
Mike Stump11289f42009-09-09 15:08:12 +00003051QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003052ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3053 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00003054 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003055 assert(!Template.getAsDependentTemplateName() &&
3056 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003057
Douglas Gregore29139c2011-03-03 17:04:51 +00003058 // Look through qualified template names.
3059 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3060 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003061
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003062 // Build the canonical template specialization type.
3063 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003064 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003065 CanonArgs.reserve(NumArgs);
3066 for (unsigned I = 0; I != NumArgs; ++I)
3067 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3068
3069 // Determine whether this canonical template specialization type already
3070 // exists.
3071 llvm::FoldingSetNodeID ID;
3072 TemplateSpecializationType::Profile(ID, CanonTemplate,
3073 CanonArgs.data(), NumArgs, *this);
3074
3075 void *InsertPos = 0;
3076 TemplateSpecializationType *Spec
3077 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3078
3079 if (!Spec) {
3080 // Allocate a new canonical template specialization type.
3081 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3082 sizeof(TemplateArgument) * NumArgs),
3083 TypeAlignment);
3084 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3085 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003086 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003087 Types.push_back(Spec);
3088 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3089 }
3090
3091 assert(Spec->isDependentType() &&
3092 "Non-dependent template-id type must have a canonical type");
3093 return QualType(Spec, 0);
3094}
3095
3096QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003097ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3098 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003099 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003100 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003101 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003102
3103 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003104 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003105 if (T)
3106 return QualType(T, 0);
3107
Douglas Gregorc42075a2010-02-04 18:10:26 +00003108 QualType Canon = NamedType;
3109 if (!Canon.isCanonical()) {
3110 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003111 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3112 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003113 (void)CheckT;
3114 }
3115
Abramo Bagnara6150c882010-05-11 21:36:43 +00003116 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003117 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003118 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003119 return QualType(T, 0);
3120}
3121
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003122QualType
Jay Foad39c79802011-01-12 09:06:06 +00003123ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003124 llvm::FoldingSetNodeID ID;
3125 ParenType::Profile(ID, InnerType);
3126
3127 void *InsertPos = 0;
3128 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3129 if (T)
3130 return QualType(T, 0);
3131
3132 QualType Canon = InnerType;
3133 if (!Canon.isCanonical()) {
3134 Canon = getCanonicalType(InnerType);
3135 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3136 assert(!CheckT && "Paren canonical type broken");
3137 (void)CheckT;
3138 }
3139
3140 T = new (*this) ParenType(InnerType, Canon);
3141 Types.push_back(T);
3142 ParenTypes.InsertNode(T, InsertPos);
3143 return QualType(T, 0);
3144}
3145
Douglas Gregor02085352010-03-31 20:19:30 +00003146QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3147 NestedNameSpecifier *NNS,
3148 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003149 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003150 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
3151
3152 if (Canon.isNull()) {
3153 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00003154 ElaboratedTypeKeyword CanonKeyword = Keyword;
3155 if (Keyword == ETK_None)
3156 CanonKeyword = ETK_Typename;
3157
3158 if (CanonNNS != NNS || CanonKeyword != Keyword)
3159 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003160 }
3161
3162 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003163 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003164
3165 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003166 DependentNameType *T
3167 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003168 if (T)
3169 return QualType(T, 0);
3170
Douglas Gregor02085352010-03-31 20:19:30 +00003171 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003172 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003173 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003174 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003175}
3176
Mike Stump11289f42009-09-09 15:08:12 +00003177QualType
John McCallc392f372010-06-11 00:33:02 +00003178ASTContext::getDependentTemplateSpecializationType(
3179 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003180 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003181 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003182 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003183 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003184 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003185 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3186 ArgCopy.push_back(Args[I].getArgument());
3187 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3188 ArgCopy.size(),
3189 ArgCopy.data());
3190}
3191
3192QualType
3193ASTContext::getDependentTemplateSpecializationType(
3194 ElaboratedTypeKeyword Keyword,
3195 NestedNameSpecifier *NNS,
3196 const IdentifierInfo *Name,
3197 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00003198 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003199 assert((!NNS || NNS->isDependent()) &&
3200 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003201
Douglas Gregorc42075a2010-02-04 18:10:26 +00003202 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003203 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3204 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003205
3206 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00003207 DependentTemplateSpecializationType *T
3208 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003209 if (T)
3210 return QualType(T, 0);
3211
John McCallc392f372010-06-11 00:33:02 +00003212 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003213
John McCallc392f372010-06-11 00:33:02 +00003214 ElaboratedTypeKeyword CanonKeyword = Keyword;
3215 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3216
3217 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003218 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003219 for (unsigned I = 0; I != NumArgs; ++I) {
3220 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3221 if (!CanonArgs[I].structurallyEquals(Args[I]))
3222 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003223 }
3224
John McCallc392f372010-06-11 00:33:02 +00003225 QualType Canon;
3226 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3227 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3228 Name, NumArgs,
3229 CanonArgs.data());
3230
3231 // Find the insert position again.
3232 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3233 }
3234
3235 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3236 sizeof(TemplateArgument) * NumArgs),
3237 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003238 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00003239 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003240 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003241 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003242 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003243}
3244
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003245QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00003246 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003247 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003248 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003249
3250 assert(Pattern->containsUnexpandedParameterPack() &&
3251 "Pack expansions must expand one or more parameter packs");
3252 void *InsertPos = 0;
3253 PackExpansionType *T
3254 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3255 if (T)
3256 return QualType(T, 0);
3257
3258 QualType Canon;
3259 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003260 Canon = getCanonicalType(Pattern);
3261 // The canonical type might not contain an unexpanded parameter pack, if it
3262 // contains an alias template specialization which ignores one of its
3263 // parameters.
3264 if (Canon->containsUnexpandedParameterPack()) {
3265 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003266
Richard Smith68eea502012-07-16 00:20:35 +00003267 // Find the insert position again, in case we inserted an element into
3268 // PackExpansionTypes and invalidated our insert position.
3269 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3270 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003271 }
3272
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003273 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003274 Types.push_back(T);
3275 PackExpansionTypes.InsertNode(T, InsertPos);
3276 return QualType(T, 0);
3277}
3278
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003279/// CmpProtocolNames - Comparison predicate for sorting protocols
3280/// alphabetically.
3281static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3282 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00003283 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003284}
3285
John McCall8b07ec22010-05-15 11:32:37 +00003286static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00003287 unsigned NumProtocols) {
3288 if (NumProtocols == 0) return true;
3289
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003290 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3291 return false;
3292
John McCallfc93cf92009-10-22 22:37:11 +00003293 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003294 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3295 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003296 return false;
3297 return true;
3298}
3299
3300static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003301 unsigned &NumProtocols) {
3302 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00003303
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003304 // Sort protocols, keyed by name.
3305 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3306
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003307 // Canonicalize.
3308 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3309 Protocols[I] = Protocols[I]->getCanonicalDecl();
3310
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003311 // Remove duplicates.
3312 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3313 NumProtocols = ProtocolsEnd-Protocols;
3314}
3315
John McCall8b07ec22010-05-15 11:32:37 +00003316QualType ASTContext::getObjCObjectType(QualType BaseType,
3317 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003318 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00003319 // If the base type is an interface and there aren't any protocols
3320 // to add, then the interface type will do just fine.
3321 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3322 return BaseType;
3323
3324 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003325 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00003326 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00003327 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00003328 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3329 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003330
John McCall8b07ec22010-05-15 11:32:37 +00003331 // Build the canonical type, which has the canonical base type and
3332 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00003333 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00003334 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3335 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3336 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003337 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003338 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003339 unsigned UniqueCount = NumProtocols;
3340
John McCallfc93cf92009-10-22 22:37:11 +00003341 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00003342 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3343 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00003344 } else {
John McCall8b07ec22010-05-15 11:32:37 +00003345 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3346 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003347 }
3348
3349 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003350 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3351 }
3352
3353 unsigned Size = sizeof(ObjCObjectTypeImpl);
3354 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3355 void *Mem = Allocate(Size, TypeAlignment);
3356 ObjCObjectTypeImpl *T =
3357 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3358
3359 Types.push_back(T);
3360 ObjCObjectTypes.InsertNode(T, InsertPos);
3361 return QualType(T, 0);
3362}
3363
3364/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3365/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003366QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003367 llvm::FoldingSetNodeID ID;
3368 ObjCObjectPointerType::Profile(ID, ObjectT);
3369
3370 void *InsertPos = 0;
3371 if (ObjCObjectPointerType *QT =
3372 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3373 return QualType(QT, 0);
3374
3375 // Find the canonical object type.
3376 QualType Canonical;
3377 if (!ObjectT.isCanonical()) {
3378 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3379
3380 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003381 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3382 }
3383
Douglas Gregorf85bee62010-02-08 22:59:26 +00003384 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003385 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3386 ObjCObjectPointerType *QType =
3387 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003388
Steve Narofffb4330f2009-06-17 22:40:22 +00003389 Types.push_back(QType);
3390 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003391 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003392}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003393
Douglas Gregor1c283312010-08-11 12:19:30 +00003394/// getObjCInterfaceType - Return the unique reference to the type for the
3395/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003396QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3397 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003398 if (Decl->TypeForDecl)
3399 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003400
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003401 if (PrevDecl) {
3402 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3403 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3404 return QualType(PrevDecl->TypeForDecl, 0);
3405 }
3406
Douglas Gregor7671e532011-12-16 16:34:57 +00003407 // Prefer the definition, if there is one.
3408 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3409 Decl = Def;
3410
Douglas Gregor1c283312010-08-11 12:19:30 +00003411 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3412 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3413 Decl->TypeForDecl = T;
3414 Types.push_back(T);
3415 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003416}
3417
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003418/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3419/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003420/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003421/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003422/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003423QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003424 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003425 if (tofExpr->isTypeDependent()) {
3426 llvm::FoldingSetNodeID ID;
3427 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003428
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003429 void *InsertPos = 0;
3430 DependentTypeOfExprType *Canon
3431 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3432 if (Canon) {
3433 // We already have a "canonical" version of an identical, dependent
3434 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003435 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003436 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003437 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003438 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003439 Canon
3440 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003441 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3442 toe = Canon;
3443 }
3444 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003445 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003446 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003447 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003448 Types.push_back(toe);
3449 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003450}
3451
Steve Naroffa773cd52007-08-01 18:02:17 +00003452/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3453/// TypeOfType AST's. The only motivation to unique these nodes would be
3454/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003455/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003456/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003457QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003458 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003459 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003460 Types.push_back(tot);
3461 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003462}
3463
Anders Carlssonad6bd352009-06-24 21:24:56 +00003464
Anders Carlsson81df7b82009-06-24 19:06:50 +00003465/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3466/// DecltypeType AST's. The only motivation to unique these nodes would be
3467/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003468/// an issue. This doesn't effect the type checker, since it operates
David Blaikie876657b2011-11-06 22:28:03 +00003469/// on canonical types (which are always unique).
Douglas Gregor81495f32012-02-12 18:42:33 +00003470QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003471 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003472
3473 // C++0x [temp.type]p2:
3474 // If an expression e involves a template parameter, decltype(e) denotes a
3475 // unique dependent type. Two such decltype-specifiers refer to the same
3476 // type only if their expressions are equivalent (14.5.6.1).
3477 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003478 llvm::FoldingSetNodeID ID;
3479 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003480
Douglas Gregora21f6c32009-07-30 23:36:40 +00003481 void *InsertPos = 0;
3482 DependentDecltypeType *Canon
3483 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3484 if (Canon) {
3485 // We already have a "canonical" version of an equivalent, dependent
3486 // decltype type. Use that as our canonical type.
Richard Smithef8bf432012-08-13 20:08:14 +00003487 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
Douglas Gregora21f6c32009-07-30 23:36:40 +00003488 QualType((DecltypeType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003489 } else {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003490 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003491 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003492 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3493 dt = Canon;
3494 }
3495 } else {
Douglas Gregor81495f32012-02-12 18:42:33 +00003496 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3497 getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003498 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003499 Types.push_back(dt);
3500 return QualType(dt, 0);
3501}
3502
Alexis Hunte852b102011-05-24 22:41:36 +00003503/// getUnaryTransformationType - We don't unique these, since the memory
3504/// savings are minimal and these are rare.
3505QualType ASTContext::getUnaryTransformType(QualType BaseType,
3506 QualType UnderlyingType,
3507 UnaryTransformType::UTTKind Kind)
3508 const {
3509 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003510 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3511 Kind,
3512 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003513 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003514 Types.push_back(Ty);
3515 return QualType(Ty, 0);
3516}
3517
Richard Smithb2bc2e62011-02-21 20:05:19 +00003518/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00003519QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smithb2bc2e62011-02-21 20:05:19 +00003520 void *InsertPos = 0;
3521 if (!DeducedType.isNull()) {
3522 // Look in the folding set for an existing type.
3523 llvm::FoldingSetNodeID ID;
3524 AutoType::Profile(ID, DeducedType);
3525 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3526 return QualType(AT, 0);
3527 }
3528
3529 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
3530 Types.push_back(AT);
3531 if (InsertPos)
3532 AutoTypes.InsertNode(AT, InsertPos);
3533 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003534}
3535
Eli Friedman0dfb8892011-10-06 23:00:33 +00003536/// getAtomicType - Return the uniqued reference to the atomic type for
3537/// the given value type.
3538QualType ASTContext::getAtomicType(QualType T) const {
3539 // Unique pointers, to guarantee there is only one pointer of a particular
3540 // structure.
3541 llvm::FoldingSetNodeID ID;
3542 AtomicType::Profile(ID, T);
3543
3544 void *InsertPos = 0;
3545 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3546 return QualType(AT, 0);
3547
3548 // If the atomic value type isn't canonical, this won't be a canonical type
3549 // either, so fill in the canonical type field.
3550 QualType Canonical;
3551 if (!T.isCanonical()) {
3552 Canonical = getAtomicType(getCanonicalType(T));
3553
3554 // Get the new insert position for the node we care about.
3555 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3556 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3557 }
3558 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3559 Types.push_back(New);
3560 AtomicTypes.InsertNode(New, InsertPos);
3561 return QualType(New, 0);
3562}
3563
Richard Smith02e85f32011-04-14 22:09:26 +00003564/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3565QualType ASTContext::getAutoDeductType() const {
3566 if (AutoDeductTy.isNull())
3567 AutoDeductTy = getAutoType(QualType());
3568 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
3569 return AutoDeductTy;
3570}
3571
3572/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3573QualType ASTContext::getAutoRRefDeductType() const {
3574 if (AutoRRefDeductTy.isNull())
3575 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3576 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3577 return AutoRRefDeductTy;
3578}
3579
Chris Lattnerfb072462007-01-23 05:45:31 +00003580/// getTagDeclType - Return the unique reference to the type for the
3581/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003582QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003583 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003584 // FIXME: What is the design on getTagDeclType when it requires casting
3585 // away const? mutable?
3586 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003587}
3588
Mike Stump11289f42009-09-09 15:08:12 +00003589/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3590/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3591/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003592CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003593 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003594}
Chris Lattnerfb072462007-01-23 05:45:31 +00003595
Hans Wennborg27541db2011-10-27 08:29:09 +00003596/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3597CanQualType ASTContext::getIntMaxType() const {
3598 return getFromTargetType(Target->getIntMaxType());
3599}
3600
3601/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3602CanQualType ASTContext::getUIntMaxType() const {
3603 return getFromTargetType(Target->getUIntMaxType());
3604}
3605
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003606/// getSignedWCharType - Return the type of "signed wchar_t".
3607/// Used when in C++, as a GCC extension.
3608QualType ASTContext::getSignedWCharType() const {
3609 // FIXME: derive from "Target" ?
3610 return WCharTy;
3611}
3612
3613/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3614/// Used when in C++, as a GCC extension.
3615QualType ASTContext::getUnsignedWCharType() const {
3616 // FIXME: derive from "Target" ?
3617 return UnsignedIntTy;
3618}
3619
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00003620QualType ASTContext::getIntPtrType() const {
3621 return getFromTargetType(Target->getIntPtrType());
3622}
3623
3624QualType ASTContext::getUIntPtrType() const {
3625 return getCorrespondingUnsignedType(getIntPtrType());
3626}
3627
Hans Wennborg27541db2011-10-27 08:29:09 +00003628/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003629/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3630QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003631 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003632}
3633
Eli Friedman4e91899e2012-11-27 02:58:24 +00003634/// \brief Return the unique type for "pid_t" defined in
3635/// <sys/types.h>. We need this to compute the correct type for vfork().
3636QualType ASTContext::getProcessIDType() const {
3637 return getFromTargetType(Target->getProcessIDType());
3638}
3639
Chris Lattnera21ad802008-04-02 05:18:44 +00003640//===----------------------------------------------------------------------===//
3641// Type Operators
3642//===----------------------------------------------------------------------===//
3643
Jay Foad39c79802011-01-12 09:06:06 +00003644CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003645 // Push qualifiers into arrays, and then discard any remaining
3646 // qualifiers.
3647 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003648 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003649 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003650 QualType Result;
3651 if (isa<ArrayType>(Ty)) {
3652 Result = getArrayDecayedType(QualType(Ty,0));
3653 } else if (isa<FunctionType>(Ty)) {
3654 Result = getPointerType(QualType(Ty, 0));
3655 } else {
3656 Result = QualType(Ty, 0);
3657 }
3658
3659 return CanQualType::CreateUnsafe(Result);
3660}
3661
John McCall6c9dd522011-01-18 07:41:22 +00003662QualType ASTContext::getUnqualifiedArrayType(QualType type,
3663 Qualifiers &quals) {
3664 SplitQualType splitType = type.getSplitUnqualifiedType();
3665
3666 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3667 // the unqualified desugared type and then drops it on the floor.
3668 // We then have to strip that sugar back off with
3669 // getUnqualifiedDesugaredType(), which is silly.
3670 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003671 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003672
3673 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003674 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003675 quals = splitType.Quals;
3676 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003677 }
3678
John McCall6c9dd522011-01-18 07:41:22 +00003679 // Otherwise, recurse on the array's element type.
3680 QualType elementType = AT->getElementType();
3681 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3682
3683 // If that didn't change the element type, AT has no qualifiers, so we
3684 // can just use the results in splitType.
3685 if (elementType == unqualElementType) {
3686 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00003687 quals = splitType.Quals;
3688 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00003689 }
3690
3691 // Otherwise, add in the qualifiers from the outermost type, then
3692 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00003693 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003694
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003695 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003696 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003697 CAT->getSizeModifier(), 0);
3698 }
3699
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003700 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003701 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003702 }
3703
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003704 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003705 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003706 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003707 VAT->getSizeModifier(),
3708 VAT->getIndexTypeCVRQualifiers(),
3709 VAT->getBracketsRange());
3710 }
3711
3712 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003713 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003714 DSAT->getSizeModifier(), 0,
3715 SourceRange());
3716}
3717
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003718/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3719/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3720/// they point to and return true. If T1 and T2 aren't pointer types
3721/// or pointer-to-member types, or if they are not similar at this
3722/// level, returns false and leaves T1 and T2 unchanged. Top-level
3723/// qualifiers on T1 and T2 are ignored. This function will typically
3724/// be called in a loop that successively "unwraps" pointer and
3725/// pointer-to-member types to compare them at each level.
3726bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3727 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3728 *T2PtrType = T2->getAs<PointerType>();
3729 if (T1PtrType && T2PtrType) {
3730 T1 = T1PtrType->getPointeeType();
3731 T2 = T2PtrType->getPointeeType();
3732 return true;
3733 }
3734
3735 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3736 *T2MPType = T2->getAs<MemberPointerType>();
3737 if (T1MPType && T2MPType &&
3738 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3739 QualType(T2MPType->getClass(), 0))) {
3740 T1 = T1MPType->getPointeeType();
3741 T2 = T2MPType->getPointeeType();
3742 return true;
3743 }
3744
David Blaikiebbafb8a2012-03-11 07:00:24 +00003745 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003746 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3747 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3748 if (T1OPType && T2OPType) {
3749 T1 = T1OPType->getPointeeType();
3750 T2 = T2OPType->getPointeeType();
3751 return true;
3752 }
3753 }
3754
3755 // FIXME: Block pointers, too?
3756
3757 return false;
3758}
3759
Jay Foad39c79802011-01-12 09:06:06 +00003760DeclarationNameInfo
3761ASTContext::getNameForTemplate(TemplateName Name,
3762 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003763 switch (Name.getKind()) {
3764 case TemplateName::QualifiedTemplate:
3765 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003766 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00003767 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3768 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003769
John McCalld9dfe3a2011-06-30 08:33:18 +00003770 case TemplateName::OverloadedTemplate: {
3771 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3772 // DNInfo work in progress: CHECKME: what about DNLoc?
3773 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3774 }
3775
3776 case TemplateName::DependentTemplate: {
3777 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003778 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00003779 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003780 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3781 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00003782 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003783 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3784 // DNInfo work in progress: FIXME: source locations?
3785 DeclarationNameLoc DNLoc;
3786 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3787 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3788 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00003789 }
3790 }
3791
John McCalld9dfe3a2011-06-30 08:33:18 +00003792 case TemplateName::SubstTemplateTemplateParm: {
3793 SubstTemplateTemplateParmStorage *subst
3794 = Name.getAsSubstTemplateTemplateParm();
3795 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3796 NameLoc);
3797 }
3798
3799 case TemplateName::SubstTemplateTemplateParmPack: {
3800 SubstTemplateTemplateParmPackStorage *subst
3801 = Name.getAsSubstTemplateTemplateParmPack();
3802 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3803 NameLoc);
3804 }
3805 }
3806
3807 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00003808}
3809
Jay Foad39c79802011-01-12 09:06:06 +00003810TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003811 switch (Name.getKind()) {
3812 case TemplateName::QualifiedTemplate:
3813 case TemplateName::Template: {
3814 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003815 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00003816 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003817 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3818
3819 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00003820 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003821 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00003822
John McCalld9dfe3a2011-06-30 08:33:18 +00003823 case TemplateName::OverloadedTemplate:
3824 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00003825
John McCalld9dfe3a2011-06-30 08:33:18 +00003826 case TemplateName::DependentTemplate: {
3827 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3828 assert(DTN && "Non-dependent template names must refer to template decls.");
3829 return DTN->CanonicalTemplateName;
3830 }
3831
3832 case TemplateName::SubstTemplateTemplateParm: {
3833 SubstTemplateTemplateParmStorage *subst
3834 = Name.getAsSubstTemplateTemplateParm();
3835 return getCanonicalTemplateName(subst->getReplacement());
3836 }
3837
3838 case TemplateName::SubstTemplateTemplateParmPack: {
3839 SubstTemplateTemplateParmPackStorage *subst
3840 = Name.getAsSubstTemplateTemplateParmPack();
3841 TemplateTemplateParmDecl *canonParameter
3842 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3843 TemplateArgument canonArgPack
3844 = getCanonicalTemplateArgument(subst->getArgumentPack());
3845 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3846 }
3847 }
3848
3849 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00003850}
3851
Douglas Gregoradee3e32009-11-11 23:06:43 +00003852bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3853 X = getCanonicalTemplateName(X);
3854 Y = getCanonicalTemplateName(Y);
3855 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3856}
3857
Mike Stump11289f42009-09-09 15:08:12 +00003858TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00003859ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00003860 switch (Arg.getKind()) {
3861 case TemplateArgument::Null:
3862 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003863
Douglas Gregora8e02e72009-07-28 23:00:59 +00003864 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00003865 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003866
Douglas Gregor31f55dc2012-04-06 22:40:38 +00003867 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00003868 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
3869 return TemplateArgument(D, Arg.isDeclForReferenceParam());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00003870 }
Mike Stump11289f42009-09-09 15:08:12 +00003871
Eli Friedmanb826a002012-09-26 02:36:12 +00003872 case TemplateArgument::NullPtr:
3873 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
3874 /*isNullPtr*/true);
3875
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003876 case TemplateArgument::Template:
3877 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003878
3879 case TemplateArgument::TemplateExpansion:
3880 return TemplateArgument(getCanonicalTemplateName(
3881 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00003882 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003883
Douglas Gregora8e02e72009-07-28 23:00:59 +00003884 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00003885 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00003886
Douglas Gregora8e02e72009-07-28 23:00:59 +00003887 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00003888 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00003889
Douglas Gregora8e02e72009-07-28 23:00:59 +00003890 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00003891 if (Arg.pack_size() == 0)
3892 return Arg;
3893
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003894 TemplateArgument *CanonArgs
3895 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00003896 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003897 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003898 AEnd = Arg.pack_end();
3899 A != AEnd; (void)++A, ++Idx)
3900 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00003901
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003902 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00003903 }
3904 }
3905
3906 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00003907 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00003908}
3909
Douglas Gregor333489b2009-03-27 23:10:48 +00003910NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00003911ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00003912 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00003913 return 0;
3914
3915 switch (NNS->getKind()) {
3916 case NestedNameSpecifier::Identifier:
3917 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00003918 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00003919 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3920 NNS->getAsIdentifier());
3921
3922 case NestedNameSpecifier::Namespace:
3923 // A namespace is canonical; build a nested-name-specifier with
3924 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00003925 return NestedNameSpecifier::Create(*this, 0,
3926 NNS->getAsNamespace()->getOriginalNamespace());
3927
3928 case NestedNameSpecifier::NamespaceAlias:
3929 // A namespace is canonical; build a nested-name-specifier with
3930 // this namespace and no prefix.
3931 return NestedNameSpecifier::Create(*this, 0,
3932 NNS->getAsNamespaceAlias()->getNamespace()
3933 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00003934
3935 case NestedNameSpecifier::TypeSpec:
3936 case NestedNameSpecifier::TypeSpecWithTemplate: {
3937 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003938
3939 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3940 // break it apart into its prefix and identifier, then reconsititute those
3941 // as the canonical nested-name-specifier. This is required to canonicalize
3942 // a dependent nested-name-specifier involving typedefs of dependent-name
3943 // types, e.g.,
3944 // typedef typename T::type T1;
3945 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00003946 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
3947 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00003948 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003949
Eli Friedman5358a0a2012-03-03 04:09:56 +00003950 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
3951 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
3952 // first place?
John McCall33ddac02011-01-19 10:06:00 +00003953 return NestedNameSpecifier::Create(*this, 0, false,
3954 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00003955 }
3956
3957 case NestedNameSpecifier::Global:
3958 // The global specifier is canonical and unique.
3959 return NNS;
3960 }
3961
David Blaikie8a40f702012-01-17 06:56:22 +00003962 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00003963}
3964
Chris Lattner7adf0762008-08-04 07:31:14 +00003965
Jay Foad39c79802011-01-12 09:06:06 +00003966const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003967 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003968 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003969 // Handle the common positive case fast.
3970 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3971 return AT;
3972 }
Mike Stump11289f42009-09-09 15:08:12 +00003973
John McCall8ccfcb52009-09-24 19:53:00 +00003974 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00003975 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00003976 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003977
John McCall8ccfcb52009-09-24 19:53:00 +00003978 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00003979 // implements C99 6.7.3p8: "If the specification of an array type includes
3980 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00003981
Chris Lattner7adf0762008-08-04 07:31:14 +00003982 // If we get here, we either have type qualifiers on the type, or we have
3983 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00003984 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00003985
John McCall33ddac02011-01-19 10:06:00 +00003986 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003987 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00003988
Chris Lattner7adf0762008-08-04 07:31:14 +00003989 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00003990 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall33ddac02011-01-19 10:06:00 +00003991 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00003992 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00003993
Chris Lattner7adf0762008-08-04 07:31:14 +00003994 // Otherwise, we have an array and we have qualifiers on it. Push the
3995 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00003996 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00003997
Chris Lattner7adf0762008-08-04 07:31:14 +00003998 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3999 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4000 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004001 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00004002 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4003 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4004 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004005 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00004006
Mike Stump11289f42009-09-09 15:08:12 +00004007 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00004008 = dyn_cast<DependentSizedArrayType>(ATy))
4009 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00004010 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004011 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00004012 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004013 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004014 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00004015
Chris Lattner7adf0762008-08-04 07:31:14 +00004016 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00004017 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004018 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00004019 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004020 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004021 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00004022}
4023
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004024QualType ASTContext::getAdjustedParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004025 // C99 6.7.5.3p7:
4026 // A declaration of a parameter as "array of type" shall be
4027 // adjusted to "qualified pointer to type", where the type
4028 // qualifiers (if any) are those specified within the [ and ] of
4029 // the array type derivation.
4030 if (T->isArrayType())
4031 return getArrayDecayedType(T);
4032
4033 // C99 6.7.5.3p8:
4034 // A declaration of a parameter as "function returning type"
4035 // shall be adjusted to "pointer to function returning type", as
4036 // in 6.3.2.1.
4037 if (T->isFunctionType())
4038 return getPointerType(T);
4039
4040 return T;
4041}
4042
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004043QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004044 T = getVariableArrayDecayedType(T);
4045 T = getAdjustedParameterType(T);
4046 return T.getUnqualifiedType();
4047}
4048
Chris Lattnera21ad802008-04-02 05:18:44 +00004049/// getArrayDecayedType - Return the properly qualified result of decaying the
4050/// specified array type to a pointer. This operation is non-trivial when
4051/// handling typedefs etc. The canonical type of "T" must be an array type,
4052/// this returns a pointer to a properly qualified element of the array.
4053///
4054/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004055QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004056 // Get the element type with 'getAsArrayType' so that we don't lose any
4057 // typedefs in the element type of the array. This also handles propagation
4058 // of type qualifiers from the array type into the element type if present
4059 // (C99 6.7.3p8).
4060 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4061 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004062
Chris Lattner7adf0762008-08-04 07:31:14 +00004063 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004064
4065 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00004066 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00004067}
4068
John McCall33ddac02011-01-19 10:06:00 +00004069QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4070 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00004071}
4072
John McCall33ddac02011-01-19 10:06:00 +00004073QualType ASTContext::getBaseElementType(QualType type) const {
4074 Qualifiers qs;
4075 while (true) {
4076 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004077 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00004078 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00004079
John McCall33ddac02011-01-19 10:06:00 +00004080 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00004081 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00004082 }
Mike Stump11289f42009-09-09 15:08:12 +00004083
John McCall33ddac02011-01-19 10:06:00 +00004084 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00004085}
4086
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004087/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00004088uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004089ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4090 uint64_t ElementCount = 1;
4091 do {
4092 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00004093 CA = dyn_cast_or_null<ConstantArrayType>(
4094 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004095 } while (CA);
4096 return ElementCount;
4097}
4098
Steve Naroff0af91202007-04-27 21:51:21 +00004099/// getFloatingRank - Return a relative rank for floating point types.
4100/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00004101static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00004102 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00004103 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00004104
John McCall9dd450b2009-09-21 23:43:11 +00004105 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4106 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004107 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004108 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00004109 case BuiltinType::Float: return FloatRank;
4110 case BuiltinType::Double: return DoubleRank;
4111 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00004112 }
4113}
4114
Mike Stump11289f42009-09-09 15:08:12 +00004115/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4116/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00004117/// 'typeDomain' is a real floating point or complex type.
4118/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004119QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4120 QualType Domain) const {
4121 FloatingRank EltRank = getFloatingRank(Size);
4122 if (Domain->isComplexType()) {
4123 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004124 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00004125 case FloatRank: return FloatComplexTy;
4126 case DoubleRank: return DoubleComplexTy;
4127 case LongDoubleRank: return LongDoubleComplexTy;
4128 }
Steve Naroff0af91202007-04-27 21:51:21 +00004129 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004130
4131 assert(Domain->isRealFloatingType() && "Unknown domain!");
4132 switch (EltRank) {
Joey Goulydd7f4562013-01-23 11:56:20 +00004133 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004134 case FloatRank: return FloatTy;
4135 case DoubleRank: return DoubleTy;
4136 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00004137 }
David Blaikief47fa302012-01-17 02:30:50 +00004138 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00004139}
4140
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004141/// getFloatingTypeOrder - Compare the rank of the two specified floating
4142/// point types, ignoring the domain of the type (i.e. 'double' ==
4143/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004144/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004145int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00004146 FloatingRank LHSR = getFloatingRank(LHS);
4147 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004148
Chris Lattnerb90739d2008-04-06 23:38:49 +00004149 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004150 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00004151 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004152 return 1;
4153 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00004154}
4155
Chris Lattner76a00cf2008-04-06 22:59:24 +00004156/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4157/// routine will assert if passed a built-in type that isn't an integer or enum,
4158/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00004159unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00004160 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004161
Chris Lattner76a00cf2008-04-06 22:59:24 +00004162 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004163 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004164 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004165 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004166 case BuiltinType::Char_S:
4167 case BuiltinType::Char_U:
4168 case BuiltinType::SChar:
4169 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004170 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004171 case BuiltinType::Short:
4172 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004173 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004174 case BuiltinType::Int:
4175 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004176 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004177 case BuiltinType::Long:
4178 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004179 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004180 case BuiltinType::LongLong:
4181 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004182 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00004183 case BuiltinType::Int128:
4184 case BuiltinType::UInt128:
4185 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00004186 }
4187}
4188
Eli Friedman629ffb92009-08-20 04:21:42 +00004189/// \brief Whether this is a promotable bitfield reference according
4190/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4191///
4192/// \returns the type this bit-field will promote to, or NULL if no
4193/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004194QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004195 if (E->isTypeDependent() || E->isValueDependent())
4196 return QualType();
4197
Eli Friedman629ffb92009-08-20 04:21:42 +00004198 FieldDecl *Field = E->getBitField();
4199 if (!Field)
4200 return QualType();
4201
4202 QualType FT = Field->getType();
4203
Richard Smithcaf33902011-10-10 18:28:20 +00004204 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004205 uint64_t IntSize = getTypeSize(IntTy);
4206 // GCC extension compatibility: if the bit-field size is less than or equal
4207 // to the size of int, it gets promoted no matter what its type is.
4208 // For instance, unsigned long bf : 4 gets promoted to signed int.
4209 if (BitWidth < IntSize)
4210 return IntTy;
4211
4212 if (BitWidth == IntSize)
4213 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4214
4215 // Types bigger than int are not subject to promotions, and therefore act
4216 // like the base type.
4217 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4218 // is ridiculous.
4219 return QualType();
4220}
4221
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004222/// getPromotedIntegerType - Returns the type that Promotable will
4223/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4224/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004225QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004226 assert(!Promotable.isNull());
4227 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004228 if (const EnumType *ET = Promotable->getAs<EnumType>())
4229 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004230
4231 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4232 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4233 // (3.9.1) can be converted to a prvalue of the first of the following
4234 // types that can represent all the values of its underlying type:
4235 // int, unsigned int, long int, unsigned long int, long long int, or
4236 // unsigned long long int [...]
4237 // FIXME: Is there some better way to compute this?
4238 if (BT->getKind() == BuiltinType::WChar_S ||
4239 BT->getKind() == BuiltinType::WChar_U ||
4240 BT->getKind() == BuiltinType::Char16 ||
4241 BT->getKind() == BuiltinType::Char32) {
4242 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4243 uint64_t FromSize = getTypeSize(BT);
4244 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4245 LongLongTy, UnsignedLongLongTy };
4246 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4247 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4248 if (FromSize < ToSize ||
4249 (FromSize == ToSize &&
4250 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4251 return PromoteTypes[Idx];
4252 }
4253 llvm_unreachable("char type should fit into long long");
4254 }
4255 }
4256
4257 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004258 if (Promotable->isSignedIntegerType())
4259 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00004260 uint64_t PromotableSize = getIntWidth(Promotable);
4261 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004262 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4263 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4264}
4265
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004266/// \brief Recurses in pointer/array types until it finds an objc retainable
4267/// type and returns its ownership.
4268Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4269 while (!T.isNull()) {
4270 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4271 return T.getObjCLifetime();
4272 if (T->isArrayType())
4273 T = getBaseElementType(T);
4274 else if (const PointerType *PT = T->getAs<PointerType>())
4275 T = PT->getPointeeType();
4276 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004277 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004278 else
4279 break;
4280 }
4281
4282 return Qualifiers::OCL_None;
4283}
4284
Mike Stump11289f42009-09-09 15:08:12 +00004285/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004286/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004287/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004288int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004289 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4290 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004291 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004292
Chris Lattner76a00cf2008-04-06 22:59:24 +00004293 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4294 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004295
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004296 unsigned LHSRank = getIntegerRank(LHSC);
4297 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004298
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004299 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4300 if (LHSRank == RHSRank) return 0;
4301 return LHSRank > RHSRank ? 1 : -1;
4302 }
Mike Stump11289f42009-09-09 15:08:12 +00004303
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004304 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4305 if (LHSUnsigned) {
4306 // If the unsigned [LHS] type is larger, return it.
4307 if (LHSRank >= RHSRank)
4308 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004309
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004310 // If the signed type can represent all values of the unsigned type, it
4311 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004312 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004313 return -1;
4314 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004315
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004316 // If the unsigned [RHS] type is larger, return it.
4317 if (RHSRank >= LHSRank)
4318 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004319
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004320 // If the signed type can represent all values of the unsigned type, it
4321 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004322 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004323 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004324}
Anders Carlsson98f07902007-08-17 05:31:46 +00004325
Anders Carlsson6d417272009-11-14 21:45:58 +00004326static RecordDecl *
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004327CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
4328 DeclContext *DC, IdentifierInfo *Id) {
4329 SourceLocation Loc;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004330 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004331 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00004332 else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004333 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00004334}
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004335
Mike Stump11289f42009-09-09 15:08:12 +00004336// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00004337QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004338 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00004339 CFConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004340 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004341 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00004342 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004343
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004344 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00004345
Anders Carlsson98f07902007-08-17 05:31:46 +00004346 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004347 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004348 // int flags;
4349 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00004350 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004351 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00004352 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004353 FieldTypes[3] = LongTy;
4354
Anders Carlsson98f07902007-08-17 05:31:46 +00004355 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004356 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00004357 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004358 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00004359 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00004360 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00004361 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004362 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004363 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004364 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004365 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004366 }
4367
Douglas Gregord5058122010-02-11 01:19:42 +00004368 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00004369 }
Mike Stump11289f42009-09-09 15:08:12 +00004370
Anders Carlsson98f07902007-08-17 05:31:46 +00004371 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00004372}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004373
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004374QualType ASTContext::getObjCSuperType() const {
4375 if (ObjCSuperType.isNull()) {
4376 RecordDecl *ObjCSuperTypeDecl =
4377 CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get("objc_super"));
4378 TUDecl->addDecl(ObjCSuperTypeDecl);
4379 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4380 }
4381 return ObjCSuperType;
4382}
4383
Douglas Gregor512b0772009-04-23 22:29:11 +00004384void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004385 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00004386 assert(Rec && "Invalid CFConstantStringType");
4387 CFConstantStringTypeDecl = Rec->getDecl();
4388}
4389
Jay Foad39c79802011-01-12 09:06:06 +00004390QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004391 if (BlockDescriptorType)
4392 return getTagDeclType(BlockDescriptorType);
4393
4394 RecordDecl *T;
4395 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004396 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004397 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00004398 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004399
4400 QualType FieldTypes[] = {
4401 UnsignedLongTy,
4402 UnsignedLongTy,
4403 };
4404
4405 const char *FieldNames[] = {
4406 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004407 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004408 };
4409
4410 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004411 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00004412 SourceLocation(),
4413 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004414 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00004415 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004416 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004417 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004418 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00004419 T->addDecl(Field);
4420 }
4421
Douglas Gregord5058122010-02-11 01:19:42 +00004422 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004423
4424 BlockDescriptorType = T;
4425
4426 return getTagDeclType(BlockDescriptorType);
4427}
4428
Jay Foad39c79802011-01-12 09:06:06 +00004429QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004430 if (BlockDescriptorExtendedType)
4431 return getTagDeclType(BlockDescriptorExtendedType);
4432
4433 RecordDecl *T;
4434 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004435 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004436 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00004437 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004438
4439 QualType FieldTypes[] = {
4440 UnsignedLongTy,
4441 UnsignedLongTy,
4442 getPointerType(VoidPtrTy),
4443 getPointerType(VoidPtrTy)
4444 };
4445
4446 const char *FieldNames[] = {
4447 "reserved",
4448 "Size",
4449 "CopyFuncPtr",
4450 "DestroyFuncPtr"
4451 };
4452
4453 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004454 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004455 SourceLocation(),
4456 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004457 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004458 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004459 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004460 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004461 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004462 T->addDecl(Field);
4463 }
4464
Douglas Gregord5058122010-02-11 01:19:42 +00004465 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004466
4467 BlockDescriptorExtendedType = T;
4468
4469 return getTagDeclType(BlockDescriptorExtendedType);
4470}
4471
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004472/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4473/// requires copy/dispose. Note that this must match the logic
4474/// in buildByrefHelpers.
4475bool ASTContext::BlockRequiresCopying(QualType Ty,
4476 const VarDecl *D) {
4477 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4478 const Expr *copyExpr = getBlockVarCopyInits(D);
4479 if (!copyExpr && record->hasTrivialDestructor()) return false;
4480
Mike Stump94967902009-10-21 18:16:27 +00004481 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004482 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004483
4484 if (!Ty->isObjCRetainableType()) return false;
4485
4486 Qualifiers qs = Ty.getQualifiers();
4487
4488 // If we have lifetime, that dominates.
4489 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4490 assert(getLangOpts().ObjCAutoRefCount);
4491
4492 switch (lifetime) {
4493 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4494
4495 // These are just bits as far as the runtime is concerned.
4496 case Qualifiers::OCL_ExplicitNone:
4497 case Qualifiers::OCL_Autoreleasing:
4498 return false;
4499
4500 // Tell the runtime that this is ARC __weak, called by the
4501 // byref routines.
4502 case Qualifiers::OCL_Weak:
4503 // ARC __strong __block variables need to be retained.
4504 case Qualifiers::OCL_Strong:
4505 return true;
4506 }
4507 llvm_unreachable("fell out of lifetime switch!");
4508 }
4509 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4510 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00004511}
4512
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004513bool ASTContext::getByrefLifetime(QualType Ty,
4514 Qualifiers::ObjCLifetime &LifeTime,
4515 bool &HasByrefExtendedLayout) const {
4516
4517 if (!getLangOpts().ObjC1 ||
4518 getLangOpts().getGC() != LangOptions::NonGC)
4519 return false;
4520
4521 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00004522 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004523 HasByrefExtendedLayout = true;
4524 LifeTime = Qualifiers::OCL_None;
4525 }
4526 else if (getLangOpts().ObjCAutoRefCount)
4527 LifeTime = Ty.getObjCLifetime();
4528 // MRR.
4529 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4530 LifeTime = Qualifiers::OCL_ExplicitNone;
4531 else
4532 LifeTime = Qualifiers::OCL_None;
4533 return true;
4534}
4535
Douglas Gregorbab8a962011-09-08 01:46:34 +00004536TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4537 if (!ObjCInstanceTypeDecl)
4538 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4539 getTranslationUnitDecl(),
4540 SourceLocation(),
4541 SourceLocation(),
4542 &Idents.get("instancetype"),
4543 getTrivialTypeSourceInfo(getObjCIdType()));
4544 return ObjCInstanceTypeDecl;
4545}
4546
Anders Carlsson18acd442007-10-29 06:33:42 +00004547// This returns true if a type has been typedefed to BOOL:
4548// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004549static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004550 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004551 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4552 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004553
Anders Carlssond8499822007-10-29 05:01:08 +00004554 return false;
4555}
4556
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004557/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004558/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004559CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004560 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4561 return CharUnits::Zero();
4562
Ken Dyck40775002010-01-11 17:06:35 +00004563 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004564
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004565 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004566 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004567 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004568 // Treat arrays as pointers, since that's how they're passed in.
4569 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004570 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004571 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004572}
4573
4574static inline
4575std::string charUnitsToString(const CharUnits &CU) {
4576 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004577}
4578
John McCall351762c2011-02-07 10:33:21 +00004579/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004580/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004581std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4582 std::string S;
4583
David Chisnall950a9512009-11-17 19:33:30 +00004584 const BlockDecl *Decl = Expr->getBlockDecl();
4585 QualType BlockTy =
4586 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4587 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004588 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004589 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None,
4590 BlockTy->getAs<FunctionType>()->getResultType(),
4591 S, true /*Extended*/);
4592 else
4593 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(),
4594 S);
David Chisnall950a9512009-11-17 19:33:30 +00004595 // Compute size of all parameters.
4596 // Start with computing size of a pointer in number of bytes.
4597 // FIXME: There might(should) be a better way of doing this computation!
4598 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004599 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4600 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00004601 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00004602 E = Decl->param_end(); PI != E; ++PI) {
4603 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004604 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00004605 if (sz.isZero())
4606 continue;
Ken Dyck40775002010-01-11 17:06:35 +00004607 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004608 ParmOffset += sz;
4609 }
4610 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004611 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004612 // Block pointer and offset.
4613 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004614
4615 // Argument types.
4616 ParmOffset = PtrSize;
4617 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4618 Decl->param_end(); PI != E; ++PI) {
4619 ParmVarDecl *PVDecl = *PI;
4620 QualType PType = PVDecl->getOriginalType();
4621 if (const ArrayType *AT =
4622 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4623 // Use array's original type only if it has known number of
4624 // elements.
4625 if (!isa<ConstantArrayType>(AT))
4626 PType = PVDecl->getType();
4627 } else if (PType->isFunctionType())
4628 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004629 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004630 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4631 S, true /*Extended*/);
4632 else
4633 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004634 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004635 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004636 }
John McCall351762c2011-02-07 10:33:21 +00004637
4638 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004639}
4640
Douglas Gregora9d84932011-05-27 01:19:52 +00004641bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004642 std::string& S) {
4643 // Encode result type.
4644 getObjCEncodingForType(Decl->getResultType(), S);
4645 CharUnits ParmOffset;
4646 // Compute size of all parameters.
4647 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4648 E = Decl->param_end(); PI != E; ++PI) {
4649 QualType PType = (*PI)->getType();
4650 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004651 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004652 continue;
4653
David Chisnall50e4eba2010-12-30 14:05:53 +00004654 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004655 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004656 ParmOffset += sz;
4657 }
4658 S += charUnitsToString(ParmOffset);
4659 ParmOffset = CharUnits::Zero();
4660
4661 // Argument types.
4662 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4663 E = Decl->param_end(); PI != E; ++PI) {
4664 ParmVarDecl *PVDecl = *PI;
4665 QualType PType = PVDecl->getOriginalType();
4666 if (const ArrayType *AT =
4667 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4668 // Use array's original type only if it has known number of
4669 // elements.
4670 if (!isa<ConstantArrayType>(AT))
4671 PType = PVDecl->getType();
4672 } else if (PType->isFunctionType())
4673 PType = PVDecl->getType();
4674 getObjCEncodingForType(PType, S);
4675 S += charUnitsToString(ParmOffset);
4676 ParmOffset += getObjCEncodingTypeSize(PType);
4677 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004678
4679 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004680}
4681
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004682/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4683/// method parameter or return type. If Extended, include class names and
4684/// block object types.
4685void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4686 QualType T, std::string& S,
4687 bool Extended) const {
4688 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4689 getObjCEncodingForTypeQualifier(QT, S);
4690 // Encode parameter type.
4691 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4692 true /*OutermostType*/,
4693 false /*EncodingProperty*/,
4694 false /*StructField*/,
4695 Extended /*EncodeBlockParameters*/,
4696 Extended /*EncodeClassNames*/);
4697}
4698
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004699/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004700/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004701bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004702 std::string& S,
4703 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004704 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004705 // Encode return type.
4706 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4707 Decl->getResultType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004708 // Compute size of all parameters.
4709 // Start with computing size of a pointer in number of bytes.
4710 // FIXME: There might(should) be a better way of doing this computation!
4711 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004712 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004713 // The first two arguments (self and _cmd) are pointers; account for
4714 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004715 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004716 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004717 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004718 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004719 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004720 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004721 continue;
4722
Ken Dyck40775002010-01-11 17:06:35 +00004723 assert (sz.isPositive() &&
4724 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004725 ParmOffset += sz;
4726 }
Ken Dyck40775002010-01-11 17:06:35 +00004727 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004728 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004729 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004730
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004731 // Argument types.
4732 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004733 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004734 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004735 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004736 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004737 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004738 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4739 // Use array's original type only if it has known number of
4740 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004741 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004742 PType = PVDecl->getType();
4743 } else if (PType->isFunctionType())
4744 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004745 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4746 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00004747 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004748 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004749 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004750
4751 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004752}
4753
Daniel Dunbar4932b362008-08-28 04:38:10 +00004754/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004755/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004756/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4757/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004758/// Property attributes are stored as a comma-delimited C string. The simple
4759/// attributes readonly and bycopy are encoded as single characters. The
4760/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4761/// encoded as single characters, followed by an identifier. Property types
4762/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004763/// these attributes are defined by the following enumeration:
4764/// @code
4765/// enum PropertyAttributes {
4766/// kPropertyReadOnly = 'R', // property is read-only.
4767/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4768/// kPropertyByref = '&', // property is a reference to the value last assigned
4769/// kPropertyDynamic = 'D', // property is dynamic
4770/// kPropertyGetter = 'G', // followed by getter selector name
4771/// kPropertySetter = 'S', // followed by setter selector name
4772/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00004773/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004774/// kPropertyWeak = 'W' // 'weak' property
4775/// kPropertyStrong = 'P' // property GC'able
4776/// kPropertyNonAtomic = 'N' // property non-atomic
4777/// };
4778/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00004779void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00004780 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00004781 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004782 // Collect information from the property implementation decl(s).
4783 bool Dynamic = false;
4784 ObjCPropertyImplDecl *SynthesizePID = 0;
4785
4786 // FIXME: Duplicated code due to poor abstraction.
4787 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00004788 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00004789 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4790 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004791 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004792 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004793 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004794 if (PID->getPropertyDecl() == PD) {
4795 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4796 Dynamic = true;
4797 } else {
4798 SynthesizePID = PID;
4799 }
4800 }
4801 }
4802 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00004803 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004804 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004805 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004806 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004807 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004808 if (PID->getPropertyDecl() == PD) {
4809 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4810 Dynamic = true;
4811 } else {
4812 SynthesizePID = PID;
4813 }
4814 }
Mike Stump11289f42009-09-09 15:08:12 +00004815 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00004816 }
4817 }
4818
4819 // FIXME: This is not very efficient.
4820 S = "T";
4821
4822 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004823 // GCC has some special rules regarding encoding of properties which
4824 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00004825 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004826 true /* outermost type */,
4827 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004828
4829 if (PD->isReadOnly()) {
4830 S += ",R";
4831 } else {
4832 switch (PD->getSetterKind()) {
4833 case ObjCPropertyDecl::Assign: break;
4834 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00004835 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00004836 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004837 }
4838 }
4839
4840 // It really isn't clear at all what this means, since properties
4841 // are "dynamic by default".
4842 if (Dynamic)
4843 S += ",D";
4844
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004845 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4846 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00004847
Daniel Dunbar4932b362008-08-28 04:38:10 +00004848 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4849 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00004850 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004851 }
4852
4853 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4854 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00004855 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004856 }
4857
4858 if (SynthesizePID) {
4859 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4860 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00004861 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004862 }
4863
4864 // FIXME: OBJCGC: weak & strong
4865}
4866
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004867/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00004868/// Another legacy compatibility encoding: 32-bit longs are encoded as
4869/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004870/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4871///
4872void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00004873 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00004874 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00004875 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004876 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00004877 else
Jay Foad39c79802011-01-12 09:06:06 +00004878 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004879 PointeeTy = IntTy;
4880 }
4881 }
4882}
4883
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004884void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00004885 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004886 // We follow the behavior of gcc, expanding structures which are
4887 // directly pointed to, and expanding embedded structures. Note that
4888 // these rules are sufficient to prevent recursive encoding of the
4889 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00004890 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00004891 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004892}
4893
John McCall393a78d2012-12-20 02:45:14 +00004894static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
4895 BuiltinType::Kind kind) {
4896 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00004897 case BuiltinType::Void: return 'v';
4898 case BuiltinType::Bool: return 'B';
4899 case BuiltinType::Char_U:
4900 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00004901 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00004902 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00004903 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00004904 case BuiltinType::UInt: return 'I';
4905 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00004906 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004907 case BuiltinType::UInt128: return 'T';
4908 case BuiltinType::ULongLong: return 'Q';
4909 case BuiltinType::Char_S:
4910 case BuiltinType::SChar: return 'c';
4911 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00004912 case BuiltinType::WChar_S:
4913 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00004914 case BuiltinType::Int: return 'i';
4915 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00004916 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004917 case BuiltinType::LongLong: return 'q';
4918 case BuiltinType::Int128: return 't';
4919 case BuiltinType::Float: return 'f';
4920 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00004921 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00004922 case BuiltinType::NullPtr: return '*'; // like char*
4923
4924 case BuiltinType::Half:
4925 // FIXME: potentially need @encodes for these!
4926 return ' ';
4927
4928 case BuiltinType::ObjCId:
4929 case BuiltinType::ObjCClass:
4930 case BuiltinType::ObjCSel:
4931 llvm_unreachable("@encoding ObjC primitive type");
4932
4933 // OpenCL and placeholder types don't need @encodings.
4934 case BuiltinType::OCLImage1d:
4935 case BuiltinType::OCLImage1dArray:
4936 case BuiltinType::OCLImage1dBuffer:
4937 case BuiltinType::OCLImage2d:
4938 case BuiltinType::OCLImage2dArray:
4939 case BuiltinType::OCLImage3d:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00004940 case BuiltinType::OCLEvent:
Guy Benyei61054192013-02-07 10:55:47 +00004941 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00004942 case BuiltinType::Dependent:
4943#define BUILTIN_TYPE(KIND, ID)
4944#define PLACEHOLDER_TYPE(KIND, ID) \
4945 case BuiltinType::KIND:
4946#include "clang/AST/BuiltinTypes.def"
4947 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00004948 }
David Blaikie5a6a0202013-01-09 17:48:41 +00004949 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00004950}
4951
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004952static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4953 EnumDecl *Enum = ET->getDecl();
4954
4955 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4956 if (!Enum->isFixed())
4957 return 'i';
4958
4959 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00004960 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
4961 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004962}
4963
Jay Foad39c79802011-01-12 09:06:06 +00004964static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00004965 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00004966 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004967 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00004968 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4969 // The GNU runtime requires more information; bitfields are encoded as b,
4970 // then the offset (in bits) of the first element, then the type of the
4971 // bitfield, then the size in bits. For example, in this structure:
4972 //
4973 // struct
4974 // {
4975 // int integer;
4976 // int flags:2;
4977 // };
4978 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4979 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4980 // information is not especially sensible, but we're stuck with it for
4981 // compatibility with GCC, although providing it breaks anything that
4982 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00004983 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00004984 const RecordDecl *RD = FD->getParent();
4985 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00004986 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004987 if (const EnumType *ET = T->getAs<EnumType>())
4988 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00004989 else {
4990 const BuiltinType *BT = T->castAs<BuiltinType>();
4991 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
4992 }
David Chisnallb190a2c2010-06-04 01:10:52 +00004993 }
Richard Smithcaf33902011-10-10 18:28:20 +00004994 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004995}
4996
Daniel Dunbar07d07852009-10-18 21:17:35 +00004997// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004998void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4999 bool ExpandPointedToStructures,
5000 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00005001 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005002 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005003 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005004 bool StructField,
5005 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005006 bool EncodeClassNames,
5007 bool EncodePointerToObjCTypedef) const {
John McCall393a78d2012-12-20 02:45:14 +00005008 CanQualType CT = getCanonicalType(T);
5009 switch (CT->getTypeClass()) {
5010 case Type::Builtin:
5011 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00005012 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00005013 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00005014 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5015 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5016 else
5017 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00005018 return;
Mike Stump11289f42009-09-09 15:08:12 +00005019
John McCall393a78d2012-12-20 02:45:14 +00005020 case Type::Complex: {
5021 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00005022 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00005023 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00005024 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005025 return;
5026 }
John McCall393a78d2012-12-20 02:45:14 +00005027
5028 case Type::Atomic: {
5029 const AtomicType *AT = T->castAs<AtomicType>();
5030 S += 'A';
5031 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, 0,
5032 false, false);
5033 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00005034 }
John McCall393a78d2012-12-20 02:45:14 +00005035
5036 // encoding for pointer or reference types.
5037 case Type::Pointer:
5038 case Type::LValueReference:
5039 case Type::RValueReference: {
5040 QualType PointeeTy;
5041 if (isa<PointerType>(CT)) {
5042 const PointerType *PT = T->castAs<PointerType>();
5043 if (PT->isObjCSelType()) {
5044 S += ':';
5045 return;
5046 }
5047 PointeeTy = PT->getPointeeType();
5048 } else {
5049 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5050 }
5051
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005052 bool isReadOnly = false;
5053 // For historical/compatibility reasons, the read-only qualifier of the
5054 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5055 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00005056 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00005057 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005058 if (OutermostType && T.isConstQualified()) {
5059 isReadOnly = true;
5060 S += 'r';
5061 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00005062 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005063 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005064 while (P->getAs<PointerType>())
5065 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005066 if (P.isConstQualified()) {
5067 isReadOnly = true;
5068 S += 'r';
5069 }
5070 }
5071 if (isReadOnly) {
5072 // Another legacy compatibility encoding. Some ObjC qualifier and type
5073 // combinations need to be rearranged.
5074 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005075 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00005076 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005077 }
Mike Stump11289f42009-09-09 15:08:12 +00005078
Anders Carlssond8499822007-10-29 05:01:08 +00005079 if (PointeeTy->isCharType()) {
5080 // char pointer types should be encoded as '*' unless it is a
5081 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00005082 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00005083 S += '*';
5084 return;
5085 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005086 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00005087 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5088 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5089 S += '#';
5090 return;
5091 }
5092 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5093 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5094 S += '@';
5095 return;
5096 }
5097 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00005098 }
Anders Carlssond8499822007-10-29 05:01:08 +00005099 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005100 getLegacyIntegralTypeEncoding(PointeeTy);
5101
Mike Stump11289f42009-09-09 15:08:12 +00005102 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005103 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005104 return;
5105 }
John McCall393a78d2012-12-20 02:45:14 +00005106
5107 case Type::ConstantArray:
5108 case Type::IncompleteArray:
5109 case Type::VariableArray: {
5110 const ArrayType *AT = cast<ArrayType>(CT);
5111
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005112 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005113 // Incomplete arrays are encoded as a pointer to the array element.
5114 S += '^';
5115
Mike Stump11289f42009-09-09 15:08:12 +00005116 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005117 false, ExpandStructures, FD);
5118 } else {
5119 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00005120
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005121 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
5122 if (getTypeSize(CAT->getElementType()) == 0)
5123 S += '0';
5124 else
5125 S += llvm::utostr(CAT->getSize().getZExtValue());
5126 } else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005127 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005128 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5129 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00005130 S += '0';
5131 }
Mike Stump11289f42009-09-09 15:08:12 +00005132
5133 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005134 false, ExpandStructures, FD);
5135 S += ']';
5136 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005137 return;
5138 }
Mike Stump11289f42009-09-09 15:08:12 +00005139
John McCall393a78d2012-12-20 02:45:14 +00005140 case Type::FunctionNoProto:
5141 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00005142 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005143 return;
Mike Stump11289f42009-09-09 15:08:12 +00005144
John McCall393a78d2012-12-20 02:45:14 +00005145 case Type::Record: {
5146 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005147 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00005148 // Anonymous structures print as '?'
5149 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5150 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005151 if (ClassTemplateSpecializationDecl *Spec
5152 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5153 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00005154 llvm::raw_string_ostream OS(S);
5155 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005156 TemplateArgs.data(),
5157 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00005158 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005159 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00005160 } else {
5161 S += '?';
5162 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00005163 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005164 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005165 if (!RDecl->isUnion()) {
5166 getObjCEncodingForStructureImpl(RDecl, S, FD);
5167 } else {
5168 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5169 FieldEnd = RDecl->field_end();
5170 Field != FieldEnd; ++Field) {
5171 if (FD) {
5172 S += '"';
5173 S += Field->getNameAsString();
5174 S += '"';
5175 }
Mike Stump11289f42009-09-09 15:08:12 +00005176
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005177 // Special case bit-fields.
5178 if (Field->isBitField()) {
5179 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie40ed2972012-06-06 20:45:41 +00005180 *Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005181 } else {
5182 QualType qt = Field->getType();
5183 getLegacyIntegralTypeEncoding(qt);
5184 getObjCEncodingForTypeImpl(qt, S, false, true,
5185 FD, /*OutermostType*/false,
5186 /*EncodingProperty*/false,
5187 /*StructField*/true);
5188 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005189 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005190 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00005191 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005192 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005193 return;
5194 }
Mike Stump11289f42009-09-09 15:08:12 +00005195
John McCall393a78d2012-12-20 02:45:14 +00005196 case Type::BlockPointer: {
5197 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00005198 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005199 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00005200 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005201
5202 S += '<';
5203 // Block return type
5204 getObjCEncodingForTypeImpl(FT->getResultType(), S,
5205 ExpandPointedToStructures, ExpandStructures,
5206 FD,
5207 false /* OutermostType */,
5208 EncodingProperty,
5209 false /* StructField */,
5210 EncodeBlockParameters,
5211 EncodeClassNames);
5212 // Block self
5213 S += "@?";
5214 // Block parameters
5215 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
5216 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
5217 E = FPT->arg_type_end(); I && (I != E); ++I) {
5218 getObjCEncodingForTypeImpl(*I, S,
5219 ExpandPointedToStructures,
5220 ExpandStructures,
5221 FD,
5222 false /* OutermostType */,
5223 EncodingProperty,
5224 false /* StructField */,
5225 EncodeBlockParameters,
5226 EncodeClassNames);
5227 }
5228 }
5229 S += '>';
5230 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005231 return;
5232 }
Mike Stump11289f42009-09-09 15:08:12 +00005233
John McCall393a78d2012-12-20 02:45:14 +00005234 case Type::ObjCObject:
5235 case Type::ObjCInterface: {
5236 // Ignore protocol qualifiers when mangling at this level.
5237 T = T->castAs<ObjCObjectType>()->getBaseType();
John McCall8b07ec22010-05-15 11:32:37 +00005238
John McCall393a78d2012-12-20 02:45:14 +00005239 // The assumption seems to be that this assert will succeed
5240 // because nested levels will have filtered out 'id' and 'Class'.
5241 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005242 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00005243 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005244 S += '{';
5245 const IdentifierInfo *II = OI->getIdentifier();
5246 S += II->getName();
5247 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005248 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005249 DeepCollectObjCIvars(OI, true, Ivars);
5250 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005251 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005252 if (Field->isBitField())
5253 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005254 else
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005255 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5256 false, false, false, false, false,
5257 EncodePointerToObjCTypedef);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005258 }
5259 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005260 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005261 }
Mike Stump11289f42009-09-09 15:08:12 +00005262
John McCall393a78d2012-12-20 02:45:14 +00005263 case Type::ObjCObjectPointer: {
5264 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005265 if (OPT->isObjCIdType()) {
5266 S += '@';
5267 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005268 }
Mike Stump11289f42009-09-09 15:08:12 +00005269
Steve Narofff0c86112009-10-28 22:03:49 +00005270 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5271 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5272 // Since this is a binary compatibility issue, need to consult with runtime
5273 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005274 S += '#';
5275 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005276 }
Mike Stump11289f42009-09-09 15:08:12 +00005277
Chris Lattnere7cabb92009-07-13 00:10:46 +00005278 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005279 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005280 ExpandPointedToStructures,
5281 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005282 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005283 // Note that we do extended encoding of protocol qualifer list
5284 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005285 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00005286 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5287 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005288 S += '<';
5289 S += (*I)->getNameAsString();
5290 S += '>';
5291 }
5292 S += '"';
5293 }
5294 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005295 }
Mike Stump11289f42009-09-09 15:08:12 +00005296
Chris Lattnere7cabb92009-07-13 00:10:46 +00005297 QualType PointeeTy = OPT->getPointeeType();
5298 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005299 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5300 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005301 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005302 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005303 // {...};
5304 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00005305 getObjCEncodingForTypeImpl(PointeeTy, S,
5306 false, ExpandPointedToStructures,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005307 NULL,
5308 false, false, false, false, false,
5309 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005310 return;
5311 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005312
5313 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005314 if (OPT->getInterfaceDecl() &&
5315 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005316 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00005317 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00005318 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5319 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005320 S += '<';
5321 S += (*I)->getNameAsString();
5322 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005323 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005324 S += '"';
5325 }
5326 return;
5327 }
Mike Stump11289f42009-09-09 15:08:12 +00005328
John McCalla9e6e8d2010-05-17 23:56:34 +00005329 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00005330 // FIXME: we shoul do better than that. 'M' is available.
5331 case Type::MemberPointer:
John McCalla9e6e8d2010-05-17 23:56:34 +00005332 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005333
John McCall393a78d2012-12-20 02:45:14 +00005334 case Type::Vector:
5335 case Type::ExtVector:
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005336 // This matches gcc's encoding, even though technically it is
5337 // insufficient.
5338 // FIXME. We should do a better job than gcc.
5339 return;
John McCall393a78d2012-12-20 02:45:14 +00005340
5341#define ABSTRACT_TYPE(KIND, BASE)
5342#define TYPE(KIND, BASE)
5343#define DEPENDENT_TYPE(KIND, BASE) \
5344 case Type::KIND:
5345#define NON_CANONICAL_TYPE(KIND, BASE) \
5346 case Type::KIND:
5347#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5348 case Type::KIND:
5349#include "clang/AST/TypeNodes.def"
5350 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005351 }
John McCall393a78d2012-12-20 02:45:14 +00005352 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00005353}
5354
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005355void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5356 std::string &S,
5357 const FieldDecl *FD,
5358 bool includeVBases) const {
5359 assert(RDecl && "Expected non-null RecordDecl");
5360 assert(!RDecl->isUnion() && "Should not be called for unions");
5361 if (!RDecl->getDefinition())
5362 return;
5363
5364 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5365 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5366 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5367
5368 if (CXXRec) {
5369 for (CXXRecordDecl::base_class_iterator
5370 BI = CXXRec->bases_begin(),
5371 BE = CXXRec->bases_end(); BI != BE; ++BI) {
5372 if (!BI->isVirtual()) {
5373 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005374 if (base->isEmpty())
5375 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005376 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005377 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5378 std::make_pair(offs, base));
5379 }
5380 }
5381 }
5382
5383 unsigned i = 0;
5384 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5385 FieldEnd = RDecl->field_end();
5386 Field != FieldEnd; ++Field, ++i) {
5387 uint64_t offs = layout.getFieldOffset(i);
5388 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie40ed2972012-06-06 20:45:41 +00005389 std::make_pair(offs, *Field));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005390 }
5391
5392 if (CXXRec && includeVBases) {
5393 for (CXXRecordDecl::base_class_iterator
5394 BI = CXXRec->vbases_begin(),
5395 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
5396 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005397 if (base->isEmpty())
5398 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005399 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00005400 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
5401 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5402 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005403 }
5404 }
5405
5406 CharUnits size;
5407 if (CXXRec) {
5408 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5409 } else {
5410 size = layout.getSize();
5411 }
5412
5413 uint64_t CurOffs = 0;
5414 std::multimap<uint64_t, NamedDecl *>::iterator
5415 CurLayObj = FieldOrBaseOffsets.begin();
5416
Douglas Gregorf5d6c742012-04-27 22:30:01 +00005417 if (CXXRec && CXXRec->isDynamicClass() &&
5418 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005419 if (FD) {
5420 S += "\"_vptr$";
5421 std::string recname = CXXRec->getNameAsString();
5422 if (recname.empty()) recname = "?";
5423 S += recname;
5424 S += '"';
5425 }
5426 S += "^^?";
5427 CurOffs += getTypeSize(VoidPtrTy);
5428 }
5429
5430 if (!RDecl->hasFlexibleArrayMember()) {
5431 // Mark the end of the structure.
5432 uint64_t offs = toBits(size);
5433 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5434 std::make_pair(offs, (NamedDecl*)0));
5435 }
5436
5437 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5438 assert(CurOffs <= CurLayObj->first);
5439
5440 if (CurOffs < CurLayObj->first) {
5441 uint64_t padding = CurLayObj->first - CurOffs;
5442 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5443 // packing/alignment of members is different that normal, in which case
5444 // the encoding will be out-of-sync with the real layout.
5445 // If the runtime switches to just consider the size of types without
5446 // taking into account alignment, we could make padding explicit in the
5447 // encoding (e.g. using arrays of chars). The encoding strings would be
5448 // longer then though.
5449 CurOffs += padding;
5450 }
5451
5452 NamedDecl *dcl = CurLayObj->second;
5453 if (dcl == 0)
5454 break; // reached end of structure.
5455
5456 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5457 // We expand the bases without their virtual bases since those are going
5458 // in the initial structure. Note that this differs from gcc which
5459 // expands virtual bases each time one is encountered in the hierarchy,
5460 // making the encoding type bigger than it really is.
5461 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005462 assert(!base->isEmpty());
5463 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005464 } else {
5465 FieldDecl *field = cast<FieldDecl>(dcl);
5466 if (FD) {
5467 S += '"';
5468 S += field->getNameAsString();
5469 S += '"';
5470 }
5471
5472 if (field->isBitField()) {
5473 EncodeBitField(this, S, field->getType(), field);
Richard Smithcaf33902011-10-10 18:28:20 +00005474 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005475 } else {
5476 QualType qt = field->getType();
5477 getLegacyIntegralTypeEncoding(qt);
5478 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5479 /*OutermostType*/false,
5480 /*EncodingProperty*/false,
5481 /*StructField*/true);
5482 CurOffs += getTypeSize(field->getType());
5483 }
5484 }
5485 }
5486}
5487
Mike Stump11289f42009-09-09 15:08:12 +00005488void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005489 std::string& S) const {
5490 if (QT & Decl::OBJC_TQ_In)
5491 S += 'n';
5492 if (QT & Decl::OBJC_TQ_Inout)
5493 S += 'N';
5494 if (QT & Decl::OBJC_TQ_Out)
5495 S += 'o';
5496 if (QT & Decl::OBJC_TQ_Bycopy)
5497 S += 'O';
5498 if (QT & Decl::OBJC_TQ_Byref)
5499 S += 'R';
5500 if (QT & Decl::OBJC_TQ_Oneway)
5501 S += 'V';
5502}
5503
Douglas Gregor3ea72692011-08-12 05:46:01 +00005504TypedefDecl *ASTContext::getObjCIdDecl() const {
5505 if (!ObjCIdDecl) {
5506 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5507 T = getObjCObjectPointerType(T);
5508 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
5509 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5510 getTranslationUnitDecl(),
5511 SourceLocation(), SourceLocation(),
5512 &Idents.get("id"), IdInfo);
5513 }
5514
5515 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00005516}
5517
Douglas Gregor52e02802011-08-12 06:17:30 +00005518TypedefDecl *ASTContext::getObjCSelDecl() const {
5519 if (!ObjCSelDecl) {
5520 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5521 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5522 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5523 getTranslationUnitDecl(),
5524 SourceLocation(), SourceLocation(),
5525 &Idents.get("SEL"), SelInfo);
5526 }
5527 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00005528}
5529
Douglas Gregor0a586182011-08-12 05:59:41 +00005530TypedefDecl *ASTContext::getObjCClassDecl() const {
5531 if (!ObjCClassDecl) {
5532 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5533 T = getObjCObjectPointerType(T);
5534 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5535 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5536 getTranslationUnitDecl(),
5537 SourceLocation(), SourceLocation(),
5538 &Idents.get("Class"), ClassInfo);
5539 }
5540
5541 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00005542}
5543
Douglas Gregord53ae832012-01-17 18:09:05 +00005544ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5545 if (!ObjCProtocolClassDecl) {
5546 ObjCProtocolClassDecl
5547 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5548 SourceLocation(),
5549 &Idents.get("Protocol"),
5550 /*PrevDecl=*/0,
5551 SourceLocation(), true);
5552 }
5553
5554 return ObjCProtocolClassDecl;
5555}
5556
Meador Inge5d3fb222012-06-16 03:34:49 +00005557//===----------------------------------------------------------------------===//
5558// __builtin_va_list Construction Functions
5559//===----------------------------------------------------------------------===//
5560
5561static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5562 // typedef char* __builtin_va_list;
5563 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5564 TypeSourceInfo *TInfo
5565 = Context->getTrivialTypeSourceInfo(CharPtrType);
5566
5567 TypedefDecl *VaListTypeDecl
5568 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5569 Context->getTranslationUnitDecl(),
5570 SourceLocation(), SourceLocation(),
5571 &Context->Idents.get("__builtin_va_list"),
5572 TInfo);
5573 return VaListTypeDecl;
5574}
5575
5576static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5577 // typedef void* __builtin_va_list;
5578 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5579 TypeSourceInfo *TInfo
5580 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5581
5582 TypedefDecl *VaListTypeDecl
5583 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5584 Context->getTranslationUnitDecl(),
5585 SourceLocation(), SourceLocation(),
5586 &Context->Idents.get("__builtin_va_list"),
5587 TInfo);
5588 return VaListTypeDecl;
5589}
5590
Tim Northover9bb857a2013-01-31 12:13:10 +00005591static TypedefDecl *
5592CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
5593 RecordDecl *VaListTagDecl;
5594 if (Context->getLangOpts().CPlusPlus) {
5595 // namespace std { struct __va_list {
5596 NamespaceDecl *NS;
5597 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5598 Context->getTranslationUnitDecl(),
5599 /*Inline*/false, SourceLocation(),
5600 SourceLocation(), &Context->Idents.get("std"),
5601 /*PrevDecl*/0);
5602
5603 VaListTagDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5604 Context->getTranslationUnitDecl(),
5605 SourceLocation(), SourceLocation(),
5606 &Context->Idents.get("__va_list"));
5607 VaListTagDecl->setDeclContext(NS);
5608 } else {
5609 // struct __va_list
5610 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5611 Context->getTranslationUnitDecl(),
5612 &Context->Idents.get("__va_list"));
5613 }
5614
5615 VaListTagDecl->startDefinition();
5616
5617 const size_t NumFields = 5;
5618 QualType FieldTypes[NumFields];
5619 const char *FieldNames[NumFields];
5620
5621 // void *__stack;
5622 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
5623 FieldNames[0] = "__stack";
5624
5625 // void *__gr_top;
5626 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
5627 FieldNames[1] = "__gr_top";
5628
5629 // void *__vr_top;
5630 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5631 FieldNames[2] = "__vr_top";
5632
5633 // int __gr_offs;
5634 FieldTypes[3] = Context->IntTy;
5635 FieldNames[3] = "__gr_offs";
5636
5637 // int __vr_offs;
5638 FieldTypes[4] = Context->IntTy;
5639 FieldNames[4] = "__vr_offs";
5640
5641 // Create fields
5642 for (unsigned i = 0; i < NumFields; ++i) {
5643 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5644 VaListTagDecl,
5645 SourceLocation(),
5646 SourceLocation(),
5647 &Context->Idents.get(FieldNames[i]),
5648 FieldTypes[i], /*TInfo=*/0,
5649 /*BitWidth=*/0,
5650 /*Mutable=*/false,
5651 ICIS_NoInit);
5652 Field->setAccess(AS_public);
5653 VaListTagDecl->addDecl(Field);
5654 }
5655 VaListTagDecl->completeDefinition();
5656 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5657 Context->VaListTagTy = VaListTagType;
5658
5659 // } __builtin_va_list;
5660 TypedefDecl *VaListTypedefDecl
5661 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5662 Context->getTranslationUnitDecl(),
5663 SourceLocation(), SourceLocation(),
5664 &Context->Idents.get("__builtin_va_list"),
5665 Context->getTrivialTypeSourceInfo(VaListTagType));
5666
5667 return VaListTypedefDecl;
5668}
5669
Meador Inge5d3fb222012-06-16 03:34:49 +00005670static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5671 // typedef struct __va_list_tag {
5672 RecordDecl *VaListTagDecl;
5673
5674 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5675 Context->getTranslationUnitDecl(),
5676 &Context->Idents.get("__va_list_tag"));
5677 VaListTagDecl->startDefinition();
5678
5679 const size_t NumFields = 5;
5680 QualType FieldTypes[NumFields];
5681 const char *FieldNames[NumFields];
5682
5683 // unsigned char gpr;
5684 FieldTypes[0] = Context->UnsignedCharTy;
5685 FieldNames[0] = "gpr";
5686
5687 // unsigned char fpr;
5688 FieldTypes[1] = Context->UnsignedCharTy;
5689 FieldNames[1] = "fpr";
5690
5691 // unsigned short reserved;
5692 FieldTypes[2] = Context->UnsignedShortTy;
5693 FieldNames[2] = "reserved";
5694
5695 // void* overflow_arg_area;
5696 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5697 FieldNames[3] = "overflow_arg_area";
5698
5699 // void* reg_save_area;
5700 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5701 FieldNames[4] = "reg_save_area";
5702
5703 // Create fields
5704 for (unsigned i = 0; i < NumFields; ++i) {
5705 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5706 SourceLocation(),
5707 SourceLocation(),
5708 &Context->Idents.get(FieldNames[i]),
5709 FieldTypes[i], /*TInfo=*/0,
5710 /*BitWidth=*/0,
5711 /*Mutable=*/false,
5712 ICIS_NoInit);
5713 Field->setAccess(AS_public);
5714 VaListTagDecl->addDecl(Field);
5715 }
5716 VaListTagDecl->completeDefinition();
5717 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005718 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005719
5720 // } __va_list_tag;
5721 TypedefDecl *VaListTagTypedefDecl
5722 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5723 Context->getTranslationUnitDecl(),
5724 SourceLocation(), SourceLocation(),
5725 &Context->Idents.get("__va_list_tag"),
5726 Context->getTrivialTypeSourceInfo(VaListTagType));
5727 QualType VaListTagTypedefType =
5728 Context->getTypedefType(VaListTagTypedefDecl);
5729
5730 // typedef __va_list_tag __builtin_va_list[1];
5731 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5732 QualType VaListTagArrayType
5733 = Context->getConstantArrayType(VaListTagTypedefType,
5734 Size, ArrayType::Normal, 0);
5735 TypeSourceInfo *TInfo
5736 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5737 TypedefDecl *VaListTypedefDecl
5738 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5739 Context->getTranslationUnitDecl(),
5740 SourceLocation(), SourceLocation(),
5741 &Context->Idents.get("__builtin_va_list"),
5742 TInfo);
5743
5744 return VaListTypedefDecl;
5745}
5746
5747static TypedefDecl *
5748CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5749 // typedef struct __va_list_tag {
5750 RecordDecl *VaListTagDecl;
5751 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5752 Context->getTranslationUnitDecl(),
5753 &Context->Idents.get("__va_list_tag"));
5754 VaListTagDecl->startDefinition();
5755
5756 const size_t NumFields = 4;
5757 QualType FieldTypes[NumFields];
5758 const char *FieldNames[NumFields];
5759
5760 // unsigned gp_offset;
5761 FieldTypes[0] = Context->UnsignedIntTy;
5762 FieldNames[0] = "gp_offset";
5763
5764 // unsigned fp_offset;
5765 FieldTypes[1] = Context->UnsignedIntTy;
5766 FieldNames[1] = "fp_offset";
5767
5768 // void* overflow_arg_area;
5769 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5770 FieldNames[2] = "overflow_arg_area";
5771
5772 // void* reg_save_area;
5773 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5774 FieldNames[3] = "reg_save_area";
5775
5776 // Create fields
5777 for (unsigned i = 0; i < NumFields; ++i) {
5778 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5779 VaListTagDecl,
5780 SourceLocation(),
5781 SourceLocation(),
5782 &Context->Idents.get(FieldNames[i]),
5783 FieldTypes[i], /*TInfo=*/0,
5784 /*BitWidth=*/0,
5785 /*Mutable=*/false,
5786 ICIS_NoInit);
5787 Field->setAccess(AS_public);
5788 VaListTagDecl->addDecl(Field);
5789 }
5790 VaListTagDecl->completeDefinition();
5791 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005792 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005793
5794 // } __va_list_tag;
5795 TypedefDecl *VaListTagTypedefDecl
5796 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5797 Context->getTranslationUnitDecl(),
5798 SourceLocation(), SourceLocation(),
5799 &Context->Idents.get("__va_list_tag"),
5800 Context->getTrivialTypeSourceInfo(VaListTagType));
5801 QualType VaListTagTypedefType =
5802 Context->getTypedefType(VaListTagTypedefDecl);
5803
5804 // typedef __va_list_tag __builtin_va_list[1];
5805 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5806 QualType VaListTagArrayType
5807 = Context->getConstantArrayType(VaListTagTypedefType,
5808 Size, ArrayType::Normal,0);
5809 TypeSourceInfo *TInfo
5810 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5811 TypedefDecl *VaListTypedefDecl
5812 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5813 Context->getTranslationUnitDecl(),
5814 SourceLocation(), SourceLocation(),
5815 &Context->Idents.get("__builtin_va_list"),
5816 TInfo);
5817
5818 return VaListTypedefDecl;
5819}
5820
5821static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5822 // typedef int __builtin_va_list[4];
5823 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5824 QualType IntArrayType
5825 = Context->getConstantArrayType(Context->IntTy,
5826 Size, ArrayType::Normal, 0);
5827 TypedefDecl *VaListTypedefDecl
5828 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5829 Context->getTranslationUnitDecl(),
5830 SourceLocation(), SourceLocation(),
5831 &Context->Idents.get("__builtin_va_list"),
5832 Context->getTrivialTypeSourceInfo(IntArrayType));
5833
5834 return VaListTypedefDecl;
5835}
5836
Logan Chien57086ce2012-10-10 06:56:20 +00005837static TypedefDecl *
5838CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
5839 RecordDecl *VaListDecl;
5840 if (Context->getLangOpts().CPlusPlus) {
5841 // namespace std { struct __va_list {
5842 NamespaceDecl *NS;
5843 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5844 Context->getTranslationUnitDecl(),
5845 /*Inline*/false, SourceLocation(),
5846 SourceLocation(), &Context->Idents.get("std"),
5847 /*PrevDecl*/0);
5848
5849 VaListDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5850 Context->getTranslationUnitDecl(),
5851 SourceLocation(), SourceLocation(),
5852 &Context->Idents.get("__va_list"));
5853
5854 VaListDecl->setDeclContext(NS);
5855
5856 } else {
5857 // struct __va_list {
5858 VaListDecl = CreateRecordDecl(*Context, TTK_Struct,
5859 Context->getTranslationUnitDecl(),
5860 &Context->Idents.get("__va_list"));
5861 }
5862
5863 VaListDecl->startDefinition();
5864
5865 // void * __ap;
5866 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5867 VaListDecl,
5868 SourceLocation(),
5869 SourceLocation(),
5870 &Context->Idents.get("__ap"),
5871 Context->getPointerType(Context->VoidTy),
5872 /*TInfo=*/0,
5873 /*BitWidth=*/0,
5874 /*Mutable=*/false,
5875 ICIS_NoInit);
5876 Field->setAccess(AS_public);
5877 VaListDecl->addDecl(Field);
5878
5879 // };
5880 VaListDecl->completeDefinition();
5881
5882 // typedef struct __va_list __builtin_va_list;
5883 TypeSourceInfo *TInfo
5884 = Context->getTrivialTypeSourceInfo(Context->getRecordType(VaListDecl));
5885
5886 TypedefDecl *VaListTypeDecl
5887 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5888 Context->getTranslationUnitDecl(),
5889 SourceLocation(), SourceLocation(),
5890 &Context->Idents.get("__builtin_va_list"),
5891 TInfo);
5892
5893 return VaListTypeDecl;
5894}
5895
Meador Inge5d3fb222012-06-16 03:34:49 +00005896static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
5897 TargetInfo::BuiltinVaListKind Kind) {
5898 switch (Kind) {
5899 case TargetInfo::CharPtrBuiltinVaList:
5900 return CreateCharPtrBuiltinVaListDecl(Context);
5901 case TargetInfo::VoidPtrBuiltinVaList:
5902 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00005903 case TargetInfo::AArch64ABIBuiltinVaList:
5904 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00005905 case TargetInfo::PowerABIBuiltinVaList:
5906 return CreatePowerABIBuiltinVaListDecl(Context);
5907 case TargetInfo::X86_64ABIBuiltinVaList:
5908 return CreateX86_64ABIBuiltinVaListDecl(Context);
5909 case TargetInfo::PNaClABIBuiltinVaList:
5910 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00005911 case TargetInfo::AAPCSABIBuiltinVaList:
5912 return CreateAAPCSABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00005913 }
5914
5915 llvm_unreachable("Unhandled __builtin_va_list type kind");
5916}
5917
5918TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
5919 if (!BuiltinVaListDecl)
5920 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
5921
5922 return BuiltinVaListDecl;
5923}
5924
Meador Ingecfb60902012-07-01 15:57:25 +00005925QualType ASTContext::getVaListTagType() const {
5926 // Force the creation of VaListTagTy by building the __builtin_va_list
5927 // declaration.
5928 if (VaListTagTy.isNull())
5929 (void) getBuiltinVaListDecl();
5930
5931 return VaListTagTy;
5932}
5933
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005934void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00005935 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00005936 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00005937
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005938 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00005939}
5940
John McCalld28ae272009-12-02 08:04:21 +00005941/// \brief Retrieve the template name that corresponds to a non-empty
5942/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00005943TemplateName
5944ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
5945 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00005946 unsigned size = End - Begin;
5947 assert(size > 1 && "set is not overloaded!");
5948
5949 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
5950 size * sizeof(FunctionTemplateDecl*));
5951 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
5952
5953 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00005954 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00005955 NamedDecl *D = *I;
5956 assert(isa<FunctionTemplateDecl>(D) ||
5957 (isa<UsingShadowDecl>(D) &&
5958 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
5959 *Storage++ = D;
5960 }
5961
5962 return TemplateName(OT);
5963}
5964
Douglas Gregordc572a32009-03-30 22:58:21 +00005965/// \brief Retrieve the template name that represents a qualified
5966/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00005967TemplateName
5968ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
5969 bool TemplateKeyword,
5970 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00005971 assert(NNS && "Missing nested-name-specifier in qualified template name");
5972
Douglas Gregorc42075a2010-02-04 18:10:26 +00005973 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00005974 llvm::FoldingSetNodeID ID;
5975 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
5976
5977 void *InsertPos = 0;
5978 QualifiedTemplateName *QTN =
5979 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5980 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00005981 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
5982 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00005983 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
5984 }
5985
5986 return TemplateName(QTN);
5987}
5988
5989/// \brief Retrieve the template name that represents a dependent
5990/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00005991TemplateName
5992ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
5993 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00005994 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00005995 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00005996
5997 llvm::FoldingSetNodeID ID;
5998 DependentTemplateName::Profile(ID, NNS, Name);
5999
6000 void *InsertPos = 0;
6001 DependentTemplateName *QTN =
6002 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6003
6004 if (QTN)
6005 return TemplateName(QTN);
6006
6007 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6008 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006009 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6010 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00006011 } else {
6012 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00006013 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6014 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006015 DependentTemplateName *CheckQTN =
6016 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6017 assert(!CheckQTN && "Dependent type name canonicalization broken");
6018 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00006019 }
6020
6021 DependentTemplateNames.InsertNode(QTN, InsertPos);
6022 return TemplateName(QTN);
6023}
6024
Douglas Gregor71395fa2009-11-04 00:56:37 +00006025/// \brief Retrieve the template name that represents a dependent
6026/// template name such as \c MetaFun::template operator+.
6027TemplateName
6028ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00006029 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00006030 assert((!NNS || NNS->isDependent()) &&
6031 "Nested name specifier must be dependent");
6032
6033 llvm::FoldingSetNodeID ID;
6034 DependentTemplateName::Profile(ID, NNS, Operator);
6035
6036 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00006037 DependentTemplateName *QTN
6038 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006039
6040 if (QTN)
6041 return TemplateName(QTN);
6042
6043 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6044 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006045 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6046 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006047 } else {
6048 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00006049 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6050 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006051
6052 DependentTemplateName *CheckQTN
6053 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6054 assert(!CheckQTN && "Dependent template name canonicalization broken");
6055 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00006056 }
6057
6058 DependentTemplateNames.InsertNode(QTN, InsertPos);
6059 return TemplateName(QTN);
6060}
6061
Douglas Gregor5590be02011-01-15 06:45:20 +00006062TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00006063ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6064 TemplateName replacement) const {
6065 llvm::FoldingSetNodeID ID;
6066 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
6067
6068 void *insertPos = 0;
6069 SubstTemplateTemplateParmStorage *subst
6070 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6071
6072 if (!subst) {
6073 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6074 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6075 }
6076
6077 return TemplateName(subst);
6078}
6079
6080TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00006081ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6082 const TemplateArgument &ArgPack) const {
6083 ASTContext &Self = const_cast<ASTContext &>(*this);
6084 llvm::FoldingSetNodeID ID;
6085 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
6086
6087 void *InsertPos = 0;
6088 SubstTemplateTemplateParmPackStorage *Subst
6089 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6090
6091 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00006092 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00006093 ArgPack.pack_size(),
6094 ArgPack.pack_begin());
6095 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6096 }
6097
6098 return TemplateName(Subst);
6099}
6100
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006101/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00006102/// TargetInfo, produce the corresponding type. The unsigned @p Type
6103/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00006104CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006105 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00006106 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006107 case TargetInfo::SignedShort: return ShortTy;
6108 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6109 case TargetInfo::SignedInt: return IntTy;
6110 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6111 case TargetInfo::SignedLong: return LongTy;
6112 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6113 case TargetInfo::SignedLongLong: return LongLongTy;
6114 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6115 }
6116
David Blaikie83d382b2011-09-23 05:06:16 +00006117 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006118}
Ted Kremenek77c51b22008-07-24 23:58:27 +00006119
6120//===----------------------------------------------------------------------===//
6121// Type Predicates.
6122//===----------------------------------------------------------------------===//
6123
Fariborz Jahanian96207692009-02-18 21:49:28 +00006124/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6125/// garbage collection attribute.
6126///
John McCall553d45a2011-01-12 00:34:59 +00006127Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006128 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00006129 return Qualifiers::GCNone;
6130
David Blaikiebbafb8a2012-03-11 07:00:24 +00006131 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00006132 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6133
6134 // Default behaviour under objective-C's gc is for ObjC pointers
6135 // (or pointers to them) be treated as though they were declared
6136 // as __strong.
6137 if (GCAttrs == Qualifiers::GCNone) {
6138 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6139 return Qualifiers::Strong;
6140 else if (Ty->isPointerType())
6141 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6142 } else {
6143 // It's not valid to set GC attributes on anything that isn't a
6144 // pointer.
6145#ifndef NDEBUG
6146 QualType CT = Ty->getCanonicalTypeInternal();
6147 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6148 CT = AT->getElementType();
6149 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6150#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00006151 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00006152 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00006153}
6154
Chris Lattner49af6a42008-04-07 06:51:04 +00006155//===----------------------------------------------------------------------===//
6156// Type Compatibility Testing
6157//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00006158
Mike Stump11289f42009-09-09 15:08:12 +00006159/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006160/// compatible.
6161static bool areCompatVectorTypes(const VectorType *LHS,
6162 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00006163 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00006164 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00006165 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00006166}
6167
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006168bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6169 QualType SecondVec) {
6170 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6171 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6172
6173 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6174 return true;
6175
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006176 // Treat Neon vector types and most AltiVec vector types as if they are the
6177 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006178 const VectorType *First = FirstVec->getAs<VectorType>();
6179 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006180 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006181 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006182 First->getVectorKind() != VectorType::AltiVecPixel &&
6183 First->getVectorKind() != VectorType::AltiVecBool &&
6184 Second->getVectorKind() != VectorType::AltiVecPixel &&
6185 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006186 return true;
6187
6188 return false;
6189}
6190
Steve Naroff8e6aee52009-07-23 01:01:38 +00006191//===----------------------------------------------------------------------===//
6192// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6193//===----------------------------------------------------------------------===//
6194
6195/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6196/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00006197bool
6198ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6199 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00006200 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006201 return true;
6202 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
6203 E = rProto->protocol_end(); PI != E; ++PI)
6204 if (ProtocolCompatibleWithProtocol(lProto, *PI))
6205 return true;
6206 return false;
6207}
6208
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006209/// QualifiedIdConformsQualifiedId - compare id<pr,...> with id<pr1,...>
Steve Naroff8e6aee52009-07-23 01:01:38 +00006210/// return true if lhs's protocols conform to rhs's protocol; false
6211/// otherwise.
6212bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
6213 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
6214 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
6215 return false;
6216}
6217
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006218/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6219/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006220bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6221 QualType rhs) {
6222 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6223 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6224 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6225
6226 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6227 E = lhsQID->qual_end(); I != E; ++I) {
6228 bool match = false;
6229 ObjCProtocolDecl *lhsProto = *I;
6230 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6231 E = rhsOPT->qual_end(); J != E; ++J) {
6232 ObjCProtocolDecl *rhsProto = *J;
6233 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6234 match = true;
6235 break;
6236 }
6237 }
6238 if (!match)
6239 return false;
6240 }
6241 return true;
6242}
6243
Steve Naroff8e6aee52009-07-23 01:01:38 +00006244/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6245/// ObjCQualifiedIDType.
6246bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6247 bool compare) {
6248 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00006249 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006250 lhs->isObjCIdType() || lhs->isObjCClassType())
6251 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006252 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006253 rhs->isObjCIdType() || rhs->isObjCClassType())
6254 return true;
6255
6256 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00006257 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006258
Steve Naroff8e6aee52009-07-23 01:01:38 +00006259 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00006260
Steve Naroff8e6aee52009-07-23 01:01:38 +00006261 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00006262 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006263 // make sure we check the class hierarchy.
6264 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6265 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6266 E = lhsQID->qual_end(); I != E; ++I) {
6267 // when comparing an id<P> on lhs with a static type on rhs,
6268 // see if static class implements all of id's protocols, directly or
6269 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00006270 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006271 return false;
6272 }
6273 }
6274 // If there are no qualifiers and no interface, we have an 'id'.
6275 return true;
6276 }
Mike Stump11289f42009-09-09 15:08:12 +00006277 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006278 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6279 E = lhsQID->qual_end(); I != E; ++I) {
6280 ObjCProtocolDecl *lhsProto = *I;
6281 bool match = false;
6282
6283 // when comparing an id<P> on lhs with a static type on rhs,
6284 // see if static class implements all of id's protocols, directly or
6285 // through its super class and categories.
6286 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6287 E = rhsOPT->qual_end(); J != E; ++J) {
6288 ObjCProtocolDecl *rhsProto = *J;
6289 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6290 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6291 match = true;
6292 break;
6293 }
6294 }
Mike Stump11289f42009-09-09 15:08:12 +00006295 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006296 // make sure we check the class hierarchy.
6297 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6298 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6299 E = lhsQID->qual_end(); I != E; ++I) {
6300 // when comparing an id<P> on lhs with a static type on rhs,
6301 // see if static class implements all of id's protocols, directly or
6302 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00006303 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006304 match = true;
6305 break;
6306 }
6307 }
6308 }
6309 if (!match)
6310 return false;
6311 }
Mike Stump11289f42009-09-09 15:08:12 +00006312
Steve Naroff8e6aee52009-07-23 01:01:38 +00006313 return true;
6314 }
Mike Stump11289f42009-09-09 15:08:12 +00006315
Steve Naroff8e6aee52009-07-23 01:01:38 +00006316 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6317 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6318
Mike Stump11289f42009-09-09 15:08:12 +00006319 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00006320 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006321 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006322 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
6323 E = lhsOPT->qual_end(); I != E; ++I) {
6324 ObjCProtocolDecl *lhsProto = *I;
6325 bool match = false;
6326
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006327 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00006328 // see if static class implements all of id's protocols, directly or
6329 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006330 // First, lhs protocols in the qualifier list must be found, direct
6331 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006332 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6333 E = rhsQID->qual_end(); J != E; ++J) {
6334 ObjCProtocolDecl *rhsProto = *J;
6335 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6336 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6337 match = true;
6338 break;
6339 }
6340 }
6341 if (!match)
6342 return false;
6343 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006344
6345 // Static class's protocols, or its super class or category protocols
6346 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6347 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6348 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6349 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6350 // This is rather dubious but matches gcc's behavior. If lhs has
6351 // no type qualifier and its class has no static protocol(s)
6352 // assume that it is mismatch.
6353 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6354 return false;
6355 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6356 LHSInheritedProtocols.begin(),
6357 E = LHSInheritedProtocols.end(); I != E; ++I) {
6358 bool match = false;
6359 ObjCProtocolDecl *lhsProto = (*I);
6360 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6361 E = rhsQID->qual_end(); J != E; ++J) {
6362 ObjCProtocolDecl *rhsProto = *J;
6363 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6364 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6365 match = true;
6366 break;
6367 }
6368 }
6369 if (!match)
6370 return false;
6371 }
6372 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00006373 return true;
6374 }
6375 return false;
6376}
6377
Eli Friedman47f77112008-08-22 00:56:42 +00006378/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006379/// compatible for assignment from RHS to LHS. This handles validation of any
6380/// protocol qualifiers on the LHS or RHS.
6381///
Steve Naroff7cae42b2009-07-10 23:34:53 +00006382bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6383 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00006384 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6385 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6386
Steve Naroff1329fa02009-07-15 18:40:39 +00006387 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00006388 if (LHS->isObjCUnqualifiedIdOrClass() ||
6389 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00006390 return true;
6391
John McCall8b07ec22010-05-15 11:32:37 +00006392 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00006393 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6394 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00006395 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006396
6397 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6398 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6399 QualType(RHSOPT,0));
6400
John McCall8b07ec22010-05-15 11:32:37 +00006401 // If we have 2 user-defined types, fall into that path.
6402 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00006403 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006404
Steve Naroff8e6aee52009-07-23 01:01:38 +00006405 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006406}
6407
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006408/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00006409/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006410/// arguments in block literals. When passed as arguments, passing 'A*' where
6411/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6412/// not OK. For the return type, the opposite is not OK.
6413bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6414 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006415 const ObjCObjectPointerType *RHSOPT,
6416 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006417 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006418 return true;
6419
6420 if (LHSOPT->isObjCBuiltinType()) {
6421 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6422 }
6423
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006424 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006425 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6426 QualType(RHSOPT,0),
6427 false);
6428
6429 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6430 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6431 if (LHS && RHS) { // We have 2 user-defined types.
6432 if (LHS != RHS) {
6433 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006434 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006435 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006436 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006437 }
6438 else
6439 return true;
6440 }
6441 return false;
6442}
6443
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006444/// getIntersectionOfProtocols - This routine finds the intersection of set
6445/// of protocols inherited from two distinct objective-c pointer objects.
6446/// It is used to build composite qualifier list of the composite type of
6447/// the conditional expression involving two objective-c pointer objects.
6448static
6449void getIntersectionOfProtocols(ASTContext &Context,
6450 const ObjCObjectPointerType *LHSOPT,
6451 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006452 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006453
John McCall8b07ec22010-05-15 11:32:37 +00006454 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6455 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6456 assert(LHS->getInterface() && "LHS must have an interface base");
6457 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006458
6459 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6460 unsigned LHSNumProtocols = LHS->getNumProtocols();
6461 if (LHSNumProtocols > 0)
6462 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6463 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006464 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006465 Context.CollectInheritedProtocols(LHS->getInterface(),
6466 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006467 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6468 LHSInheritedProtocols.end());
6469 }
6470
6471 unsigned RHSNumProtocols = RHS->getNumProtocols();
6472 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00006473 ObjCProtocolDecl **RHSProtocols =
6474 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006475 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6476 if (InheritedProtocolSet.count(RHSProtocols[i]))
6477 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00006478 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006479 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006480 Context.CollectInheritedProtocols(RHS->getInterface(),
6481 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006482 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6483 RHSInheritedProtocols.begin(),
6484 E = RHSInheritedProtocols.end(); I != E; ++I)
6485 if (InheritedProtocolSet.count((*I)))
6486 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006487 }
6488}
6489
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006490/// areCommonBaseCompatible - Returns common base class of the two classes if
6491/// one found. Note that this is O'2 algorithm. But it will be called as the
6492/// last type comparison in a ?-exp of ObjC pointer types before a
6493/// warning is issued. So, its invokation is extremely rare.
6494QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00006495 const ObjCObjectPointerType *Lptr,
6496 const ObjCObjectPointerType *Rptr) {
6497 const ObjCObjectType *LHS = Lptr->getObjectType();
6498 const ObjCObjectType *RHS = Rptr->getObjectType();
6499 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6500 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00006501 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006502 return QualType();
6503
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006504 do {
John McCall8b07ec22010-05-15 11:32:37 +00006505 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006506 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006507 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00006508 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6509
6510 QualType Result = QualType(LHS, 0);
6511 if (!Protocols.empty())
6512 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6513 Result = getObjCObjectPointerType(Result);
6514 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006515 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006516 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006517
6518 return QualType();
6519}
6520
John McCall8b07ec22010-05-15 11:32:37 +00006521bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6522 const ObjCObjectType *RHS) {
6523 assert(LHS->getInterface() && "LHS is not an interface type");
6524 assert(RHS->getInterface() && "RHS is not an interface type");
6525
Chris Lattner49af6a42008-04-07 06:51:04 +00006526 // Verify that the base decls are compatible: the RHS must be a subclass of
6527 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00006528 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00006529 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006530
Chris Lattner49af6a42008-04-07 06:51:04 +00006531 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6532 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00006533 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00006534 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006535
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006536 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6537 // more detailed analysis is required.
6538 if (RHS->getNumProtocols() == 0) {
6539 // OK, if LHS is a superclass of RHS *and*
6540 // this superclass is assignment compatible with LHS.
6541 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006542 bool IsSuperClass =
6543 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6544 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006545 // OK if conversion of LHS to SuperClass results in narrowing of types
6546 // ; i.e., SuperClass may implement at least one of the protocols
6547 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6548 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6549 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006550 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006551 // If super class has no protocols, it is not a match.
6552 if (SuperClassInheritedProtocols.empty())
6553 return false;
6554
6555 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6556 LHSPE = LHS->qual_end();
6557 LHSPI != LHSPE; LHSPI++) {
6558 bool SuperImplementsProtocol = false;
6559 ObjCProtocolDecl *LHSProto = (*LHSPI);
6560
6561 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6562 SuperClassInheritedProtocols.begin(),
6563 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6564 ObjCProtocolDecl *SuperClassProto = (*I);
6565 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6566 SuperImplementsProtocol = true;
6567 break;
6568 }
6569 }
6570 if (!SuperImplementsProtocol)
6571 return false;
6572 }
6573 return true;
6574 }
6575 return false;
6576 }
Mike Stump11289f42009-09-09 15:08:12 +00006577
John McCall8b07ec22010-05-15 11:32:37 +00006578 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6579 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00006580 LHSPI != LHSPE; LHSPI++) {
6581 bool RHSImplementsProtocol = false;
6582
6583 // If the RHS doesn't implement the protocol on the left, the types
6584 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00006585 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6586 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00006587 RHSPI != RHSPE; RHSPI++) {
6588 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00006589 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00006590 break;
6591 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006592 }
6593 // FIXME: For better diagnostics, consider passing back the protocol name.
6594 if (!RHSImplementsProtocol)
6595 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00006596 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006597 // The RHS implements all protocols listed on the LHS.
6598 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00006599}
6600
Steve Naroffb7605152009-02-12 17:52:19 +00006601bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6602 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00006603 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6604 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006605
Steve Naroff7cae42b2009-07-10 23:34:53 +00006606 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00006607 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006608
6609 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6610 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00006611}
6612
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006613bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6614 return canAssignObjCInterfaces(
6615 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6616 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6617}
6618
Mike Stump11289f42009-09-09 15:08:12 +00006619/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00006620/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00006621/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00006622/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006623bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6624 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006625 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00006626 return hasSameType(LHS, RHS);
6627
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006628 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00006629}
6630
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006631bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00006632 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006633}
6634
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006635bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6636 return !mergeTypes(LHS, RHS, true).isNull();
6637}
6638
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006639/// mergeTransparentUnionType - if T is a transparent union type and a member
6640/// of T is compatible with SubType, return the merged type, else return
6641/// QualType()
6642QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6643 bool OfBlockPointer,
6644 bool Unqualified) {
6645 if (const RecordType *UT = T->getAsUnionType()) {
6646 RecordDecl *UD = UT->getDecl();
6647 if (UD->hasAttr<TransparentUnionAttr>()) {
6648 for (RecordDecl::field_iterator it = UD->field_begin(),
6649 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00006650 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006651 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6652 if (!MT.isNull())
6653 return MT;
6654 }
6655 }
6656 }
6657
6658 return QualType();
6659}
6660
6661/// mergeFunctionArgumentTypes - merge two types which appear as function
6662/// argument types
6663QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
6664 bool OfBlockPointer,
6665 bool Unqualified) {
6666 // GNU extension: two types are compatible if they appear as a function
6667 // argument, one of the types is a transparent union type and the other
6668 // type is compatible with a union member
6669 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6670 Unqualified);
6671 if (!lmerge.isNull())
6672 return lmerge;
6673
6674 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6675 Unqualified);
6676 if (!rmerge.isNull())
6677 return rmerge;
6678
6679 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6680}
6681
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006682QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006683 bool OfBlockPointer,
6684 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00006685 const FunctionType *lbase = lhs->getAs<FunctionType>();
6686 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006687 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6688 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00006689 bool allLTypes = true;
6690 bool allRTypes = true;
6691
6692 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006693 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00006694 if (OfBlockPointer) {
6695 QualType RHS = rbase->getResultType();
6696 QualType LHS = lbase->getResultType();
6697 bool UnqualifiedResult = Unqualified;
6698 if (!UnqualifiedResult)
6699 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006700 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00006701 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006702 else
John McCall8c6b56f2010-12-15 01:06:38 +00006703 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6704 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006705 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006706
6707 if (Unqualified)
6708 retType = retType.getUnqualifiedType();
6709
6710 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6711 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6712 if (Unqualified) {
6713 LRetType = LRetType.getUnqualifiedType();
6714 RRetType = RRetType.getUnqualifiedType();
6715 }
6716
6717 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006718 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006719 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006720 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006721
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00006722 // FIXME: double check this
6723 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6724 // rbase->getRegParmAttr() != 0 &&
6725 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00006726 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6727 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00006728
Douglas Gregor8c940862010-01-18 17:14:39 +00006729 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00006730 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00006731 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006732
John McCall8c6b56f2010-12-15 01:06:38 +00006733 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00006734 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6735 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00006736 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6737 return QualType();
6738
John McCall31168b02011-06-15 23:02:42 +00006739 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6740 return QualType();
6741
John McCall8c6b56f2010-12-15 01:06:38 +00006742 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6743 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00006744
Rafael Espindola8778c282012-11-29 16:09:03 +00006745 if (lbaseInfo.getNoReturn() != NoReturn)
6746 allLTypes = false;
6747 if (rbaseInfo.getNoReturn() != NoReturn)
6748 allRTypes = false;
6749
John McCall31168b02011-06-15 23:02:42 +00006750 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00006751
Eli Friedman47f77112008-08-22 00:56:42 +00006752 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006753 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6754 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006755 unsigned lproto_nargs = lproto->getNumArgs();
6756 unsigned rproto_nargs = rproto->getNumArgs();
6757
6758 // Compatible functions must have the same number of arguments
6759 if (lproto_nargs != rproto_nargs)
6760 return QualType();
6761
6762 // Variadic and non-variadic functions aren't compatible
6763 if (lproto->isVariadic() != rproto->isVariadic())
6764 return QualType();
6765
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00006766 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6767 return QualType();
6768
Fariborz Jahanian97676972011-09-28 21:52:05 +00006769 if (LangOpts.ObjCAutoRefCount &&
6770 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6771 return QualType();
6772
Eli Friedman47f77112008-08-22 00:56:42 +00006773 // Check argument compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006774 SmallVector<QualType, 10> types;
Eli Friedman47f77112008-08-22 00:56:42 +00006775 for (unsigned i = 0; i < lproto_nargs; i++) {
6776 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
6777 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006778 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
6779 OfBlockPointer,
6780 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006781 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006782
6783 if (Unqualified)
6784 argtype = argtype.getUnqualifiedType();
6785
Eli Friedman47f77112008-08-22 00:56:42 +00006786 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006787 if (Unqualified) {
6788 largtype = largtype.getUnqualifiedType();
6789 rargtype = rargtype.getUnqualifiedType();
6790 }
6791
Chris Lattner465fa322008-10-05 17:34:18 +00006792 if (getCanonicalType(argtype) != getCanonicalType(largtype))
6793 allLTypes = false;
6794 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
6795 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00006796 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00006797
Eli Friedman47f77112008-08-22 00:56:42 +00006798 if (allLTypes) return lhs;
6799 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006800
6801 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
6802 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00006803 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006804 }
6805
6806 if (lproto) allRTypes = false;
6807 if (rproto) allLTypes = false;
6808
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006809 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00006810 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006811 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006812 if (proto->isVariadic()) return QualType();
6813 // Check that the types are compatible with the types that
6814 // would result from default argument promotions (C99 6.7.5.3p15).
6815 // The only types actually affected are promotable integer
6816 // types and floats, which would be passed as a different
6817 // type depending on whether the prototype is visible.
6818 unsigned proto_nargs = proto->getNumArgs();
6819 for (unsigned i = 0; i < proto_nargs; ++i) {
6820 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00006821
Eli Friedman448ce402012-08-30 00:44:15 +00006822 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00006823 // to pass enum values.
Eli Friedman448ce402012-08-30 00:44:15 +00006824 if (const EnumType *Enum = argTy->getAs<EnumType>()) {
6825 argTy = Enum->getDecl()->getIntegerType();
6826 if (argTy.isNull())
6827 return QualType();
6828 }
Douglas Gregor2973d402010-02-03 19:27:29 +00006829
Eli Friedman47f77112008-08-22 00:56:42 +00006830 if (argTy->isPromotableIntegerType() ||
6831 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
6832 return QualType();
6833 }
6834
6835 if (allLTypes) return lhs;
6836 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006837
6838 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
6839 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00006840 return getFunctionType(retType,
6841 ArrayRef<QualType>(proto->arg_type_begin(),
6842 proto->getNumArgs()),
6843 EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00006844 }
6845
6846 if (allLTypes) return lhs;
6847 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00006848 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00006849}
6850
John McCall433c2e62013-03-21 00:10:07 +00006851/// Given that we have an enum type and a non-enum type, try to merge them.
6852static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
6853 QualType other, bool isBlockReturnType) {
6854 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
6855 // a signed integer type, or an unsigned integer type.
6856 // Compatibility is based on the underlying type, not the promotion
6857 // type.
6858 QualType underlyingType = ET->getDecl()->getIntegerType();
6859 if (underlyingType.isNull()) return QualType();
6860 if (Context.hasSameType(underlyingType, other))
6861 return other;
6862
6863 // In block return types, we're more permissive and accept any
6864 // integral type of the same size.
6865 if (isBlockReturnType && other->isIntegerType() &&
6866 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
6867 return other;
6868
6869 return QualType();
6870}
6871
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006872QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006873 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006874 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00006875 // C++ [expr]: If an expression initially has the type "reference to T", the
6876 // type is adjusted to "T" prior to any further analysis, the expression
6877 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006878 // expression is an lvalue unless the reference is an rvalue reference and
6879 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00006880 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
6881 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006882
6883 if (Unqualified) {
6884 LHS = LHS.getUnqualifiedType();
6885 RHS = RHS.getUnqualifiedType();
6886 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00006887
Eli Friedman47f77112008-08-22 00:56:42 +00006888 QualType LHSCan = getCanonicalType(LHS),
6889 RHSCan = getCanonicalType(RHS);
6890
6891 // If two types are identical, they are compatible.
6892 if (LHSCan == RHSCan)
6893 return LHS;
6894
John McCall8ccfcb52009-09-24 19:53:00 +00006895 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006896 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6897 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00006898 if (LQuals != RQuals) {
6899 // If any of these qualifiers are different, we have a type
6900 // mismatch.
6901 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00006902 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
6903 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00006904 return QualType();
6905
6906 // Exactly one GC qualifier difference is allowed: __strong is
6907 // okay if the other type has no GC qualifier but is an Objective
6908 // C object pointer (i.e. implicitly strong by default). We fix
6909 // this by pretending that the unqualified type was actually
6910 // qualified __strong.
6911 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6912 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6913 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6914
6915 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6916 return QualType();
6917
6918 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
6919 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
6920 }
6921 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
6922 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
6923 }
Eli Friedman47f77112008-08-22 00:56:42 +00006924 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00006925 }
6926
6927 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00006928
Eli Friedmandcca6332009-06-01 01:22:52 +00006929 Type::TypeClass LHSClass = LHSCan->getTypeClass();
6930 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00006931
Chris Lattnerfd652912008-01-14 05:45:46 +00006932 // We want to consider the two function types to be the same for these
6933 // comparisons, just force one to the other.
6934 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
6935 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00006936
6937 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00006938 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
6939 LHSClass = Type::ConstantArray;
6940 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
6941 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00006942
John McCall8b07ec22010-05-15 11:32:37 +00006943 // ObjCInterfaces are just specialized ObjCObjects.
6944 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
6945 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
6946
Nate Begemance4d7fc2008-04-18 23:10:10 +00006947 // Canonicalize ExtVector -> Vector.
6948 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
6949 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00006950
Chris Lattner95554662008-04-07 05:43:21 +00006951 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00006952 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00006953 // Note that we only have special rules for turning block enum
6954 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00006955 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00006956 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00006957 }
John McCall9dd450b2009-09-21 23:43:11 +00006958 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00006959 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00006960 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00006961 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00006962 if (OfBlockPointer && !BlockReturnType) {
6963 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
6964 return LHS;
6965 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
6966 return RHS;
6967 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00006968
Eli Friedman47f77112008-08-22 00:56:42 +00006969 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00006970 }
Eli Friedman47f77112008-08-22 00:56:42 +00006971
Steve Naroffc6edcbd2008-01-09 22:43:08 +00006972 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00006973 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006974#define TYPE(Class, Base)
6975#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00006976#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006977#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
6978#define DEPENDENT_TYPE(Class, Base) case Type::Class:
6979#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00006980 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006981
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006982 case Type::LValueReference:
6983 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006984 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00006985 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006986
John McCall8b07ec22010-05-15 11:32:37 +00006987 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006988 case Type::IncompleteArray:
6989 case Type::VariableArray:
6990 case Type::FunctionProto:
6991 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00006992 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006993
Chris Lattnerfd652912008-01-14 05:45:46 +00006994 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00006995 {
6996 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006997 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
6998 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006999 if (Unqualified) {
7000 LHSPointee = LHSPointee.getUnqualifiedType();
7001 RHSPointee = RHSPointee.getUnqualifiedType();
7002 }
7003 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7004 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007005 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00007006 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007007 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00007008 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007009 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007010 return getPointerType(ResultType);
7011 }
Steve Naroff68e167d2008-12-10 17:49:55 +00007012 case Type::BlockPointer:
7013 {
7014 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007015 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7016 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007017 if (Unqualified) {
7018 LHSPointee = LHSPointee.getUnqualifiedType();
7019 RHSPointee = RHSPointee.getUnqualifiedType();
7020 }
7021 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7022 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00007023 if (ResultType.isNull()) return QualType();
7024 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7025 return LHS;
7026 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7027 return RHS;
7028 return getBlockPointerType(ResultType);
7029 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00007030 case Type::Atomic:
7031 {
7032 // Merge two pointer types, while trying to preserve typedef info
7033 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7034 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7035 if (Unqualified) {
7036 LHSValue = LHSValue.getUnqualifiedType();
7037 RHSValue = RHSValue.getUnqualifiedType();
7038 }
7039 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7040 Unqualified);
7041 if (ResultType.isNull()) return QualType();
7042 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7043 return LHS;
7044 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7045 return RHS;
7046 return getAtomicType(ResultType);
7047 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007048 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00007049 {
7050 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7051 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7052 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7053 return QualType();
7054
7055 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7056 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007057 if (Unqualified) {
7058 LHSElem = LHSElem.getUnqualifiedType();
7059 RHSElem = RHSElem.getUnqualifiedType();
7060 }
7061
7062 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007063 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00007064 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7065 return LHS;
7066 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7067 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00007068 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7069 ArrayType::ArraySizeModifier(), 0);
7070 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7071 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007072 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7073 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00007074 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7075 return LHS;
7076 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7077 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007078 if (LVAT) {
7079 // FIXME: This isn't correct! But tricky to implement because
7080 // the array's size has to be the size of LHS, but the type
7081 // has to be different.
7082 return LHS;
7083 }
7084 if (RVAT) {
7085 // FIXME: This isn't correct! But tricky to implement because
7086 // the array's size has to be the size of RHS, but the type
7087 // has to be different.
7088 return RHS;
7089 }
Eli Friedman3e62c212008-08-22 01:48:21 +00007090 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7091 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00007092 return getIncompleteArrayType(ResultType,
7093 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007094 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007095 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007096 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007097 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007098 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00007099 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00007100 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007101 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00007102 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00007103 case Type::Complex:
7104 // Distinct complex types are incompatible.
7105 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007106 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00007107 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00007108 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7109 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00007110 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00007111 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00007112 case Type::ObjCObject: {
7113 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00007114 // FIXME: This should be type compatibility, e.g. whether
7115 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00007116 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7117 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7118 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00007119 return LHS;
7120
Eli Friedman47f77112008-08-22 00:56:42 +00007121 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00007122 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007123 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007124 if (OfBlockPointer) {
7125 if (canAssignObjCInterfacesInBlockPointer(
7126 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007127 RHS->getAs<ObjCObjectPointerType>(),
7128 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00007129 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007130 return QualType();
7131 }
John McCall9dd450b2009-09-21 23:43:11 +00007132 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7133 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007134 return LHS;
7135
Steve Naroffc68cfcf2008-12-10 22:14:21 +00007136 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00007137 }
Steve Naroff32e44c02007-10-15 20:41:53 +00007138 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007139
David Blaikie8a40f702012-01-17 06:56:22 +00007140 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00007141}
Ted Kremenekfc581a92007-10-31 17:10:13 +00007142
Fariborz Jahanian97676972011-09-28 21:52:05 +00007143bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7144 const FunctionProtoType *FromFunctionType,
7145 const FunctionProtoType *ToFunctionType) {
7146 if (FromFunctionType->hasAnyConsumedArgs() !=
7147 ToFunctionType->hasAnyConsumedArgs())
7148 return false;
7149 FunctionProtoType::ExtProtoInfo FromEPI =
7150 FromFunctionType->getExtProtoInfo();
7151 FunctionProtoType::ExtProtoInfo ToEPI =
7152 ToFunctionType->getExtProtoInfo();
7153 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
7154 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
7155 ArgIdx != NumArgs; ++ArgIdx) {
7156 if (FromEPI.ConsumedArguments[ArgIdx] !=
7157 ToEPI.ConsumedArguments[ArgIdx])
7158 return false;
7159 }
7160 return true;
7161}
7162
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007163/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7164/// 'RHS' attributes and returns the merged version; including for function
7165/// return types.
7166QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7167 QualType LHSCan = getCanonicalType(LHS),
7168 RHSCan = getCanonicalType(RHS);
7169 // If two types are identical, they are compatible.
7170 if (LHSCan == RHSCan)
7171 return LHS;
7172 if (RHSCan->isFunctionType()) {
7173 if (!LHSCan->isFunctionType())
7174 return QualType();
7175 QualType OldReturnType =
7176 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
7177 QualType NewReturnType =
7178 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
7179 QualType ResReturnType =
7180 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7181 if (ResReturnType.isNull())
7182 return QualType();
7183 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7184 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7185 // In either case, use OldReturnType to build the new function type.
7186 const FunctionType *F = LHS->getAs<FunctionType>();
7187 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00007188 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7189 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007190 QualType ResultType
Jordan Rose5c382722013-03-08 21:51:21 +00007191 = getFunctionType(OldReturnType,
7192 ArrayRef<QualType>(FPT->arg_type_begin(),
7193 FPT->getNumArgs()),
7194 EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007195 return ResultType;
7196 }
7197 }
7198 return QualType();
7199 }
7200
7201 // If the qualifiers are different, the types can still be merged.
7202 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7203 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7204 if (LQuals != RQuals) {
7205 // If any of these qualifiers are different, we have a type mismatch.
7206 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7207 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7208 return QualType();
7209
7210 // Exactly one GC qualifier difference is allowed: __strong is
7211 // okay if the other type has no GC qualifier but is an Objective
7212 // C object pointer (i.e. implicitly strong by default). We fix
7213 // this by pretending that the unqualified type was actually
7214 // qualified __strong.
7215 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7216 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7217 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7218
7219 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7220 return QualType();
7221
7222 if (GC_L == Qualifiers::Strong)
7223 return LHS;
7224 if (GC_R == Qualifiers::Strong)
7225 return RHS;
7226 return QualType();
7227 }
7228
7229 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7230 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7231 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7232 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7233 if (ResQT == LHSBaseQT)
7234 return LHS;
7235 if (ResQT == RHSBaseQT)
7236 return RHS;
7237 }
7238 return QualType();
7239}
7240
Chris Lattner4ba0cef2008-04-07 07:01:58 +00007241//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007242// Integer Predicates
7243//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00007244
Jay Foad39c79802011-01-12 09:06:06 +00007245unsigned ASTContext::getIntWidth(QualType T) const {
John McCall424cec92011-01-19 06:33:43 +00007246 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00007247 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00007248 if (T->isBooleanType())
7249 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00007250 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007251 return (unsigned)getTypeSize(T);
7252}
7253
Abramo Bagnara13640492012-09-09 10:21:24 +00007254QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007255 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00007256
7257 // Turn <4 x signed int> -> <4 x unsigned int>
7258 if (const VectorType *VTy = T->getAs<VectorType>())
7259 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00007260 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00007261
7262 // For enums, we return the unsigned version of the base type.
7263 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007264 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00007265
7266 const BuiltinType *BTy = T->getAs<BuiltinType>();
7267 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007268 switch (BTy->getKind()) {
7269 case BuiltinType::Char_S:
7270 case BuiltinType::SChar:
7271 return UnsignedCharTy;
7272 case BuiltinType::Short:
7273 return UnsignedShortTy;
7274 case BuiltinType::Int:
7275 return UnsignedIntTy;
7276 case BuiltinType::Long:
7277 return UnsignedLongTy;
7278 case BuiltinType::LongLong:
7279 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00007280 case BuiltinType::Int128:
7281 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007282 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007283 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007284 }
7285}
7286
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00007287ASTMutationListener::~ASTMutationListener() { }
7288
Chris Lattnerecd79c62009-06-14 00:45:47 +00007289
7290//===----------------------------------------------------------------------===//
7291// Builtin Type Computation
7292//===----------------------------------------------------------------------===//
7293
7294/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00007295/// pointer over the consumed characters. This returns the resultant type. If
7296/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7297/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7298/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007299///
7300/// RequiresICE is filled in on return to indicate whether the value is required
7301/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00007302static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00007303 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007304 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00007305 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00007306 // Modifiers.
7307 int HowLong = 0;
7308 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007309 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00007310
Chris Lattnerdc226c22010-10-01 22:42:38 +00007311 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00007312 bool Done = false;
7313 while (!Done) {
7314 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00007315 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00007316 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007317 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00007318 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007319 case 'S':
7320 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7321 assert(!Signed && "Can't use 'S' modifier multiple times!");
7322 Signed = true;
7323 break;
7324 case 'U':
7325 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7326 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7327 Unsigned = true;
7328 break;
7329 case 'L':
7330 assert(HowLong <= 2 && "Can't have LLLL modifier");
7331 ++HowLong;
7332 break;
7333 }
7334 }
7335
7336 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00007337
Chris Lattnerecd79c62009-06-14 00:45:47 +00007338 // Read the base type.
7339 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00007340 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007341 case 'v':
7342 assert(HowLong == 0 && !Signed && !Unsigned &&
7343 "Bad modifiers used with 'v'!");
7344 Type = Context.VoidTy;
7345 break;
7346 case 'f':
7347 assert(HowLong == 0 && !Signed && !Unsigned &&
7348 "Bad modifiers used with 'f'!");
7349 Type = Context.FloatTy;
7350 break;
7351 case 'd':
7352 assert(HowLong < 2 && !Signed && !Unsigned &&
7353 "Bad modifiers used with 'd'!");
7354 if (HowLong)
7355 Type = Context.LongDoubleTy;
7356 else
7357 Type = Context.DoubleTy;
7358 break;
7359 case 's':
7360 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7361 if (Unsigned)
7362 Type = Context.UnsignedShortTy;
7363 else
7364 Type = Context.ShortTy;
7365 break;
7366 case 'i':
7367 if (HowLong == 3)
7368 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7369 else if (HowLong == 2)
7370 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7371 else if (HowLong == 1)
7372 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7373 else
7374 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7375 break;
7376 case 'c':
7377 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7378 if (Signed)
7379 Type = Context.SignedCharTy;
7380 else if (Unsigned)
7381 Type = Context.UnsignedCharTy;
7382 else
7383 Type = Context.CharTy;
7384 break;
7385 case 'b': // boolean
7386 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7387 Type = Context.BoolTy;
7388 break;
7389 case 'z': // size_t.
7390 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7391 Type = Context.getSizeType();
7392 break;
7393 case 'F':
7394 Type = Context.getCFConstantStringType();
7395 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00007396 case 'G':
7397 Type = Context.getObjCIdType();
7398 break;
7399 case 'H':
7400 Type = Context.getObjCSelType();
7401 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00007402 case 'M':
7403 Type = Context.getObjCSuperType();
7404 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007405 case 'a':
7406 Type = Context.getBuiltinVaListType();
7407 assert(!Type.isNull() && "builtin va list type not initialized!");
7408 break;
7409 case 'A':
7410 // This is a "reference" to a va_list; however, what exactly
7411 // this means depends on how va_list is defined. There are two
7412 // different kinds of va_list: ones passed by value, and ones
7413 // passed by reference. An example of a by-value va_list is
7414 // x86, where va_list is a char*. An example of by-ref va_list
7415 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7416 // we want this argument to be a char*&; for x86-64, we want
7417 // it to be a __va_list_tag*.
7418 Type = Context.getBuiltinVaListType();
7419 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007420 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00007421 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007422 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00007423 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007424 break;
7425 case 'V': {
7426 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007427 unsigned NumElements = strtoul(Str, &End, 10);
7428 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007429 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00007430
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007431 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7432 RequiresICE, false);
7433 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00007434
7435 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00007436 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00007437 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007438 break;
7439 }
Douglas Gregorfed66992012-06-07 18:08:25 +00007440 case 'E': {
7441 char *End;
7442
7443 unsigned NumElements = strtoul(Str, &End, 10);
7444 assert(End != Str && "Missing vector size");
7445
7446 Str = End;
7447
7448 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7449 false);
7450 Type = Context.getExtVectorType(ElementType, NumElements);
7451 break;
7452 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007453 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007454 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7455 false);
7456 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007457 Type = Context.getComplexType(ElementType);
7458 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00007459 }
7460 case 'Y' : {
7461 Type = Context.getPointerDiffType();
7462 break;
7463 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00007464 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00007465 Type = Context.getFILEType();
7466 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007467 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007468 return QualType();
7469 }
Mike Stump2adb4da2009-07-28 23:47:15 +00007470 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00007471 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00007472 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00007473 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00007474 else
7475 Type = Context.getjmp_bufType();
7476
Mike Stump2adb4da2009-07-28 23:47:15 +00007477 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007478 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00007479 return QualType();
7480 }
7481 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00007482 case 'K':
7483 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7484 Type = Context.getucontext_tType();
7485
7486 if (Type.isNull()) {
7487 Error = ASTContext::GE_Missing_ucontext;
7488 return QualType();
7489 }
7490 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00007491 case 'p':
7492 Type = Context.getProcessIDType();
7493 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00007494 }
Mike Stump11289f42009-09-09 15:08:12 +00007495
Chris Lattnerdc226c22010-10-01 22:42:38 +00007496 // If there are modifiers and if we're allowed to parse them, go for it.
7497 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007498 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00007499 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007500 default: Done = true; --Str; break;
7501 case '*':
7502 case '&': {
7503 // Both pointers and references can have their pointee types
7504 // qualified with an address space.
7505 char *End;
7506 unsigned AddrSpace = strtoul(Str, &End, 10);
7507 if (End != Str && AddrSpace != 0) {
7508 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7509 Str = End;
7510 }
7511 if (c == '*')
7512 Type = Context.getPointerType(Type);
7513 else
7514 Type = Context.getLValueReferenceType(Type);
7515 break;
7516 }
7517 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7518 case 'C':
7519 Type = Type.withConst();
7520 break;
7521 case 'D':
7522 Type = Context.getVolatileType(Type);
7523 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00007524 case 'R':
7525 Type = Type.withRestrict();
7526 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007527 }
7528 }
Chris Lattner84733392010-10-01 07:13:18 +00007529
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007530 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00007531 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00007532
Chris Lattnerecd79c62009-06-14 00:45:47 +00007533 return Type;
7534}
7535
7536/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00007537QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007538 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00007539 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007540 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00007541
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007542 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00007543
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007544 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007545 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007546 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7547 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007548 if (Error != GE_None)
7549 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007550
7551 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7552
Chris Lattnerecd79c62009-06-14 00:45:47 +00007553 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007554 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007555 if (Error != GE_None)
7556 return QualType();
7557
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007558 // If this argument is required to be an IntegerConstantExpression and the
7559 // caller cares, fill in the bitmask we return.
7560 if (RequiresICE && IntegerConstantArgs)
7561 *IntegerConstantArgs |= 1 << ArgTypes.size();
7562
Chris Lattnerecd79c62009-06-14 00:45:47 +00007563 // Do array -> pointer decay. The builtin should use the decayed type.
7564 if (Ty->isArrayType())
7565 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00007566
Chris Lattnerecd79c62009-06-14 00:45:47 +00007567 ArgTypes.push_back(Ty);
7568 }
7569
7570 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7571 "'.' should only occur at end of builtin type list!");
7572
John McCall991eb4b2010-12-21 00:44:39 +00007573 FunctionType::ExtInfo EI;
7574 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7575
7576 bool Variadic = (TypeStr[0] == '.');
7577
7578 // We really shouldn't be making a no-proto type here, especially in C++.
7579 if (ArgTypes.empty() && Variadic)
7580 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00007581
John McCalldb40c7f2010-12-14 08:05:40 +00007582 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00007583 EPI.ExtInfo = EI;
7584 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00007585
Jordan Rose5c382722013-03-08 21:51:21 +00007586 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007587}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00007588
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007589GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
7590 GVALinkage External = GVA_StrongExternal;
7591
7592 Linkage L = FD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007593 switch (L) {
7594 case NoLinkage:
7595 case InternalLinkage:
7596 case UniqueExternalLinkage:
7597 return GVA_Internal;
7598
7599 case ExternalLinkage:
7600 switch (FD->getTemplateSpecializationKind()) {
7601 case TSK_Undeclared:
7602 case TSK_ExplicitSpecialization:
7603 External = GVA_StrongExternal;
7604 break;
7605
7606 case TSK_ExplicitInstantiationDefinition:
7607 return GVA_ExplicitTemplateInstantiation;
7608
7609 case TSK_ExplicitInstantiationDeclaration:
7610 case TSK_ImplicitInstantiation:
7611 External = GVA_TemplateInstantiation;
7612 break;
7613 }
7614 }
7615
7616 if (!FD->isInlined())
7617 return External;
7618
David Blaikiebbafb8a2012-03-11 07:00:24 +00007619 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007620 // GNU or C99 inline semantics. Determine whether this symbol should be
7621 // externally visible.
7622 if (FD->isInlineDefinitionExternallyVisible())
7623 return External;
7624
7625 // C99 inline semantics, where the symbol is not externally visible.
7626 return GVA_C99Inline;
7627 }
7628
7629 // C++0x [temp.explicit]p9:
7630 // [ Note: The intent is that an inline function that is the subject of
7631 // an explicit instantiation declaration will still be implicitly
7632 // instantiated when used so that the body can be considered for
7633 // inlining, but that no out-of-line copy of the inline function would be
7634 // generated in the translation unit. -- end note ]
7635 if (FD->getTemplateSpecializationKind()
7636 == TSK_ExplicitInstantiationDeclaration)
7637 return GVA_C99Inline;
7638
7639 return GVA_CXXInline;
7640}
7641
7642GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
7643 // If this is a static data member, compute the kind of template
7644 // specialization. Otherwise, this variable is not part of a
7645 // template.
7646 TemplateSpecializationKind TSK = TSK_Undeclared;
7647 if (VD->isStaticDataMember())
7648 TSK = VD->getTemplateSpecializationKind();
7649
7650 Linkage L = VD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007651
7652 switch (L) {
7653 case NoLinkage:
7654 case InternalLinkage:
7655 case UniqueExternalLinkage:
7656 return GVA_Internal;
7657
7658 case ExternalLinkage:
7659 switch (TSK) {
7660 case TSK_Undeclared:
7661 case TSK_ExplicitSpecialization:
7662 return GVA_StrongExternal;
7663
7664 case TSK_ExplicitInstantiationDeclaration:
7665 llvm_unreachable("Variable should not be instantiated");
7666 // Fall through to treat this like any other instantiation.
7667
7668 case TSK_ExplicitInstantiationDefinition:
7669 return GVA_ExplicitTemplateInstantiation;
7670
7671 case TSK_ImplicitInstantiation:
7672 return GVA_TemplateInstantiation;
7673 }
7674 }
7675
David Blaikie8a40f702012-01-17 06:56:22 +00007676 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007677}
7678
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00007679bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007680 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7681 if (!VD->isFileVarDecl())
7682 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00007683 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7684 // We never need to emit an uninstantiated function template.
7685 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
7686 return false;
7687 } else
7688 return false;
7689
7690 // If this is a member of a class template, we do not need to emit it.
7691 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007692 return false;
7693
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007694 // Weak references don't produce any output by themselves.
7695 if (D->hasAttr<WeakRefAttr>())
7696 return false;
7697
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007698 // Aliases and used decls are required.
7699 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7700 return true;
7701
7702 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7703 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00007704 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00007705 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007706
7707 // Constructors and destructors are required.
7708 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7709 return true;
7710
John McCall6bd2a892013-01-25 22:31:03 +00007711 // The key function for a class is required. This rule only comes
7712 // into play when inline functions can be key functions, though.
7713 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7714 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7715 const CXXRecordDecl *RD = MD->getParent();
7716 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7717 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
7718 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7719 return true;
7720 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007721 }
7722 }
7723
7724 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7725
7726 // static, static inline, always_inline, and extern inline functions can
7727 // always be deferred. Normal inline functions can be deferred in C99/C++.
7728 // Implicit template instantiations can also be deferred in C++.
7729 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev79de4d42012-02-02 06:06:34 +00007730 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007731 return false;
7732 return true;
7733 }
Douglas Gregor87d81242011-09-10 00:22:34 +00007734
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007735 const VarDecl *VD = cast<VarDecl>(D);
7736 assert(VD->isFileVarDecl() && "Expected file scoped var");
7737
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007738 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7739 return false;
7740
Richard Smitha0e5e542012-11-12 21:38:00 +00007741 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007742 GVALinkage L = GetGVALinkageForVariable(VD);
Richard Smitha0e5e542012-11-12 21:38:00 +00007743 if (L != GVA_Internal && L != GVA_TemplateInstantiation)
7744 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007745
Richard Smitha0e5e542012-11-12 21:38:00 +00007746 // Variables that have destruction with side-effects are required.
7747 if (VD->getType().isDestructedType())
7748 return true;
7749
7750 // Variables that have initialization with side-effects are required.
7751 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
7752 return true;
7753
7754 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007755}
Charles Davis53c59df2010-08-16 03:33:14 +00007756
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007757CallingConv ASTContext::getDefaultCXXMethodCallConv(bool isVariadic) {
Charles Davis99202b32010-11-09 18:04:24 +00007758 // Pass through to the C++ ABI object
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007759 return ABI->getDefaultMethodCallConv(isVariadic);
7760}
7761
7762CallingConv ASTContext::getCanonicalCallConv(CallingConv CC) const {
John McCall359b8852013-01-25 22:30:49 +00007763 if (CC == CC_C && !LangOpts.MRTD &&
7764 getTargetInfo().getCXXABI().isMemberFunctionCCDefault())
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007765 return CC_Default;
7766 return CC;
Charles Davis99202b32010-11-09 18:04:24 +00007767}
7768
Jay Foad39c79802011-01-12 09:06:06 +00007769bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00007770 // Pass through to the C++ ABI object
7771 return ABI->isNearlyEmpty(RD);
7772}
7773
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007774MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00007775 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00007776 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00007777 case TargetCXXABI::GenericItanium:
7778 case TargetCXXABI::GenericARM:
7779 case TargetCXXABI::iOS:
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007780 return createItaniumMangleContext(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00007781 case TargetCXXABI::Microsoft:
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007782 return createMicrosoftMangleContext(*this, getDiagnostics());
7783 }
David Blaikie83d382b2011-09-23 05:06:16 +00007784 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007785}
7786
Charles Davis53c59df2010-08-16 03:33:14 +00007787CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007788
7789size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek7d39c9a2011-07-27 18:41:12 +00007790 return ASTRecordLayouts.getMemorySize()
7791 + llvm::capacity_in_bytes(ObjCLayouts)
7792 + llvm::capacity_in_bytes(KeyFunctions)
7793 + llvm::capacity_in_bytes(ObjCImpls)
7794 + llvm::capacity_in_bytes(BlockVarCopyInits)
7795 + llvm::capacity_in_bytes(DeclAttrs)
7796 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
7797 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
7798 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
7799 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
7800 + llvm::capacity_in_bytes(OverriddenMethods)
7801 + llvm::capacity_in_bytes(Types)
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007802 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet57928252011-08-14 14:28:49 +00007803 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007804}
Ted Kremenek540017e2011-10-06 05:00:56 +00007805
David Blaikie095deba2012-11-14 01:52:05 +00007806void ASTContext::addUnnamedTag(const TagDecl *Tag) {
7807 // FIXME: This mangling should be applied to function local classes too
7808 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl() ||
7809 !isa<CXXRecordDecl>(Tag->getParent()) || Tag->getLinkage() != ExternalLinkage)
7810 return;
7811
7812 std::pair<llvm::DenseMap<const DeclContext *, unsigned>::iterator, bool> P =
7813 UnnamedMangleContexts.insert(std::make_pair(Tag->getParent(), 0));
7814 UnnamedMangleNumbers.insert(std::make_pair(Tag, P.first->second++));
7815}
7816
7817int ASTContext::getUnnamedTagManglingNumber(const TagDecl *Tag) const {
7818 llvm::DenseMap<const TagDecl *, unsigned>::const_iterator I =
7819 UnnamedMangleNumbers.find(Tag);
7820 return I != UnnamedMangleNumbers.end() ? I->second : -1;
7821}
7822
Douglas Gregor63798542012-02-20 19:44:39 +00007823unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
7824 CXXRecordDecl *Lambda = CallOperator->getParent();
7825 return LambdaMangleContexts[Lambda->getDeclContext()]
7826 .getManglingNumber(CallOperator);
7827}
7828
7829
Ted Kremenek540017e2011-10-06 05:00:56 +00007830void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
7831 ParamIndices[D] = index;
7832}
7833
7834unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
7835 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
7836 assert(I != ParamIndices.end() &&
7837 "ParmIndices lacks entry set by ParmVarDecl");
7838 return I->second;
7839}