blob: b19150f0485b1d3ca2d2d2c6eb3272900050b91f [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 {
Fariborz Jahanian096f7c12013-05-13 17:27:00 +0000412 if (D->isInvalidDecl())
413 return NULL;
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000414 D = adjustDeclToTemplate(D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000415
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000416 const Decl *Canonical = D->getCanonicalDecl();
417 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
418 ParsedComments.find(Canonical);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000419
420 if (Pos != ParsedComments.end()) {
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000421 if (Canonical != D) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000422 comments::FullComment *FC = Pos->second;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000423 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000424 return CFC;
425 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000426 return Pos->second;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000427 }
428
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000429 const Decl *OriginalDecl;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000430
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000431 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000432 if (!RC) {
433 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000434 SmallVector<const NamedDecl*, 8> Overridden;
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000435 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000436 if (OMD && OMD->isPropertyAccessor())
437 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
438 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
439 return cloneFullComment(FC, D);
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000440 if (OMD)
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000441 addRedeclaredMethods(OMD, Overridden);
442 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000443 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
444 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
445 return cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000446 }
Fariborz Jahanian6384fbb2013-05-02 15:44:16 +0000447 else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000448 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000449 // does not have one of its own.
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000450 QualType QT = TD->getUnderlyingType();
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000451 if (const TagType *TT = QT->getAs<TagType>())
452 if (const Decl *TD = TT->getDecl())
453 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000454 return cloneFullComment(FC, D);
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000455 }
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000456 else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
457 while (IC->getSuperClass()) {
458 IC = IC->getSuperClass();
459 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
460 return cloneFullComment(FC, D);
461 }
462 }
463 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
464 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
465 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
466 return cloneFullComment(FC, D);
467 }
468 else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
469 if (!(RD = RD->getDefinition()))
470 return NULL;
471 // Check non-virtual bases.
472 for (CXXRecordDecl::base_class_const_iterator I =
473 RD->bases_begin(), E = RD->bases_end(); I != E; ++I) {
Fariborz Jahanian5a2e4a22013-04-26 23:34:36 +0000474 if (I->isVirtual() || (I->getAccessSpecifier() != AS_public))
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000475 continue;
476 QualType Ty = I->getType();
477 if (Ty.isNull())
478 continue;
479 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
480 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
481 continue;
482
483 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
484 return cloneFullComment(FC, D);
485 }
486 }
487 // Check virtual bases.
488 for (CXXRecordDecl::base_class_const_iterator I =
489 RD->vbases_begin(), E = RD->vbases_end(); I != E; ++I) {
Fariborz Jahanian5a2e4a22013-04-26 23:34:36 +0000490 if (I->getAccessSpecifier() != AS_public)
491 continue;
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000492 QualType Ty = I->getType();
493 if (Ty.isNull())
494 continue;
495 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
496 if (!(VirtualBase= VirtualBase->getDefinition()))
497 continue;
498 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
499 return cloneFullComment(FC, D);
500 }
501 }
502 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000503 return NULL;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000504 }
505
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000506 // If the RawComment was attached to other redeclaration of this Decl, we
507 // should parse the comment in context of that other Decl. This is important
508 // because comments can contain references to parameter names which can be
509 // different across redeclarations.
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000510 if (D != OriginalDecl)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000511 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000512
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000513 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000514 ParsedComments[Canonical] = FC;
515 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000516}
517
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000518void
519ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
520 TemplateTemplateParmDecl *Parm) {
521 ID.AddInteger(Parm->getDepth());
522 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000523 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000524
525 TemplateParameterList *Params = Parm->getTemplateParameters();
526 ID.AddInteger(Params->size());
527 for (TemplateParameterList::const_iterator P = Params->begin(),
528 PEnd = Params->end();
529 P != PEnd; ++P) {
530 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
531 ID.AddInteger(0);
532 ID.AddBoolean(TTP->isParameterPack());
533 continue;
534 }
535
536 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
537 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000538 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000539 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000540 if (NTTP->isExpandedParameterPack()) {
541 ID.AddBoolean(true);
542 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000543 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
544 QualType T = NTTP->getExpansionType(I);
545 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
546 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000547 } else
548 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000549 continue;
550 }
551
552 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
553 ID.AddInteger(2);
554 Profile(ID, TTP);
555 }
556}
557
558TemplateTemplateParmDecl *
559ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000560 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000561 // Check if we already have a canonical template template parameter.
562 llvm::FoldingSetNodeID ID;
563 CanonicalTemplateTemplateParm::Profile(ID, TTP);
564 void *InsertPos = 0;
565 CanonicalTemplateTemplateParm *Canonical
566 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
567 if (Canonical)
568 return Canonical->getParam();
569
570 // Build a canonical template parameter list.
571 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000572 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000573 CanonParams.reserve(Params->size());
574 for (TemplateParameterList::const_iterator P = Params->begin(),
575 PEnd = Params->end();
576 P != PEnd; ++P) {
577 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
578 CanonParams.push_back(
579 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000580 SourceLocation(),
581 SourceLocation(),
582 TTP->getDepth(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000583 TTP->getIndex(), 0, false,
584 TTP->isParameterPack()));
585 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000586 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
587 QualType T = getCanonicalType(NTTP->getType());
588 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
589 NonTypeTemplateParmDecl *Param;
590 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000591 SmallVector<QualType, 2> ExpandedTypes;
592 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000593 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
594 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
595 ExpandedTInfos.push_back(
596 getTrivialTypeSourceInfo(ExpandedTypes.back()));
597 }
598
599 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000600 SourceLocation(),
601 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000602 NTTP->getDepth(),
603 NTTP->getPosition(), 0,
604 T,
605 TInfo,
606 ExpandedTypes.data(),
607 ExpandedTypes.size(),
608 ExpandedTInfos.data());
609 } else {
610 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000611 SourceLocation(),
612 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000613 NTTP->getDepth(),
614 NTTP->getPosition(), 0,
615 T,
616 NTTP->isParameterPack(),
617 TInfo);
618 }
619 CanonParams.push_back(Param);
620
621 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000622 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
623 cast<TemplateTemplateParmDecl>(*P)));
624 }
625
626 TemplateTemplateParmDecl *CanonTTP
627 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
628 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000629 TTP->getPosition(),
630 TTP->isParameterPack(),
631 0,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000632 TemplateParameterList::Create(*this, SourceLocation(),
633 SourceLocation(),
634 CanonParams.data(),
635 CanonParams.size(),
636 SourceLocation()));
637
638 // Get the new insert position for the node we care about.
639 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
640 assert(Canonical == 0 && "Shouldn't be in the map!");
641 (void)Canonical;
642
643 // Create the canonical template template parameter entry.
644 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
645 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
646 return CanonTTP;
647}
648
Charles Davis53c59df2010-08-16 03:33:14 +0000649CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000650 if (!LangOpts.CPlusPlus) return 0;
651
John McCall359b8852013-01-25 22:30:49 +0000652 switch (T.getCXXABI().getKind()) {
653 case TargetCXXABI::GenericARM:
654 case TargetCXXABI::iOS:
John McCall86353412010-08-21 22:46:04 +0000655 return CreateARMCXXABI(*this);
Tim Northover9bb857a2013-01-31 12:13:10 +0000656 case TargetCXXABI::GenericAArch64: // Same as Itanium at this level
John McCall359b8852013-01-25 22:30:49 +0000657 case TargetCXXABI::GenericItanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000658 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000659 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000660 return CreateMicrosoftCXXABI(*this);
661 }
David Blaikie8a40f702012-01-17 06:56:22 +0000662 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000663}
664
Douglas Gregore8bbc122011-09-02 00:18:52 +0000665static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000666 const LangOptions &LOpts) {
667 if (LOpts.FakeAddressSpaceMap) {
668 // The fake address space map must have a distinct entry for each
669 // language-specific address space.
670 static const unsigned FakeAddrSpaceMap[] = {
671 1, // opencl_global
672 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000673 3, // opencl_constant
674 4, // cuda_device
675 5, // cuda_constant
676 6 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000677 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000678 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000679 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000680 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000681 }
682}
683
Douglas Gregor7018d5b2011-09-01 20:23:19 +0000684ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000685 const TargetInfo *t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000686 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000687 Builtin::Context &builtins,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000688 unsigned size_reserve,
689 bool DelayInitialization)
690 : FunctionProtoTypes(this_()),
691 TemplateSpecializationTypes(this_()),
692 DependentTemplateSpecializationTypes(this_()),
693 SubstTemplateTemplateParmPacks(this_()),
694 GlobalNestedNameSpecifier(0),
695 Int128Decl(0), UInt128Decl(0),
Meador Inge5d3fb222012-06-16 03:34:49 +0000696 BuiltinVaListDecl(0),
Douglas Gregord53ae832012-01-17 18:09:05 +0000697 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Fariborz Jahanianf2578572012-08-30 18:49:41 +0000698 BOOLDecl(0),
Douglas Gregorbab8a962011-09-08 01:46:34 +0000699 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000700 FILEDecl(0),
Rafael Espindola6cfa82b2011-11-13 21:51:09 +0000701 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
702 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
703 cudaConfigureCallDecl(0),
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000704 NullTypeSourceInfo(QualType()),
705 FirstLocalImport(), LastLocalImport(),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000706 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000707 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000708 Idents(idents), Selectors(sels),
709 BuiltinInfo(builtins),
710 DeclarationNames(*this),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000711 ExternalSource(0), Listener(0),
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000712 Comments(SM), CommentsLoaded(false),
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000713 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000714 LastSDM(0, 0),
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +0000715 UniqueBlockByRefTypeID(0)
Douglas Gregore8bbc122011-09-02 00:18:52 +0000716{
Mike Stump11289f42009-09-09 15:08:12 +0000717 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000718 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000719
720 if (!DelayInitialization) {
721 assert(t && "No target supplied for ASTContext initialization");
722 InitBuiltinTypes(*t);
723 }
Daniel Dunbar221fa942008-08-11 04:54:23 +0000724}
725
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000726ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000727 // Release the DenseMaps associated with DeclContext objects.
728 // FIXME: Is this the ideal solution?
729 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000730
Douglas Gregor5b11d492010-07-25 17:53:33 +0000731 // Call all of the deallocation functions.
732 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
733 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor1a809332010-05-23 18:26:36 +0000734
Ted Kremenek076baeb2010-06-08 23:00:58 +0000735 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000736 // because they can contain DenseMaps.
737 for (llvm::DenseMap<const ObjCContainerDecl*,
738 const ASTRecordLayout*>::iterator
739 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
740 // Increment in loop to prevent using deallocated memory.
741 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
742 R->Destroy(*this);
743
Ted Kremenek076baeb2010-06-08 23:00:58 +0000744 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
745 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
746 // Increment in loop to prevent using deallocated memory.
747 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
748 R->Destroy(*this);
749 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000750
751 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
752 AEnd = DeclAttrs.end();
753 A != AEnd; ++A)
754 A->second->~AttrVec();
755}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000756
Douglas Gregor1a809332010-05-23 18:26:36 +0000757void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
758 Deallocations.push_back(std::make_pair(Callback, Data));
759}
760
Mike Stump11289f42009-09-09 15:08:12 +0000761void
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000762ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000763 ExternalSource.reset(Source.take());
764}
765
Chris Lattner4eb445d2007-01-26 01:27:23 +0000766void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000767 llvm::errs() << "\n*** AST Context Stats:\n";
768 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000769
Douglas Gregora30d0462009-05-26 14:40:08 +0000770 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000771#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000772#define ABSTRACT_TYPE(Name, Parent)
773#include "clang/AST/TypeNodes.def"
774 0 // Extra
775 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000776
Chris Lattner4eb445d2007-01-26 01:27:23 +0000777 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
778 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000779 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000780 }
781
Douglas Gregora30d0462009-05-26 14:40:08 +0000782 unsigned Idx = 0;
783 unsigned TotalBytes = 0;
784#define TYPE(Name, Parent) \
785 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000786 llvm::errs() << " " << counts[Idx] << " " << #Name \
787 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000788 TotalBytes += counts[Idx] * sizeof(Name##Type); \
789 ++Idx;
790#define ABSTRACT_TYPE(Name, Parent)
791#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000792
Chandler Carruth3c147a72011-07-04 05:32:14 +0000793 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
794
Douglas Gregor7454c562010-07-02 20:37:36 +0000795 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000796 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
797 << NumImplicitDefaultConstructors
798 << " implicit default constructors created\n";
799 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
800 << NumImplicitCopyConstructors
801 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000802 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000803 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
804 << NumImplicitMoveConstructors
805 << " implicit move constructors created\n";
806 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
807 << NumImplicitCopyAssignmentOperators
808 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000809 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000810 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
811 << NumImplicitMoveAssignmentOperators
812 << " implicit move assignment operators created\n";
813 llvm::errs() << NumImplicitDestructorsDeclared << "/"
814 << NumImplicitDestructors
815 << " implicit destructors created\n";
816
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000817 if (ExternalSource.get()) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000818 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000819 ExternalSource->PrintStats();
820 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000821
Douglas Gregor5b11d492010-07-25 17:53:33 +0000822 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000823}
824
Douglas Gregor801c99d2011-08-12 06:49:56 +0000825TypedefDecl *ASTContext::getInt128Decl() const {
826 if (!Int128Decl) {
827 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
828 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
829 getTranslationUnitDecl(),
830 SourceLocation(),
831 SourceLocation(),
832 &Idents.get("__int128_t"),
833 TInfo);
834 }
835
836 return Int128Decl;
837}
838
839TypedefDecl *ASTContext::getUInt128Decl() const {
840 if (!UInt128Decl) {
841 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
842 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
843 getTranslationUnitDecl(),
844 SourceLocation(),
845 SourceLocation(),
846 &Idents.get("__uint128_t"),
847 TInfo);
848 }
849
850 return UInt128Decl;
851}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000852
John McCall48f2d582009-10-23 23:03:21 +0000853void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000854 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000855 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000856 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000857}
858
Douglas Gregore8bbc122011-09-02 00:18:52 +0000859void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
860 assert((!this->Target || this->Target == &Target) &&
861 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000862 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000863
Douglas Gregore8bbc122011-09-02 00:18:52 +0000864 this->Target = &Target;
865
866 ABI.reset(createCXXABI(Target));
867 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
868
Chris Lattner970e54e2006-11-12 00:37:36 +0000869 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000870 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000871
Chris Lattner970e54e2006-11-12 00:37:36 +0000872 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000873 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000874 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000875 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000876 InitBuiltinType(CharTy, BuiltinType::Char_S);
877 else
878 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000879 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000880 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
881 InitBuiltinType(ShortTy, BuiltinType::Short);
882 InitBuiltinType(IntTy, BuiltinType::Int);
883 InitBuiltinType(LongTy, BuiltinType::Long);
884 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000885
Chris Lattner970e54e2006-11-12 00:37:36 +0000886 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000887 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
888 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
889 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
890 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
891 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000892
Chris Lattner970e54e2006-11-12 00:37:36 +0000893 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000894 InitBuiltinType(FloatTy, BuiltinType::Float);
895 InitBuiltinType(DoubleTy, BuiltinType::Double);
896 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000897
Chris Lattnerf122cef2009-04-30 02:43:43 +0000898 // GNU extension, 128-bit integers.
899 InitBuiltinType(Int128Ty, BuiltinType::Int128);
900 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
901
Hans Wennborg0d81e012013-05-10 10:08:40 +0000902 // C++ 3.9.1p5
903 if (TargetInfo::isTypeSigned(Target.getWCharType()))
904 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
905 else // -fshort-wchar makes wchar_t be unsigned.
906 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
907 if (LangOpts.CPlusPlus && LangOpts.WChar)
908 WideCharTy = WCharTy;
909 else {
910 // C99 (or C++ using -fno-wchar).
911 WideCharTy = getFromTargetType(Target.getWCharType());
912 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000913
James Molloy36365542012-05-04 10:55:22 +0000914 WIntTy = getFromTargetType(Target.getWIntType());
915
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000916 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
917 InitBuiltinType(Char16Ty, BuiltinType::Char16);
918 else // C99
919 Char16Ty = getFromTargetType(Target.getChar16Type());
920
921 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
922 InitBuiltinType(Char32Ty, BuiltinType::Char32);
923 else // C99
924 Char32Ty = getFromTargetType(Target.getChar32Type());
925
Douglas Gregor4619e432008-12-05 23:32:09 +0000926 // Placeholder type for type-dependent expressions whose type is
927 // completely unknown. No code should ever check a type against
928 // DependentTy and users should never see it; however, it is here to
929 // help diagnose failures to properly check for type-dependent
930 // expressions.
931 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000932
John McCall36e7fe32010-10-12 00:20:44 +0000933 // Placeholder type for functions.
934 InitBuiltinType(OverloadTy, BuiltinType::Overload);
935
John McCall0009fcc2011-04-26 20:42:42 +0000936 // Placeholder type for bound members.
937 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
938
John McCall526ab472011-10-25 17:37:35 +0000939 // Placeholder type for pseudo-objects.
940 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
941
John McCall31996342011-04-07 08:22:57 +0000942 // "any" type; useful for debugger-like clients.
943 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
944
John McCall8a6b59a2011-10-17 18:09:15 +0000945 // Placeholder type for unbridged ARC casts.
946 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
947
Eli Friedman34866c72012-08-31 00:14:07 +0000948 // Placeholder type for builtin functions.
949 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
950
Chris Lattner970e54e2006-11-12 00:37:36 +0000951 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000952 FloatComplexTy = getComplexType(FloatTy);
953 DoubleComplexTy = getComplexType(DoubleTy);
954 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000955
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000956 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000957 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
958 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000959 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000960
961 if (LangOpts.OpenCL) {
962 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
963 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
964 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
965 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
966 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
967 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +0000968
Guy Benyei61054192013-02-07 10:55:47 +0000969 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +0000970 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000971 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000972
973 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +0000974 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
975 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000976
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000977 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +0000978
979 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000980
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000981 // void * type
982 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000983
984 // nullptr type (C++0x 2.14.7)
985 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000986
987 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
988 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +0000989
990 // Builtin type used to help define __builtin_va_list.
991 VaListTagTy = QualType();
Chris Lattner970e54e2006-11-12 00:37:36 +0000992}
993
David Blaikie9c902b52011-09-25 23:23:43 +0000994DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000995 return SourceMgr.getDiagnostics();
996}
997
Douglas Gregor561eceb2010-08-30 16:49:28 +0000998AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
999 AttrVec *&Result = DeclAttrs[D];
1000 if (!Result) {
1001 void *Mem = Allocate(sizeof(AttrVec));
1002 Result = new (Mem) AttrVec;
1003 }
1004
1005 return *Result;
1006}
1007
1008/// \brief Erase the attributes corresponding to the given declaration.
1009void ASTContext::eraseDeclAttrs(const Decl *D) {
1010 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1011 if (Pos != DeclAttrs.end()) {
1012 Pos->second->~AttrVec();
1013 DeclAttrs.erase(Pos);
1014 }
1015}
1016
Douglas Gregor86d142a2009-10-08 07:24:58 +00001017MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001018ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001019 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +00001020 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001021 = InstantiatedFromStaticDataMember.find(Var);
1022 if (Pos == InstantiatedFromStaticDataMember.end())
1023 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001024
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001025 return Pos->second;
1026}
1027
Mike Stump11289f42009-09-09 15:08:12 +00001028void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001029ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001030 TemplateSpecializationKind TSK,
1031 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001032 assert(Inst->isStaticDataMember() && "Not a static data member");
1033 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1034 assert(!InstantiatedFromStaticDataMember[Inst] &&
1035 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +00001036 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001037 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001038}
1039
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001040FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1041 const FunctionDecl *FD){
1042 assert(FD && "Specialization is 0");
1043 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001044 = ClassScopeSpecializationPattern.find(FD);
1045 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001046 return 0;
1047
1048 return Pos->second;
1049}
1050
1051void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1052 FunctionDecl *Pattern) {
1053 assert(FD && "Specialization is 0");
1054 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001055 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001056}
1057
John McCalle61f2ba2009-11-18 02:36:19 +00001058NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +00001059ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +00001060 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +00001061 = InstantiatedFromUsingDecl.find(UUD);
1062 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001063 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001064
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001065 return Pos->second;
1066}
1067
1068void
John McCallb96ec562009-12-04 22:46:56 +00001069ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1070 assert((isa<UsingDecl>(Pattern) ||
1071 isa<UnresolvedUsingValueDecl>(Pattern) ||
1072 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1073 "pattern decl is not a using decl");
1074 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1075 InstantiatedFromUsingDecl[Inst] = Pattern;
1076}
1077
1078UsingShadowDecl *
1079ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1080 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1081 = InstantiatedFromUsingShadowDecl.find(Inst);
1082 if (Pos == InstantiatedFromUsingShadowDecl.end())
1083 return 0;
1084
1085 return Pos->second;
1086}
1087
1088void
1089ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1090 UsingShadowDecl *Pattern) {
1091 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1092 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001093}
1094
Anders Carlsson5da84842009-09-01 04:26:58 +00001095FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1096 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1097 = InstantiatedFromUnnamedFieldDecl.find(Field);
1098 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1099 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001100
Anders Carlsson5da84842009-09-01 04:26:58 +00001101 return Pos->second;
1102}
1103
1104void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1105 FieldDecl *Tmpl) {
1106 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1107 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1108 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1109 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001110
Anders Carlsson5da84842009-09-01 04:26:58 +00001111 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1112}
1113
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +00001114bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
1115 const FieldDecl *LastFD) const {
1116 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001117 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +00001118}
1119
Fariborz Jahanianeb397412011-05-02 17:20:56 +00001120bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
1121 const FieldDecl *LastFD) const {
1122 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001123 FD->getBitWidthValue(*this) == 0 &&
1124 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanianeb397412011-05-02 17:20:56 +00001125}
1126
Fariborz Jahanian84335f72011-05-04 18:51:37 +00001127bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
1128 const FieldDecl *LastFD) const {
1129 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001130 FD->getBitWidthValue(*this) &&
1131 LastFD->getBitWidthValue(*this));
Fariborz Jahanian84335f72011-05-04 18:51:37 +00001132}
1133
Chad Rosierf01a7dd2011-08-04 23:34:15 +00001134bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +00001135 const FieldDecl *LastFD) const {
1136 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001137 LastFD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +00001138}
1139
Chad Rosierf01a7dd2011-08-04 23:34:15 +00001140bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +00001141 const FieldDecl *LastFD) const {
1142 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001143 FD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +00001144}
1145
Douglas Gregor832940b2010-03-02 23:58:15 +00001146ASTContext::overridden_cxx_method_iterator
1147ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1148 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001149 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001150 if (Pos == OverriddenMethods.end())
1151 return 0;
1152
1153 return Pos->second.begin();
1154}
1155
1156ASTContext::overridden_cxx_method_iterator
1157ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1158 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001159 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001160 if (Pos == OverriddenMethods.end())
1161 return 0;
1162
1163 return Pos->second.end();
1164}
1165
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001166unsigned
1167ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1168 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001169 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001170 if (Pos == OverriddenMethods.end())
1171 return 0;
1172
1173 return Pos->second.size();
1174}
1175
Douglas Gregor832940b2010-03-02 23:58:15 +00001176void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1177 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001178 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001179 OverriddenMethods[Method].push_back(Overridden);
1180}
1181
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001182void ASTContext::getOverriddenMethods(
1183 const NamedDecl *D,
1184 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001185 assert(D);
1186
1187 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001188 Overridden.append(overridden_methods_begin(CXXMethod),
1189 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001190 return;
1191 }
1192
1193 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1194 if (!Method)
1195 return;
1196
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001197 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1198 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001199 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001200}
1201
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001202void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1203 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1204 assert(!Import->isFromASTFile() && "Non-local import declaration");
1205 if (!FirstLocalImport) {
1206 FirstLocalImport = Import;
1207 LastLocalImport = Import;
1208 return;
1209 }
1210
1211 LastLocalImport->NextLocalImport = Import;
1212 LastLocalImport = Import;
1213}
1214
Chris Lattner53cfe802007-07-18 17:52:12 +00001215//===----------------------------------------------------------------------===//
1216// Type Sizing and Analysis
1217//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001218
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001219/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1220/// scalar floating point type.
1221const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001222 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001223 assert(BT && "Not a floating point type!");
1224 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001225 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001226 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001227 case BuiltinType::Float: return Target->getFloatFormat();
1228 case BuiltinType::Double: return Target->getDoubleFormat();
1229 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001230 }
1231}
1232
Ken Dyck160146e2010-01-27 17:10:57 +00001233/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +00001234/// specified decl. Note that bitfields do not have a valid alignment, so
1235/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001236/// If @p RefAsPointee, references are treated like their underlying type
1237/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad39c79802011-01-12 09:06:06 +00001238CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001239 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001240
John McCall94268702010-10-08 18:24:19 +00001241 bool UseAlignAttrOnly = false;
1242 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1243 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001244
John McCall94268702010-10-08 18:24:19 +00001245 // __attribute__((aligned)) can increase or decrease alignment
1246 // *except* on a struct or struct member, where it only increases
1247 // alignment unless 'packed' is also specified.
1248 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001249 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001250 // ignore that possibility; Sema should diagnose it.
1251 if (isa<FieldDecl>(D)) {
1252 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1253 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1254 } else {
1255 UseAlignAttrOnly = true;
1256 }
1257 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001258 else if (isa<FieldDecl>(D))
1259 UseAlignAttrOnly =
1260 D->hasAttr<PackedAttr>() ||
1261 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001262
John McCall4e819612011-01-20 07:57:12 +00001263 // If we're using the align attribute only, just ignore everything
1264 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001265 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001266 // do nothing
1267
John McCall94268702010-10-08 18:24:19 +00001268 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001269 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001270 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001271 if (RefAsPointee)
1272 T = RT->getPointeeType();
1273 else
1274 T = getPointerType(RT->getPointeeType());
1275 }
1276 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +00001277 // Adjust alignments of declarations with array type by the
1278 // large-array alignment on the target.
Douglas Gregore8bbc122011-09-02 00:18:52 +00001279 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall33ddac02011-01-19 10:06:00 +00001280 const ArrayType *arrayType;
1281 if (MinWidth && (arrayType = getAsArrayType(T))) {
1282 if (isa<VariableArrayType>(arrayType))
Douglas Gregore8bbc122011-09-02 00:18:52 +00001283 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall33ddac02011-01-19 10:06:00 +00001284 else if (isa<ConstantArrayType>(arrayType) &&
1285 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregore8bbc122011-09-02 00:18:52 +00001286 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedman19a546c2009-02-22 02:56:25 +00001287
John McCall33ddac02011-01-19 10:06:00 +00001288 // Walk through any array types while we're at it.
1289 T = getBaseElementType(arrayType);
1290 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001291 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Ulrich Weigandfa806422013-05-06 16:23:57 +00001292 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1293 if (VD->hasGlobalStorage())
1294 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1295 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001296 }
John McCall4e819612011-01-20 07:57:12 +00001297
1298 // Fields can be subject to extra alignment constraints, like if
1299 // the field is packed, the struct is packed, or the struct has a
1300 // a max-field-alignment constraint (#pragma pack). So calculate
1301 // the actual alignment of the field within the struct, and then
1302 // (as we're expected to) constrain that by the alignment of the type.
1303 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
1304 // So calculate the alignment of the field.
1305 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
1306
1307 // Start with the record's overall alignment.
Ken Dyck7ad11e72011-02-15 02:32:40 +00001308 unsigned fieldAlign = toBits(layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001309
1310 // Use the GCD of that and the offset within the record.
1311 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
1312 if (offset > 0) {
1313 // Alignment is always a power of 2, so the GCD will be a power of 2,
1314 // which means we get to do this crazy thing instead of Euclid's.
1315 uint64_t lowBitOfOffset = offset & (~offset + 1);
1316 if (lowBitOfOffset < fieldAlign)
1317 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
1318 }
1319
1320 Align = std::min(Align, fieldAlign);
Charles Davis3fc51072010-02-23 04:52:00 +00001321 }
Chris Lattner68061312009-01-24 21:53:27 +00001322 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001323
Ken Dyckcc56c542011-01-15 18:38:59 +00001324 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001325}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001326
John McCallf1249922012-08-21 04:10:00 +00001327// getTypeInfoDataSizeInChars - Return the size of a type, in
1328// chars. If the type is a record, its data size is returned. This is
1329// the size of the memcpy that's performed when assigning this type
1330// using a trivial copy/move assignment operator.
1331std::pair<CharUnits, CharUnits>
1332ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1333 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1334
1335 // In C++, objects can sometimes be allocated into the tail padding
1336 // of a base-class subobject. We decide whether that's possible
1337 // during class layout, so here we can just trust the layout results.
1338 if (getLangOpts().CPlusPlus) {
1339 if (const RecordType *RT = T->getAs<RecordType>()) {
1340 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1341 sizeAndAlign.first = layout.getDataSize();
1342 }
1343 }
1344
1345 return sizeAndAlign;
1346}
1347
Richard Trieu04d2d942013-05-14 21:59:17 +00001348/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1349/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1350std::pair<CharUnits, CharUnits>
1351static getConstantArrayInfoInChars(const ASTContext &Context,
1352 const ConstantArrayType *CAT) {
1353 std::pair<CharUnits, CharUnits> EltInfo =
1354 Context.getTypeInfoInChars(CAT->getElementType());
1355 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001356 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1357 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001358 "Overflow in array type char size evaluation");
1359 uint64_t Width = EltInfo.first.getQuantity() * Size;
1360 unsigned Align = EltInfo.second.getQuantity();
1361 Width = llvm::RoundUpToAlignment(Width, Align);
1362 return std::make_pair(CharUnits::fromQuantity(Width),
1363 CharUnits::fromQuantity(Align));
1364}
1365
John McCall87fe5d52010-05-20 01:18:31 +00001366std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001367ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001368 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1369 return getConstantArrayInfoInChars(*this, CAT);
John McCall87fe5d52010-05-20 01:18:31 +00001370 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +00001371 return std::make_pair(toCharUnitsFromBits(Info.first),
1372 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +00001373}
1374
1375std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001376ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001377 return getTypeInfoInChars(T.getTypePtr());
1378}
1379
Daniel Dunbarc6475872012-03-09 04:12:54 +00001380std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1381 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1382 if (it != MemoizedTypeInfo.end())
1383 return it->second;
1384
1385 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1386 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1387 return Info;
1388}
1389
1390/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1391/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001392///
1393/// FIXME: Pointers into different addr spaces could have different sizes and
1394/// alignment requirements: getPointerInfo should take an AddrSpace, this
1395/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +00001396std::pair<uint64_t, unsigned>
Daniel Dunbarc6475872012-03-09 04:12:54 +00001397ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +00001398 uint64_t Width=0;
1399 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001400 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001401#define TYPE(Class, Base)
1402#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001403#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001404#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1405#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001406 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001407
Chris Lattner355332d2007-07-13 22:27:08 +00001408 case Type::FunctionNoProto:
1409 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001410 // GCC extension: alignof(function) = 32 bits
1411 Width = 0;
1412 Align = 32;
1413 break;
1414
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001415 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001416 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001417 Width = 0;
1418 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1419 break;
1420
Steve Naroff5c131802007-08-30 01:06:46 +00001421 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001422 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001423
Chris Lattner37e05872008-03-05 18:54:05 +00001424 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001425 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarc6475872012-03-09 04:12:54 +00001426 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1427 "Overflow in array type bit size evaluation");
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001428 Width = EltInfo.first*Size;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001429 Align = EltInfo.second;
Argyrios Kyrtzidisae40e4e2011-04-26 21:05:39 +00001430 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001431 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001432 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001433 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001434 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001435 const VectorType *VT = cast<VectorType>(T);
1436 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1437 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001438 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001439 // If the alignment is not a power of 2, round up to the next power of 2.
1440 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001441 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001442 Align = llvm::NextPowerOf2(Align);
1443 Width = llvm::RoundUpToAlignment(Width, Align);
1444 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001445 // Adjust the alignment based on the target max.
1446 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1447 if (TargetVectorAlign && TargetVectorAlign < Align)
1448 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001449 break;
1450 }
Chris Lattner647fb222007-07-18 18:26:58 +00001451
Chris Lattner7570e9c2008-03-08 08:52:55 +00001452 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001453 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001454 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001455 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001456 // GCC extension: alignof(void) = 8 bits.
1457 Width = 0;
1458 Align = 8;
1459 break;
1460
Chris Lattner6a4f7452007-12-19 19:23:28 +00001461 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001462 Width = Target->getBoolWidth();
1463 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001464 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001465 case BuiltinType::Char_S:
1466 case BuiltinType::Char_U:
1467 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001468 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001469 Width = Target->getCharWidth();
1470 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001471 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001472 case BuiltinType::WChar_S:
1473 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001474 Width = Target->getWCharWidth();
1475 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001476 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001477 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001478 Width = Target->getChar16Width();
1479 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001480 break;
1481 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001482 Width = Target->getChar32Width();
1483 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001484 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001485 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001486 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001487 Width = Target->getShortWidth();
1488 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001489 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001490 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001491 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001492 Width = Target->getIntWidth();
1493 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001494 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001495 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001496 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001497 Width = Target->getLongWidth();
1498 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001499 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001500 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001501 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001502 Width = Target->getLongLongWidth();
1503 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001504 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001505 case BuiltinType::Int128:
1506 case BuiltinType::UInt128:
1507 Width = 128;
1508 Align = 128; // int128_t is 128-bit aligned on all targets.
1509 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001510 case BuiltinType::Half:
1511 Width = Target->getHalfWidth();
1512 Align = Target->getHalfAlign();
1513 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001514 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001515 Width = Target->getFloatWidth();
1516 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001517 break;
1518 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001519 Width = Target->getDoubleWidth();
1520 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001521 break;
1522 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001523 Width = Target->getLongDoubleWidth();
1524 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001525 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001526 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001527 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1528 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001529 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001530 case BuiltinType::ObjCId:
1531 case BuiltinType::ObjCClass:
1532 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001533 Width = Target->getPointerWidth(0);
1534 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001535 break;
Guy Benyei61054192013-02-07 10:55:47 +00001536 case BuiltinType::OCLSampler:
1537 // Samplers are modeled as integers.
1538 Width = Target->getIntWidth();
1539 Align = Target->getIntAlign();
1540 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001541 case BuiltinType::OCLEvent:
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001542 case BuiltinType::OCLImage1d:
1543 case BuiltinType::OCLImage1dArray:
1544 case BuiltinType::OCLImage1dBuffer:
1545 case BuiltinType::OCLImage2d:
1546 case BuiltinType::OCLImage2dArray:
1547 case BuiltinType::OCLImage3d:
1548 // Currently these types are pointers to opaque types.
1549 Width = Target->getPointerWidth(0);
1550 Align = Target->getPointerAlign(0);
1551 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001552 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001553 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001554 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001555 Width = Target->getPointerWidth(0);
1556 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001557 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001558 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001559 unsigned AS = getTargetAddressSpace(
1560 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001561 Width = Target->getPointerWidth(AS);
1562 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001563 break;
1564 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001565 case Type::LValueReference:
1566 case Type::RValueReference: {
1567 // alignof and sizeof should never enter this code path here, so we go
1568 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001569 unsigned AS = getTargetAddressSpace(
1570 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001571 Width = Target->getPointerWidth(AS);
1572 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001573 break;
1574 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001575 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001576 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001577 Width = Target->getPointerWidth(AS);
1578 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001579 break;
1580 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001581 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001582 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Reid Kleckner3a52abf2013-03-28 20:02:56 +00001583 llvm::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001584 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001585 }
Chris Lattner647fb222007-07-18 18:26:58 +00001586 case Type::Complex: {
1587 // Complex types have the same alignment as their elements, but twice the
1588 // size.
Mike Stump11289f42009-09-09 15:08:12 +00001589 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +00001590 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +00001591 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +00001592 Align = EltInfo.second;
1593 break;
1594 }
John McCall8b07ec22010-05-15 11:32:37 +00001595 case Type::ObjCObject:
1596 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001597 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001598 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001599 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001600 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001601 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001602 break;
1603 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001604 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001605 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001606 const TagType *TT = cast<TagType>(T);
1607
1608 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001609 Width = 8;
1610 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001611 break;
1612 }
Mike Stump11289f42009-09-09 15:08:12 +00001613
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001614 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +00001615 return getTypeInfo(ET->getDecl()->getIntegerType());
1616
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001617 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +00001618 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001619 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001620 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +00001621 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001622 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001623
Chris Lattner63d2b362009-10-22 05:17:15 +00001624 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001625 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1626 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001627
Richard Smith30482bc2011-02-20 03:19:35 +00001628 case Type::Auto: {
1629 const AutoType *A = cast<AutoType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00001630 assert(!A->getDeducedType().isNull() &&
1631 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001632 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001633 }
1634
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001635 case Type::Paren:
1636 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1637
Douglas Gregoref462e62009-04-30 17:32:17 +00001638 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001639 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +00001640 std::pair<uint64_t, unsigned> Info
1641 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001642 // If the typedef has an aligned attribute on it, it overrides any computed
1643 // alignment we have. This violates the GCC documentation (which says that
1644 // attribute(aligned) can only round up) but matches its implementation.
1645 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1646 Align = AttrAlign;
1647 else
1648 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +00001649 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +00001650 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001651 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001652
1653 case Type::TypeOfExpr:
1654 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1655 .getTypePtr());
1656
1657 case Type::TypeOf:
1658 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1659
Anders Carlsson81df7b82009-06-24 19:06:50 +00001660 case Type::Decltype:
1661 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1662 .getTypePtr());
1663
Alexis Hunte852b102011-05-24 22:41:36 +00001664 case Type::UnaryTransform:
1665 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1666
Abramo Bagnara6150c882010-05-11 21:36:43 +00001667 case Type::Elaborated:
1668 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001669
John McCall81904512011-01-06 01:58:22 +00001670 case Type::Attributed:
1671 return getTypeInfo(
1672 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1673
Richard Smith3f1b5d02011-05-05 21:57:07 +00001674 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00001675 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +00001676 "Cannot request the size of a dependent type");
Richard Smith3f1b5d02011-05-05 21:57:07 +00001677 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1678 // A type alias template specialization may refer to a typedef with the
1679 // aligned attribute on it.
1680 if (TST->isTypeAlias())
1681 return getTypeInfo(TST->getAliasedType().getTypePtr());
1682 else
1683 return getTypeInfo(getCanonicalType(T));
1684 }
1685
Eli Friedman0dfb8892011-10-06 23:00:33 +00001686 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00001687 // Start with the base type information.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001688 std::pair<uint64_t, unsigned> Info
1689 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1690 Width = Info.first;
1691 Align = Info.second;
John McCalla8ec7eb2013-03-07 21:37:17 +00001692
1693 // If the size of the type doesn't exceed the platform's max
1694 // atomic promotion width, make the size and alignment more
1695 // favorable to atomic operations:
1696 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1697 // Round the size up to a power of 2.
1698 if (!llvm::isPowerOf2_64(Width))
1699 Width = llvm::NextPowerOf2(Width);
1700
1701 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001702 Align = static_cast<unsigned>(Width);
1703 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001704 }
1705
Douglas Gregoref462e62009-04-30 17:32:17 +00001706 }
Mike Stump11289f42009-09-09 15:08:12 +00001707
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001708 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +00001709 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001710}
1711
Ken Dyckcc56c542011-01-15 18:38:59 +00001712/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1713CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1714 return CharUnits::fromQuantity(BitSize / getCharWidth());
1715}
1716
Ken Dyckb0fcc592011-02-11 01:54:29 +00001717/// toBits - Convert a size in characters to a size in characters.
1718int64_t ASTContext::toBits(CharUnits CharSize) const {
1719 return CharSize.getQuantity() * getCharWidth();
1720}
1721
Ken Dyck8c89d592009-12-22 14:23:30 +00001722/// getTypeSizeInChars - Return the size of the specified type, in characters.
1723/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001724CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001725 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001726}
Jay Foad39c79802011-01-12 09:06:06 +00001727CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001728 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001729}
1730
Ken Dycka6046ab2010-01-26 17:25:18 +00001731/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001732/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001733CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001734 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001735}
Jay Foad39c79802011-01-12 09:06:06 +00001736CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001737 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001738}
1739
Chris Lattnera3402cd2009-01-27 18:08:34 +00001740/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1741/// type for the current target in bits. This can be different than the ABI
1742/// alignment in cases where it is beneficial for performance to overalign
1743/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001744unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +00001745 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +00001746
1747 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +00001748 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001749 T = CT->getElementType().getTypePtr();
1750 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001751 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1752 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman7ab09572009-05-25 21:27:19 +00001753 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1754
Chris Lattnera3402cd2009-01-27 18:08:34 +00001755 return ABIAlign;
1756}
1757
Ulrich Weigandfa806422013-05-06 16:23:57 +00001758/// getAlignOfGlobalVar - Return the alignment in bits that should be given
1759/// to a global variable of the specified type.
1760unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1761 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1762}
1763
1764/// getAlignOfGlobalVarInChars - Return the alignment in characters that
1765/// should be given to a global variable of the specified type.
1766CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1767 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1768}
1769
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001770/// DeepCollectObjCIvars -
1771/// This routine first collects all declared, but not synthesized, ivars in
1772/// super class and then collects all ivars, including those synthesized for
1773/// current class. This routine is used for implementation of current class
1774/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001775///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001776void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1777 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001778 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001779 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1780 DeepCollectObjCIvars(SuperClass, false, Ivars);
1781 if (!leafClass) {
1782 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1783 E = OI->ivar_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001784 Ivars.push_back(*I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001785 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001786 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001787 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001788 Iv= Iv->getNextIvar())
1789 Ivars.push_back(Iv);
1790 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001791}
1792
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001793/// CollectInheritedProtocols - Collect all protocols in current class and
1794/// those inherited by it.
1795void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001796 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001797 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001798 // We can use protocol_iterator here instead of
1799 // all_referenced_protocol_iterator since we are walking all categories.
1800 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1801 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001802 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001803 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001804 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001805 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001806 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001807 CollectInheritedProtocols(*P, Protocols);
1808 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001809 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001810
1811 // Categories of this Interface.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001812 for (ObjCInterfaceDecl::visible_categories_iterator
1813 Cat = OI->visible_categories_begin(),
1814 CatEnd = OI->visible_categories_end();
1815 Cat != CatEnd; ++Cat) {
1816 CollectInheritedProtocols(*Cat, Protocols);
1817 }
1818
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001819 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1820 while (SD) {
1821 CollectInheritedProtocols(SD, Protocols);
1822 SD = SD->getSuperClass();
1823 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001824 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001825 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001826 PE = OC->protocol_end(); P != PE; ++P) {
1827 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001828 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001829 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1830 PE = Proto->protocol_end(); P != PE; ++P)
1831 CollectInheritedProtocols(*P, Protocols);
1832 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001833 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001834 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1835 PE = OP->protocol_end(); P != PE; ++P) {
1836 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001837 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001838 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1839 PE = Proto->protocol_end(); P != PE; ++P)
1840 CollectInheritedProtocols(*P, Protocols);
1841 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001842 }
1843}
1844
Jay Foad39c79802011-01-12 09:06:06 +00001845unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001846 unsigned count = 0;
1847 // Count ivars declared in class extension.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001848 for (ObjCInterfaceDecl::known_extensions_iterator
1849 Ext = OI->known_extensions_begin(),
1850 ExtEnd = OI->known_extensions_end();
1851 Ext != ExtEnd; ++Ext) {
1852 count += Ext->ivar_size();
1853 }
1854
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001855 // Count ivar defined in this class's implementation. This
1856 // includes synthesized ivars.
1857 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001858 count += ImplDecl->ivar_size();
1859
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001860 return count;
1861}
1862
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001863bool ASTContext::isSentinelNullExpr(const Expr *E) {
1864 if (!E)
1865 return false;
1866
1867 // nullptr_t is always treated as null.
1868 if (E->getType()->isNullPtrType()) return true;
1869
1870 if (E->getType()->isAnyPointerType() &&
1871 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1872 Expr::NPC_ValueDependentIsNull))
1873 return true;
1874
1875 // Unfortunately, __null has type 'int'.
1876 if (isa<GNUNullExpr>(E)) return true;
1877
1878 return false;
1879}
1880
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001881/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1882ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1883 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1884 I = ObjCImpls.find(D);
1885 if (I != ObjCImpls.end())
1886 return cast<ObjCImplementationDecl>(I->second);
1887 return 0;
1888}
1889/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1890ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1891 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1892 I = ObjCImpls.find(D);
1893 if (I != ObjCImpls.end())
1894 return cast<ObjCCategoryImplDecl>(I->second);
1895 return 0;
1896}
1897
1898/// \brief Set the implementation of ObjCInterfaceDecl.
1899void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1900 ObjCImplementationDecl *ImplD) {
1901 assert(IFaceD && ImplD && "Passed null params");
1902 ObjCImpls[IFaceD] = ImplD;
1903}
1904/// \brief Set the implementation of ObjCCategoryDecl.
1905void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1906 ObjCCategoryImplDecl *ImplD) {
1907 assert(CatD && ImplD && "Passed null params");
1908 ObjCImpls[CatD] = ImplD;
1909}
1910
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001911const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
1912 const NamedDecl *ND) const {
1913 if (const ObjCInterfaceDecl *ID =
1914 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001915 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001916 if (const ObjCCategoryDecl *CD =
1917 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001918 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001919 if (const ObjCImplDecl *IMD =
1920 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001921 return IMD->getClassInterface();
1922
1923 return 0;
1924}
1925
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001926/// \brief Get the copy initialization expression of VarDecl,or NULL if
1927/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001928Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001929 assert(VD && "Passed null params");
1930 assert(VD->hasAttr<BlocksAttr>() &&
1931 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001932 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001933 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001934 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1935}
1936
1937/// \brief Set the copy inialization expression of a block var decl.
1938void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1939 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001940 assert(VD->hasAttr<BlocksAttr>() &&
1941 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001942 BlockVarCopyInits[VD] = Init;
1943}
1944
John McCallbcd03502009-12-07 02:54:59 +00001945TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001946 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001947 if (!DataSize)
1948 DataSize = TypeLoc::getFullDataSizeForType(T);
1949 else
1950 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001951 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001952
John McCallbcd03502009-12-07 02:54:59 +00001953 TypeSourceInfo *TInfo =
1954 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1955 new (TInfo) TypeSourceInfo(T);
1956 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001957}
1958
John McCallbcd03502009-12-07 02:54:59 +00001959TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001960 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001961 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001962 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001963 return DI;
1964}
1965
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001966const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001967ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001968 return getObjCLayout(D, 0);
1969}
1970
1971const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001972ASTContext::getASTObjCImplementationLayout(
1973 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001974 return getObjCLayout(D->getClassInterface(), D);
1975}
1976
Chris Lattner983a8bb2007-07-13 22:13:22 +00001977//===----------------------------------------------------------------------===//
1978// Type creation/memoization methods
1979//===----------------------------------------------------------------------===//
1980
Jay Foad39c79802011-01-12 09:06:06 +00001981QualType
John McCall33ddac02011-01-19 10:06:00 +00001982ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1983 unsigned fastQuals = quals.getFastQualifiers();
1984 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001985
1986 // Check if we've already instantiated this type.
1987 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001988 ExtQuals::Profile(ID, baseType, quals);
1989 void *insertPos = 0;
1990 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1991 assert(eq->getQualifiers() == quals);
1992 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001993 }
1994
John McCall33ddac02011-01-19 10:06:00 +00001995 // If the base type is not canonical, make the appropriate canonical type.
1996 QualType canon;
1997 if (!baseType->isCanonicalUnqualified()) {
1998 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00001999 canonSplit.Quals.addConsistentQualifiers(quals);
2000 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002001
2002 // Re-find the insert position.
2003 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2004 }
2005
2006 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2007 ExtQualNodes.InsertNode(eq, insertPos);
2008 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002009}
2010
Jay Foad39c79802011-01-12 09:06:06 +00002011QualType
2012ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002013 QualType CanT = getCanonicalType(T);
2014 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002015 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002016
John McCall8ccfcb52009-09-24 19:53:00 +00002017 // If we are composing extended qualifiers together, merge together
2018 // into one ExtQuals node.
2019 QualifierCollector Quals;
2020 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002021
John McCall8ccfcb52009-09-24 19:53:00 +00002022 // If this type already has an address space specified, it cannot get
2023 // another one.
2024 assert(!Quals.hasAddressSpace() &&
2025 "Type cannot be in multiple addr spaces!");
2026 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002027
John McCall8ccfcb52009-09-24 19:53:00 +00002028 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002029}
2030
Chris Lattnerd60183d2009-02-18 22:53:11 +00002031QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002032 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002033 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002034 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002035 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002036
John McCall53fa7142010-12-24 02:08:15 +00002037 if (const PointerType *ptr = T->getAs<PointerType>()) {
2038 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002039 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002040 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2041 return getPointerType(ResultType);
2042 }
2043 }
Mike Stump11289f42009-09-09 15:08:12 +00002044
John McCall8ccfcb52009-09-24 19:53:00 +00002045 // If we are composing extended qualifiers together, merge together
2046 // into one ExtQuals node.
2047 QualifierCollector Quals;
2048 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002049
John McCall8ccfcb52009-09-24 19:53:00 +00002050 // If this type already has an ObjCGC specified, it cannot get
2051 // another one.
2052 assert(!Quals.hasObjCGCAttr() &&
2053 "Type cannot have multiple ObjCGCs!");
2054 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002055
John McCall8ccfcb52009-09-24 19:53:00 +00002056 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002057}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002058
John McCall4f5019e2010-12-19 02:44:49 +00002059const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2060 FunctionType::ExtInfo Info) {
2061 if (T->getExtInfo() == Info)
2062 return T;
2063
2064 QualType Result;
2065 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
2066 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
2067 } else {
2068 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2069 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2070 EPI.ExtInfo = Info;
Jordan Rose5c382722013-03-08 21:51:21 +00002071 Result = getFunctionType(FPT->getResultType(),
2072 ArrayRef<QualType>(FPT->arg_type_begin(),
2073 FPT->getNumArgs()),
2074 EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002075 }
2076
2077 return cast<FunctionType>(Result.getTypePtr());
2078}
2079
Richard Smith2a7d4812013-05-04 07:00:32 +00002080void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2081 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002082 FD = FD->getMostRecentDecl();
2083 while (true) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002084 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2085 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2086 FD->setType(getFunctionType(ResultType, FPT->getArgTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002087 if (FunctionDecl *Next = FD->getPreviousDecl())
2088 FD = Next;
2089 else
2090 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002091 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002092 if (ASTMutationListener *L = getASTMutationListener())
2093 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002094}
2095
Chris Lattnerc6395932007-06-22 20:56:16 +00002096/// getComplexType - Return the uniqued reference to the type for a complex
2097/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002098QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002099 // Unique pointers, to guarantee there is only one pointer of a particular
2100 // structure.
2101 llvm::FoldingSetNodeID ID;
2102 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002103
Chris Lattnerc6395932007-06-22 20:56:16 +00002104 void *InsertPos = 0;
2105 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2106 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002107
Chris Lattnerc6395932007-06-22 20:56:16 +00002108 // If the pointee type isn't canonical, this won't be a canonical type either,
2109 // so fill in the canonical type field.
2110 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002111 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002112 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002113
Chris Lattnerc6395932007-06-22 20:56:16 +00002114 // Get the new insert position for the node we care about.
2115 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002116 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002117 }
John McCall90d1c2d2009-09-24 23:30:46 +00002118 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002119 Types.push_back(New);
2120 ComplexTypes.InsertNode(New, InsertPos);
2121 return QualType(New, 0);
2122}
2123
Chris Lattner970e54e2006-11-12 00:37:36 +00002124/// getPointerType - Return the uniqued reference to the type for a pointer to
2125/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002126QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002127 // Unique pointers, to guarantee there is only one pointer of a particular
2128 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002129 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002130 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002131
Chris Lattner67521df2007-01-27 01:29:36 +00002132 void *InsertPos = 0;
2133 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002134 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002135
Chris Lattner7ccecb92006-11-12 08:50:50 +00002136 // If the pointee type isn't canonical, this won't be a canonical type either,
2137 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002138 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002139 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002140 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002141
Bob Wilsonc8541f22013-03-15 17:12:43 +00002142 // Get the new insert position for the node we care about.
2143 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2144 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2145 }
John McCall90d1c2d2009-09-24 23:30:46 +00002146 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002147 Types.push_back(New);
2148 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002149 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002150}
2151
Mike Stump11289f42009-09-09 15:08:12 +00002152/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002153/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002154QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002155 assert(T->isFunctionType() && "block of function types only");
2156 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002157 // structure.
2158 llvm::FoldingSetNodeID ID;
2159 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002160
Steve Naroffec33ed92008-08-27 16:04:49 +00002161 void *InsertPos = 0;
2162 if (BlockPointerType *PT =
2163 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2164 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002165
2166 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002167 // type either so fill in the canonical type field.
2168 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002169 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002170 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002171
Steve Naroffec33ed92008-08-27 16:04:49 +00002172 // Get the new insert position for the node we care about.
2173 BlockPointerType *NewIP =
2174 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002175 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002176 }
John McCall90d1c2d2009-09-24 23:30:46 +00002177 BlockPointerType *New
2178 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002179 Types.push_back(New);
2180 BlockPointerTypes.InsertNode(New, InsertPos);
2181 return QualType(New, 0);
2182}
2183
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002184/// getLValueReferenceType - Return the uniqued reference to the type for an
2185/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002186QualType
2187ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002188 assert(getCanonicalType(T) != OverloadTy &&
2189 "Unresolved overloaded function type");
2190
Bill Wendling3708c182007-05-27 10:15:43 +00002191 // Unique pointers, to guarantee there is only one pointer of a particular
2192 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002193 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002194 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002195
2196 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002197 if (LValueReferenceType *RT =
2198 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002199 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002200
John McCallfc93cf92009-10-22 22:37:11 +00002201 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2202
Bill Wendling3708c182007-05-27 10:15:43 +00002203 // If the referencee type isn't canonical, this won't be a canonical type
2204 // either, so fill in the canonical type field.
2205 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002206 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2207 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2208 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002209
Bill Wendling3708c182007-05-27 10:15:43 +00002210 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002211 LValueReferenceType *NewIP =
2212 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002213 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002214 }
2215
John McCall90d1c2d2009-09-24 23:30:46 +00002216 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002217 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2218 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002219 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002220 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002221
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002222 return QualType(New, 0);
2223}
2224
2225/// getRValueReferenceType - Return the uniqued reference to the type for an
2226/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002227QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002228 // Unique pointers, to guarantee there is only one pointer of a particular
2229 // structure.
2230 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002231 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002232
2233 void *InsertPos = 0;
2234 if (RValueReferenceType *RT =
2235 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2236 return QualType(RT, 0);
2237
John McCallfc93cf92009-10-22 22:37:11 +00002238 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2239
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002240 // If the referencee type isn't canonical, this won't be a canonical type
2241 // either, so fill in the canonical type field.
2242 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002243 if (InnerRef || !T.isCanonical()) {
2244 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2245 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002246
2247 // Get the new insert position for the node we care about.
2248 RValueReferenceType *NewIP =
2249 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002250 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002251 }
2252
John McCall90d1c2d2009-09-24 23:30:46 +00002253 RValueReferenceType *New
2254 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002255 Types.push_back(New);
2256 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002257 return QualType(New, 0);
2258}
2259
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002260/// getMemberPointerType - Return the uniqued reference to the type for a
2261/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002262QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002263 // Unique pointers, to guarantee there is only one pointer of a particular
2264 // structure.
2265 llvm::FoldingSetNodeID ID;
2266 MemberPointerType::Profile(ID, T, Cls);
2267
2268 void *InsertPos = 0;
2269 if (MemberPointerType *PT =
2270 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2271 return QualType(PT, 0);
2272
2273 // If the pointee or class type isn't canonical, this won't be a canonical
2274 // type either, so fill in the canonical type field.
2275 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002276 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002277 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2278
2279 // Get the new insert position for the node we care about.
2280 MemberPointerType *NewIP =
2281 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002282 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002283 }
John McCall90d1c2d2009-09-24 23:30:46 +00002284 MemberPointerType *New
2285 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002286 Types.push_back(New);
2287 MemberPointerTypes.InsertNode(New, InsertPos);
2288 return QualType(New, 0);
2289}
2290
Mike Stump11289f42009-09-09 15:08:12 +00002291/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002292/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002293QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002294 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002295 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002296 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002297 assert((EltTy->isDependentType() ||
2298 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002299 "Constant array of VLAs is illegal!");
2300
Chris Lattnere2df3f92009-05-13 04:12:56 +00002301 // Convert the array size into a canonical width matching the pointer size for
2302 // the target.
2303 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002304 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002305 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002306
Chris Lattner23b7eb62007-06-15 23:05:46 +00002307 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002308 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002309
Chris Lattner36f8e652007-01-27 08:31:04 +00002310 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002311 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002312 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002313 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002314
John McCall33ddac02011-01-19 10:06:00 +00002315 // If the element type isn't canonical or has qualifiers, this won't
2316 // be a canonical type either, so fill in the canonical type field.
2317 QualType Canon;
2318 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2319 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002320 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002321 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002322 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002323
Chris Lattner36f8e652007-01-27 08:31:04 +00002324 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002325 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002326 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002327 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002328 }
Mike Stump11289f42009-09-09 15:08:12 +00002329
John McCall90d1c2d2009-09-24 23:30:46 +00002330 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002331 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002332 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002333 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002334 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002335}
2336
John McCall06549462011-01-18 08:40:38 +00002337/// getVariableArrayDecayedType - Turns the given type, which may be
2338/// variably-modified, into the corresponding type with all the known
2339/// sizes replaced with [*].
2340QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2341 // Vastly most common case.
2342 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002343
John McCall06549462011-01-18 08:40:38 +00002344 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002345
John McCall06549462011-01-18 08:40:38 +00002346 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002347 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002348 switch (ty->getTypeClass()) {
2349#define TYPE(Class, Base)
2350#define ABSTRACT_TYPE(Class, Base)
2351#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2352#include "clang/AST/TypeNodes.def"
2353 llvm_unreachable("didn't desugar past all non-canonical types?");
2354
2355 // These types should never be variably-modified.
2356 case Type::Builtin:
2357 case Type::Complex:
2358 case Type::Vector:
2359 case Type::ExtVector:
2360 case Type::DependentSizedExtVector:
2361 case Type::ObjCObject:
2362 case Type::ObjCInterface:
2363 case Type::ObjCObjectPointer:
2364 case Type::Record:
2365 case Type::Enum:
2366 case Type::UnresolvedUsing:
2367 case Type::TypeOfExpr:
2368 case Type::TypeOf:
2369 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002370 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002371 case Type::DependentName:
2372 case Type::InjectedClassName:
2373 case Type::TemplateSpecialization:
2374 case Type::DependentTemplateSpecialization:
2375 case Type::TemplateTypeParm:
2376 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002377 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002378 case Type::PackExpansion:
2379 llvm_unreachable("type should never be variably-modified");
2380
2381 // These types can be variably-modified but should never need to
2382 // further decay.
2383 case Type::FunctionNoProto:
2384 case Type::FunctionProto:
2385 case Type::BlockPointer:
2386 case Type::MemberPointer:
2387 return type;
2388
2389 // These types can be variably-modified. All these modifications
2390 // preserve structure except as noted by comments.
2391 // TODO: if we ever care about optimizing VLAs, there are no-op
2392 // optimizations available here.
2393 case Type::Pointer:
2394 result = getPointerType(getVariableArrayDecayedType(
2395 cast<PointerType>(ty)->getPointeeType()));
2396 break;
2397
2398 case Type::LValueReference: {
2399 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2400 result = getLValueReferenceType(
2401 getVariableArrayDecayedType(lv->getPointeeType()),
2402 lv->isSpelledAsLValue());
2403 break;
2404 }
2405
2406 case Type::RValueReference: {
2407 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2408 result = getRValueReferenceType(
2409 getVariableArrayDecayedType(lv->getPointeeType()));
2410 break;
2411 }
2412
Eli Friedman0dfb8892011-10-06 23:00:33 +00002413 case Type::Atomic: {
2414 const AtomicType *at = cast<AtomicType>(ty);
2415 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2416 break;
2417 }
2418
John McCall06549462011-01-18 08:40:38 +00002419 case Type::ConstantArray: {
2420 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2421 result = getConstantArrayType(
2422 getVariableArrayDecayedType(cat->getElementType()),
2423 cat->getSize(),
2424 cat->getSizeModifier(),
2425 cat->getIndexTypeCVRQualifiers());
2426 break;
2427 }
2428
2429 case Type::DependentSizedArray: {
2430 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2431 result = getDependentSizedArrayType(
2432 getVariableArrayDecayedType(dat->getElementType()),
2433 dat->getSizeExpr(),
2434 dat->getSizeModifier(),
2435 dat->getIndexTypeCVRQualifiers(),
2436 dat->getBracketsRange());
2437 break;
2438 }
2439
2440 // Turn incomplete types into [*] types.
2441 case Type::IncompleteArray: {
2442 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2443 result = getVariableArrayType(
2444 getVariableArrayDecayedType(iat->getElementType()),
2445 /*size*/ 0,
2446 ArrayType::Normal,
2447 iat->getIndexTypeCVRQualifiers(),
2448 SourceRange());
2449 break;
2450 }
2451
2452 // Turn VLA types into [*] types.
2453 case Type::VariableArray: {
2454 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2455 result = getVariableArrayType(
2456 getVariableArrayDecayedType(vat->getElementType()),
2457 /*size*/ 0,
2458 ArrayType::Star,
2459 vat->getIndexTypeCVRQualifiers(),
2460 vat->getBracketsRange());
2461 break;
2462 }
2463 }
2464
2465 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002466 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002467}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002468
Steve Naroffcadebd02007-08-30 18:14:25 +00002469/// getVariableArrayType - Returns a non-unique reference to the type for a
2470/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002471QualType ASTContext::getVariableArrayType(QualType EltTy,
2472 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002473 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002474 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002475 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002476 // Since we don't unique expressions, it isn't possible to unique VLA's
2477 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002478 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002479
John McCall33ddac02011-01-19 10:06:00 +00002480 // Be sure to pull qualifiers off the element type.
2481 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2482 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002483 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002484 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002485 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002486 }
2487
John McCall90d1c2d2009-09-24 23:30:46 +00002488 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002489 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002490
2491 VariableArrayTypes.push_back(New);
2492 Types.push_back(New);
2493 return QualType(New, 0);
2494}
2495
Douglas Gregor4619e432008-12-05 23:32:09 +00002496/// getDependentSizedArrayType - Returns a non-unique reference to
2497/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002498/// type.
John McCall33ddac02011-01-19 10:06:00 +00002499QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2500 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002501 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002502 unsigned elementTypeQuals,
2503 SourceRange brackets) const {
2504 assert((!numElements || numElements->isTypeDependent() ||
2505 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002506 "Size must be type- or value-dependent!");
2507
John McCall33ddac02011-01-19 10:06:00 +00002508 // Dependently-sized array types that do not have a specified number
2509 // of elements will have their sizes deduced from a dependent
2510 // initializer. We do no canonicalization here at all, which is okay
2511 // because they can't be used in most locations.
2512 if (!numElements) {
2513 DependentSizedArrayType *newType
2514 = new (*this, TypeAlignment)
2515 DependentSizedArrayType(*this, elementType, QualType(),
2516 numElements, ASM, elementTypeQuals,
2517 brackets);
2518 Types.push_back(newType);
2519 return QualType(newType, 0);
2520 }
2521
2522 // Otherwise, we actually build a new type every time, but we
2523 // also build a canonical type.
2524
2525 SplitQualType canonElementType = getCanonicalType(elementType).split();
2526
2527 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002528 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002529 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002530 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002531 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002532
John McCall33ddac02011-01-19 10:06:00 +00002533 // Look for an existing type with these properties.
2534 DependentSizedArrayType *canonTy =
2535 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002536
John McCall33ddac02011-01-19 10:06:00 +00002537 // If we don't have one, build one.
2538 if (!canonTy) {
2539 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002540 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002541 QualType(), numElements, ASM, elementTypeQuals,
2542 brackets);
2543 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2544 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002545 }
2546
John McCall33ddac02011-01-19 10:06:00 +00002547 // Apply qualifiers from the element type to the array.
2548 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002549 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002550
John McCall33ddac02011-01-19 10:06:00 +00002551 // If we didn't need extra canonicalization for the element type,
2552 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00002553 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00002554 return canon;
2555
2556 // Otherwise, we need to build a type which follows the spelling
2557 // of the element type.
2558 DependentSizedArrayType *sugaredType
2559 = new (*this, TypeAlignment)
2560 DependentSizedArrayType(*this, elementType, canon, numElements,
2561 ASM, elementTypeQuals, brackets);
2562 Types.push_back(sugaredType);
2563 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002564}
2565
John McCall33ddac02011-01-19 10:06:00 +00002566QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002567 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002568 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002569 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002570 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002571
John McCall33ddac02011-01-19 10:06:00 +00002572 void *insertPos = 0;
2573 if (IncompleteArrayType *iat =
2574 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2575 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002576
2577 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002578 // either, so fill in the canonical type field. We also have to pull
2579 // qualifiers off the element type.
2580 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002581
John McCall33ddac02011-01-19 10:06:00 +00002582 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2583 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002584 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002585 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002586 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002587
2588 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002589 IncompleteArrayType *existing =
2590 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2591 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002592 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002593
John McCall33ddac02011-01-19 10:06:00 +00002594 IncompleteArrayType *newType = new (*this, TypeAlignment)
2595 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002596
John McCall33ddac02011-01-19 10:06:00 +00002597 IncompleteArrayTypes.InsertNode(newType, insertPos);
2598 Types.push_back(newType);
2599 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002600}
2601
Steve Naroff91fcddb2007-07-18 18:00:27 +00002602/// getVectorType - Return the unique reference to a vector type of
2603/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002604QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002605 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002606 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002607
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002608 // Check if we've already instantiated a vector of this type.
2609 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002610 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002611
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002612 void *InsertPos = 0;
2613 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2614 return QualType(VTP, 0);
2615
2616 // If the element type isn't canonical, this won't be a canonical type either,
2617 // so fill in the canonical type field.
2618 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002619 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002620 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002621
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002622 // Get the new insert position for the node we care about.
2623 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002624 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002625 }
John McCall90d1c2d2009-09-24 23:30:46 +00002626 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002627 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002628 VectorTypes.InsertNode(New, InsertPos);
2629 Types.push_back(New);
2630 return QualType(New, 0);
2631}
2632
Nate Begemance4d7fc2008-04-18 23:10:10 +00002633/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002634/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002635QualType
2636ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002637 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002638
Steve Naroff91fcddb2007-07-18 18:00:27 +00002639 // Check if we've already instantiated a vector of this type.
2640 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002641 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002642 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002643 void *InsertPos = 0;
2644 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2645 return QualType(VTP, 0);
2646
2647 // If the element type isn't canonical, this won't be a canonical type either,
2648 // so fill in the canonical type field.
2649 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002650 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002651 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002652
Steve Naroff91fcddb2007-07-18 18:00:27 +00002653 // Get the new insert position for the node we care about.
2654 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002655 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002656 }
John McCall90d1c2d2009-09-24 23:30:46 +00002657 ExtVectorType *New = new (*this, TypeAlignment)
2658 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002659 VectorTypes.InsertNode(New, InsertPos);
2660 Types.push_back(New);
2661 return QualType(New, 0);
2662}
2663
Jay Foad39c79802011-01-12 09:06:06 +00002664QualType
2665ASTContext::getDependentSizedExtVectorType(QualType vecType,
2666 Expr *SizeExpr,
2667 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002668 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002669 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002670 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002671
Douglas Gregor352169a2009-07-31 03:54:25 +00002672 void *InsertPos = 0;
2673 DependentSizedExtVectorType *Canon
2674 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2675 DependentSizedExtVectorType *New;
2676 if (Canon) {
2677 // We already have a canonical version of this array type; use it as
2678 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002679 New = new (*this, TypeAlignment)
2680 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2681 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002682 } else {
2683 QualType CanonVecTy = getCanonicalType(vecType);
2684 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002685 New = new (*this, TypeAlignment)
2686 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2687 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002688
2689 DependentSizedExtVectorType *CanonCheck
2690 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2691 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2692 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002693 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2694 } else {
2695 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2696 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002697 New = new (*this, TypeAlignment)
2698 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002699 }
2700 }
Mike Stump11289f42009-09-09 15:08:12 +00002701
Douglas Gregor758a8692009-06-17 21:51:59 +00002702 Types.push_back(New);
2703 return QualType(New, 0);
2704}
2705
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002706/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002707///
Jay Foad39c79802011-01-12 09:06:06 +00002708QualType
2709ASTContext::getFunctionNoProtoType(QualType ResultTy,
2710 const FunctionType::ExtInfo &Info) const {
Roman Divacky65b88cd2011-03-01 17:40:53 +00002711 const CallingConv DefaultCC = Info.getCC();
2712 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2713 CC_X86StdCall : DefaultCC;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002714 // Unique functions, to guarantee there is only one function of a particular
2715 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002716 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002717 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002718
Chris Lattner47955de2007-01-27 08:37:20 +00002719 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002720 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002721 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002722 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002723
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002724 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00002725 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00002726 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002727 Canonical =
2728 getFunctionNoProtoType(getCanonicalType(ResultTy),
2729 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00002730
Chris Lattner47955de2007-01-27 08:37:20 +00002731 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002732 FunctionNoProtoType *NewIP =
2733 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002734 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002735 }
Mike Stump11289f42009-09-09 15:08:12 +00002736
Roman Divacky65b88cd2011-03-01 17:40:53 +00002737 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002738 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002739 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002740 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002741 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002742 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002743}
2744
Douglas Gregorcd780372013-01-17 23:36:45 +00002745/// \brief Determine whether \p T is canonical as the result type of a function.
2746static bool isCanonicalResultType(QualType T) {
2747 return T.isCanonical() &&
2748 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2749 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2750}
2751
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002752/// getFunctionType - Return a normal function type with a typed argument
2753/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00002754QualType
Jordan Rose5c382722013-03-08 21:51:21 +00002755ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad39c79802011-01-12 09:06:06 +00002756 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rose5c382722013-03-08 21:51:21 +00002757 size_t NumArgs = ArgArray.size();
2758
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002759 // Unique functions, to guarantee there is only one function of a particular
2760 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002761 llvm::FoldingSetNodeID ID;
Jordan Rose5c382722013-03-08 21:51:21 +00002762 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
2763 *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002764
2765 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002766 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002767 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002768 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002769
2770 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002771 bool isCanonical =
Douglas Gregorcd780372013-01-17 23:36:45 +00002772 EPI.ExceptionSpecType == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smith5e580292012-02-10 09:58:53 +00002773 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002774 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002775 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002776 isCanonical = false;
2777
Roman Divacky65b88cd2011-03-01 17:40:53 +00002778 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2779 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2780 CC_X86StdCall : DefaultCC;
John McCalldb40c7f2010-12-14 08:05:40 +00002781
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002782 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002783 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002784 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00002785 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002786 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002787 CanonicalArgs.reserve(NumArgs);
2788 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002789 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002790
John McCalldb40c7f2010-12-14 08:05:40 +00002791 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002792 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002793 CanonicalEPI.ExceptionSpecType = EST_None;
2794 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002795 CanonicalEPI.ExtInfo
2796 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2797
Douglas Gregorcd780372013-01-17 23:36:45 +00002798 // Result types do not have ARC lifetime qualifiers.
2799 QualType CanResultTy = getCanonicalType(ResultTy);
2800 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2801 Qualifiers Qs = CanResultTy.getQualifiers();
2802 Qs.removeObjCLifetime();
2803 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2804 }
2805
Jordan Rose5c382722013-03-08 21:51:21 +00002806 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002807
Chris Lattnerfd4de792007-01-27 01:15:32 +00002808 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002809 FunctionProtoType *NewIP =
2810 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002811 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002812 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002813
John McCall31168b02011-06-15 23:02:42 +00002814 // FunctionProtoType objects are allocated with extra bytes after
2815 // them for three variable size arrays at the end:
2816 // - parameter types
2817 // - exception types
2818 // - consumed-arguments flags
2819 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00002820 // expression, or information used to resolve the exception
2821 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00002822 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002823 NumArgs * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002824 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002825 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002826 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002827 Size += sizeof(Expr*);
Richard Smithf623c962012-04-17 00:58:00 +00002828 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00002829 Size += 2 * sizeof(FunctionDecl*);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002830 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2831 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002832 }
John McCall31168b02011-06-15 23:02:42 +00002833 if (EPI.ConsumedArguments)
2834 Size += NumArgs * sizeof(bool);
2835
John McCalldb40c7f2010-12-14 08:05:40 +00002836 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002837 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2838 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Jordan Rose5c382722013-03-08 21:51:21 +00002839 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002840 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002841 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002842 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002843}
Chris Lattneref51c202006-11-10 07:17:23 +00002844
John McCalle78aac42010-03-10 03:28:59 +00002845#ifndef NDEBUG
2846static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2847 if (!isa<CXXRecordDecl>(D)) return false;
2848 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2849 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2850 return true;
2851 if (RD->getDescribedClassTemplate() &&
2852 !isa<ClassTemplateSpecializationDecl>(RD))
2853 return true;
2854 return false;
2855}
2856#endif
2857
2858/// getInjectedClassNameType - Return the unique reference to the
2859/// injected class name type for the specified templated declaration.
2860QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002861 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002862 assert(NeedsInjectedClassNameType(Decl));
2863 if (Decl->TypeForDecl) {
2864 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00002865 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00002866 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2867 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2868 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2869 } else {
John McCall424cec92011-01-19 06:33:43 +00002870 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002871 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002872 Decl->TypeForDecl = newType;
2873 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002874 }
2875 return QualType(Decl->TypeForDecl, 0);
2876}
2877
Douglas Gregor83a586e2008-04-13 21:07:44 +00002878/// getTypeDeclType - Return the unique reference to the type for the
2879/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002880QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002881 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002882 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002883
Richard Smithdda56e42011-04-15 14:24:37 +00002884 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002885 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002886
John McCall96f0b5f2010-03-10 06:48:02 +00002887 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2888 "Template type parameter types are always available.");
2889
John McCall81e38502010-02-16 03:57:14 +00002890 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002891 assert(!Record->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002892 "struct/union has previous declaration");
2893 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002894 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002895 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002896 assert(!Enum->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002897 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002898 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002899 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002900 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002901 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2902 Decl->TypeForDecl = newType;
2903 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002904 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002905 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002906
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002907 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002908}
2909
Chris Lattner32d920b2007-01-26 02:01:53 +00002910/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002911/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002912QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002913ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2914 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002915 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002916
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002917 if (Canonical.isNull())
2918 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002919 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002920 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002921 Decl->TypeForDecl = newType;
2922 Types.push_back(newType);
2923 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002924}
2925
Jay Foad39c79802011-01-12 09:06:06 +00002926QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002927 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2928
Douglas Gregorec9fd132012-01-14 16:38:05 +00002929 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002930 if (PrevDecl->TypeForDecl)
2931 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2932
John McCall424cec92011-01-19 06:33:43 +00002933 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2934 Decl->TypeForDecl = newType;
2935 Types.push_back(newType);
2936 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002937}
2938
Jay Foad39c79802011-01-12 09:06:06 +00002939QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002940 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2941
Douglas Gregorec9fd132012-01-14 16:38:05 +00002942 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002943 if (PrevDecl->TypeForDecl)
2944 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2945
John McCall424cec92011-01-19 06:33:43 +00002946 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2947 Decl->TypeForDecl = newType;
2948 Types.push_back(newType);
2949 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002950}
2951
John McCall81904512011-01-06 01:58:22 +00002952QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2953 QualType modifiedType,
2954 QualType equivalentType) {
2955 llvm::FoldingSetNodeID id;
2956 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2957
2958 void *insertPos = 0;
2959 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2960 if (type) return QualType(type, 0);
2961
2962 QualType canon = getCanonicalType(equivalentType);
2963 type = new (*this, TypeAlignment)
2964 AttributedType(canon, attrKind, modifiedType, equivalentType);
2965
2966 Types.push_back(type);
2967 AttributedTypes.InsertNode(type, insertPos);
2968
2969 return QualType(type, 0);
2970}
2971
2972
John McCallcebee162009-10-18 09:09:24 +00002973/// \brief Retrieve a substitution-result type.
2974QualType
2975ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00002976 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00002977 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00002978 && "replacement types must always be canonical");
2979
2980 llvm::FoldingSetNodeID ID;
2981 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2982 void *InsertPos = 0;
2983 SubstTemplateTypeParmType *SubstParm
2984 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2985
2986 if (!SubstParm) {
2987 SubstParm = new (*this, TypeAlignment)
2988 SubstTemplateTypeParmType(Parm, Replacement);
2989 Types.push_back(SubstParm);
2990 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2991 }
2992
2993 return QualType(SubstParm, 0);
2994}
2995
Douglas Gregorada4b792011-01-14 02:55:32 +00002996/// \brief Retrieve a
2997QualType ASTContext::getSubstTemplateTypeParmPackType(
2998 const TemplateTypeParmType *Parm,
2999 const TemplateArgument &ArgPack) {
3000#ifndef NDEBUG
3001 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
3002 PEnd = ArgPack.pack_end();
3003 P != PEnd; ++P) {
3004 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3005 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
3006 }
3007#endif
3008
3009 llvm::FoldingSetNodeID ID;
3010 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
3011 void *InsertPos = 0;
3012 if (SubstTemplateTypeParmPackType *SubstParm
3013 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3014 return QualType(SubstParm, 0);
3015
3016 QualType Canon;
3017 if (!Parm->isCanonicalUnqualified()) {
3018 Canon = getCanonicalType(QualType(Parm, 0));
3019 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3020 ArgPack);
3021 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3022 }
3023
3024 SubstTemplateTypeParmPackType *SubstParm
3025 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3026 ArgPack);
3027 Types.push_back(SubstParm);
3028 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3029 return QualType(SubstParm, 0);
3030}
3031
Douglas Gregoreff93e02009-02-05 23:33:38 +00003032/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003033/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003034/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003035QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003036 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003037 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003038 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003039 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003040 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003041 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003042 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3043
3044 if (TypeParm)
3045 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003046
Chandler Carruth08836322011-05-01 00:51:33 +00003047 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003048 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003049 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003050
3051 TemplateTypeParmType *TypeCheck
3052 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3053 assert(!TypeCheck && "Template type parameter canonical type broken");
3054 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003055 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003056 TypeParm = new (*this, TypeAlignment)
3057 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003058
3059 Types.push_back(TypeParm);
3060 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3061
3062 return QualType(TypeParm, 0);
3063}
3064
John McCalle78aac42010-03-10 03:28:59 +00003065TypeSourceInfo *
3066ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3067 SourceLocation NameLoc,
3068 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003069 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003070 assert(!Name.getAsDependentTemplateName() &&
3071 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003072 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003073
3074 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003075 TemplateSpecializationTypeLoc TL =
3076 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003077 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003078 TL.setTemplateNameLoc(NameLoc);
3079 TL.setLAngleLoc(Args.getLAngleLoc());
3080 TL.setRAngleLoc(Args.getRAngleLoc());
3081 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3082 TL.setArgLocInfo(i, Args[i].getLocInfo());
3083 return DI;
3084}
3085
Mike Stump11289f42009-09-09 15:08:12 +00003086QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003087ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003088 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003089 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003090 assert(!Template.getAsDependentTemplateName() &&
3091 "No dependent template names here!");
3092
John McCall6b51f282009-11-23 01:53:49 +00003093 unsigned NumArgs = Args.size();
3094
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003095 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00003096 ArgVec.reserve(NumArgs);
3097 for (unsigned i = 0; i != NumArgs; ++i)
3098 ArgVec.push_back(Args[i].getArgument());
3099
John McCall2408e322010-04-27 00:57:59 +00003100 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003101 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003102}
3103
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003104#ifndef NDEBUG
3105static bool hasAnyPackExpansions(const TemplateArgument *Args,
3106 unsigned NumArgs) {
3107 for (unsigned I = 0; I != NumArgs; ++I)
3108 if (Args[I].isPackExpansion())
3109 return true;
3110
3111 return true;
3112}
3113#endif
3114
John McCall0ad16662009-10-29 08:12:44 +00003115QualType
3116ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00003117 const TemplateArgument *Args,
3118 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003119 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003120 assert(!Template.getAsDependentTemplateName() &&
3121 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003122 // Look through qualified template names.
3123 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3124 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003125
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003126 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003127 Template.getAsTemplateDecl() &&
3128 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003129 QualType CanonType;
3130 if (!Underlying.isNull())
3131 CanonType = getCanonicalType(Underlying);
3132 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003133 // We can get here with an alias template when the specialization contains
3134 // a pack expansion that does not match up with a parameter pack.
3135 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3136 "Caller must compute aliased type");
3137 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003138 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3139 NumArgs);
3140 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003141
Douglas Gregora8e02e72009-07-28 23:00:59 +00003142 // Allocate the (non-canonical) template specialization type, but don't
3143 // try to unique it: these types typically have location information that
3144 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003145 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3146 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003147 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003148 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003149 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003150 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3151 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003152
Douglas Gregor8bf42052009-02-09 18:46:07 +00003153 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003154 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003155}
3156
Mike Stump11289f42009-09-09 15:08:12 +00003157QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003158ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3159 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00003160 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003161 assert(!Template.getAsDependentTemplateName() &&
3162 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003163
Douglas Gregore29139c2011-03-03 17:04:51 +00003164 // Look through qualified template names.
3165 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3166 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003167
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003168 // Build the canonical template specialization type.
3169 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003170 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003171 CanonArgs.reserve(NumArgs);
3172 for (unsigned I = 0; I != NumArgs; ++I)
3173 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3174
3175 // Determine whether this canonical template specialization type already
3176 // exists.
3177 llvm::FoldingSetNodeID ID;
3178 TemplateSpecializationType::Profile(ID, CanonTemplate,
3179 CanonArgs.data(), NumArgs, *this);
3180
3181 void *InsertPos = 0;
3182 TemplateSpecializationType *Spec
3183 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3184
3185 if (!Spec) {
3186 // Allocate a new canonical template specialization type.
3187 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3188 sizeof(TemplateArgument) * NumArgs),
3189 TypeAlignment);
3190 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3191 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003192 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003193 Types.push_back(Spec);
3194 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3195 }
3196
3197 assert(Spec->isDependentType() &&
3198 "Non-dependent template-id type must have a canonical type");
3199 return QualType(Spec, 0);
3200}
3201
3202QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003203ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3204 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003205 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003206 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003207 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003208
3209 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003210 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003211 if (T)
3212 return QualType(T, 0);
3213
Douglas Gregorc42075a2010-02-04 18:10:26 +00003214 QualType Canon = NamedType;
3215 if (!Canon.isCanonical()) {
3216 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003217 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3218 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003219 (void)CheckT;
3220 }
3221
Abramo Bagnara6150c882010-05-11 21:36:43 +00003222 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003223 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003224 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003225 return QualType(T, 0);
3226}
3227
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003228QualType
Jay Foad39c79802011-01-12 09:06:06 +00003229ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003230 llvm::FoldingSetNodeID ID;
3231 ParenType::Profile(ID, InnerType);
3232
3233 void *InsertPos = 0;
3234 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3235 if (T)
3236 return QualType(T, 0);
3237
3238 QualType Canon = InnerType;
3239 if (!Canon.isCanonical()) {
3240 Canon = getCanonicalType(InnerType);
3241 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3242 assert(!CheckT && "Paren canonical type broken");
3243 (void)CheckT;
3244 }
3245
3246 T = new (*this) ParenType(InnerType, Canon);
3247 Types.push_back(T);
3248 ParenTypes.InsertNode(T, InsertPos);
3249 return QualType(T, 0);
3250}
3251
Douglas Gregor02085352010-03-31 20:19:30 +00003252QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3253 NestedNameSpecifier *NNS,
3254 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003255 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003256 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
3257
3258 if (Canon.isNull()) {
3259 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00003260 ElaboratedTypeKeyword CanonKeyword = Keyword;
3261 if (Keyword == ETK_None)
3262 CanonKeyword = ETK_Typename;
3263
3264 if (CanonNNS != NNS || CanonKeyword != Keyword)
3265 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003266 }
3267
3268 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003269 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003270
3271 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003272 DependentNameType *T
3273 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003274 if (T)
3275 return QualType(T, 0);
3276
Douglas Gregor02085352010-03-31 20:19:30 +00003277 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003278 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003279 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003280 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003281}
3282
Mike Stump11289f42009-09-09 15:08:12 +00003283QualType
John McCallc392f372010-06-11 00:33:02 +00003284ASTContext::getDependentTemplateSpecializationType(
3285 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003286 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003287 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003288 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003289 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003290 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003291 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3292 ArgCopy.push_back(Args[I].getArgument());
3293 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3294 ArgCopy.size(),
3295 ArgCopy.data());
3296}
3297
3298QualType
3299ASTContext::getDependentTemplateSpecializationType(
3300 ElaboratedTypeKeyword Keyword,
3301 NestedNameSpecifier *NNS,
3302 const IdentifierInfo *Name,
3303 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00003304 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003305 assert((!NNS || NNS->isDependent()) &&
3306 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003307
Douglas Gregorc42075a2010-02-04 18:10:26 +00003308 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003309 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3310 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003311
3312 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00003313 DependentTemplateSpecializationType *T
3314 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003315 if (T)
3316 return QualType(T, 0);
3317
John McCallc392f372010-06-11 00:33:02 +00003318 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003319
John McCallc392f372010-06-11 00:33:02 +00003320 ElaboratedTypeKeyword CanonKeyword = Keyword;
3321 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3322
3323 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003324 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003325 for (unsigned I = 0; I != NumArgs; ++I) {
3326 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3327 if (!CanonArgs[I].structurallyEquals(Args[I]))
3328 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003329 }
3330
John McCallc392f372010-06-11 00:33:02 +00003331 QualType Canon;
3332 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3333 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3334 Name, NumArgs,
3335 CanonArgs.data());
3336
3337 // Find the insert position again.
3338 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3339 }
3340
3341 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3342 sizeof(TemplateArgument) * NumArgs),
3343 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003344 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00003345 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003346 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003347 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003348 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003349}
3350
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003351QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00003352 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003353 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003354 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003355
3356 assert(Pattern->containsUnexpandedParameterPack() &&
3357 "Pack expansions must expand one or more parameter packs");
3358 void *InsertPos = 0;
3359 PackExpansionType *T
3360 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3361 if (T)
3362 return QualType(T, 0);
3363
3364 QualType Canon;
3365 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003366 Canon = getCanonicalType(Pattern);
3367 // The canonical type might not contain an unexpanded parameter pack, if it
3368 // contains an alias template specialization which ignores one of its
3369 // parameters.
3370 if (Canon->containsUnexpandedParameterPack()) {
3371 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003372
Richard Smith68eea502012-07-16 00:20:35 +00003373 // Find the insert position again, in case we inserted an element into
3374 // PackExpansionTypes and invalidated our insert position.
3375 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3376 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003377 }
3378
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003379 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003380 Types.push_back(T);
3381 PackExpansionTypes.InsertNode(T, InsertPos);
3382 return QualType(T, 0);
3383}
3384
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003385/// CmpProtocolNames - Comparison predicate for sorting protocols
3386/// alphabetically.
3387static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3388 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00003389 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003390}
3391
John McCall8b07ec22010-05-15 11:32:37 +00003392static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00003393 unsigned NumProtocols) {
3394 if (NumProtocols == 0) return true;
3395
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003396 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3397 return false;
3398
John McCallfc93cf92009-10-22 22:37:11 +00003399 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003400 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3401 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003402 return false;
3403 return true;
3404}
3405
3406static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003407 unsigned &NumProtocols) {
3408 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00003409
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003410 // Sort protocols, keyed by name.
3411 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3412
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003413 // Canonicalize.
3414 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3415 Protocols[I] = Protocols[I]->getCanonicalDecl();
3416
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003417 // Remove duplicates.
3418 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3419 NumProtocols = ProtocolsEnd-Protocols;
3420}
3421
John McCall8b07ec22010-05-15 11:32:37 +00003422QualType ASTContext::getObjCObjectType(QualType BaseType,
3423 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003424 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00003425 // If the base type is an interface and there aren't any protocols
3426 // to add, then the interface type will do just fine.
3427 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3428 return BaseType;
3429
3430 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003431 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00003432 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00003433 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00003434 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3435 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003436
John McCall8b07ec22010-05-15 11:32:37 +00003437 // Build the canonical type, which has the canonical base type and
3438 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00003439 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00003440 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3441 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3442 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003443 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003444 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003445 unsigned UniqueCount = NumProtocols;
3446
John McCallfc93cf92009-10-22 22:37:11 +00003447 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00003448 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3449 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00003450 } else {
John McCall8b07ec22010-05-15 11:32:37 +00003451 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3452 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003453 }
3454
3455 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003456 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3457 }
3458
3459 unsigned Size = sizeof(ObjCObjectTypeImpl);
3460 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3461 void *Mem = Allocate(Size, TypeAlignment);
3462 ObjCObjectTypeImpl *T =
3463 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3464
3465 Types.push_back(T);
3466 ObjCObjectTypes.InsertNode(T, InsertPos);
3467 return QualType(T, 0);
3468}
3469
3470/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3471/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003472QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003473 llvm::FoldingSetNodeID ID;
3474 ObjCObjectPointerType::Profile(ID, ObjectT);
3475
3476 void *InsertPos = 0;
3477 if (ObjCObjectPointerType *QT =
3478 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3479 return QualType(QT, 0);
3480
3481 // Find the canonical object type.
3482 QualType Canonical;
3483 if (!ObjectT.isCanonical()) {
3484 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3485
3486 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003487 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3488 }
3489
Douglas Gregorf85bee62010-02-08 22:59:26 +00003490 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003491 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3492 ObjCObjectPointerType *QType =
3493 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003494
Steve Narofffb4330f2009-06-17 22:40:22 +00003495 Types.push_back(QType);
3496 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003497 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003498}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003499
Douglas Gregor1c283312010-08-11 12:19:30 +00003500/// getObjCInterfaceType - Return the unique reference to the type for the
3501/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003502QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3503 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003504 if (Decl->TypeForDecl)
3505 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003506
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003507 if (PrevDecl) {
3508 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3509 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3510 return QualType(PrevDecl->TypeForDecl, 0);
3511 }
3512
Douglas Gregor7671e532011-12-16 16:34:57 +00003513 // Prefer the definition, if there is one.
3514 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3515 Decl = Def;
3516
Douglas Gregor1c283312010-08-11 12:19:30 +00003517 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3518 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3519 Decl->TypeForDecl = T;
3520 Types.push_back(T);
3521 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003522}
3523
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003524/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3525/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003526/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003527/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003528/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003529QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003530 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003531 if (tofExpr->isTypeDependent()) {
3532 llvm::FoldingSetNodeID ID;
3533 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003534
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003535 void *InsertPos = 0;
3536 DependentTypeOfExprType *Canon
3537 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3538 if (Canon) {
3539 // We already have a "canonical" version of an identical, dependent
3540 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003541 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003542 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003543 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003544 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003545 Canon
3546 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003547 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3548 toe = Canon;
3549 }
3550 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003551 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003552 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003553 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003554 Types.push_back(toe);
3555 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003556}
3557
Steve Naroffa773cd52007-08-01 18:02:17 +00003558/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3559/// TypeOfType AST's. The only motivation to unique these nodes would be
3560/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003561/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003562/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003563QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003564 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003565 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003566 Types.push_back(tot);
3567 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003568}
3569
Anders Carlssonad6bd352009-06-24 21:24:56 +00003570
Anders Carlsson81df7b82009-06-24 19:06:50 +00003571/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3572/// DecltypeType AST's. The only motivation to unique these nodes would be
3573/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003574/// an issue. This doesn't effect the type checker, since it operates
David Blaikie876657b2011-11-06 22:28:03 +00003575/// on canonical types (which are always unique).
Douglas Gregor81495f32012-02-12 18:42:33 +00003576QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003577 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003578
3579 // C++0x [temp.type]p2:
3580 // If an expression e involves a template parameter, decltype(e) denotes a
3581 // unique dependent type. Two such decltype-specifiers refer to the same
3582 // type only if their expressions are equivalent (14.5.6.1).
3583 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003584 llvm::FoldingSetNodeID ID;
3585 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003586
Douglas Gregora21f6c32009-07-30 23:36:40 +00003587 void *InsertPos = 0;
3588 DependentDecltypeType *Canon
3589 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3590 if (Canon) {
3591 // We already have a "canonical" version of an equivalent, dependent
3592 // decltype type. Use that as our canonical type.
Richard Smithef8bf432012-08-13 20:08:14 +00003593 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
Douglas Gregora21f6c32009-07-30 23:36:40 +00003594 QualType((DecltypeType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003595 } else {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003596 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003597 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003598 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3599 dt = Canon;
3600 }
3601 } else {
Douglas Gregor81495f32012-02-12 18:42:33 +00003602 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3603 getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003604 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003605 Types.push_back(dt);
3606 return QualType(dt, 0);
3607}
3608
Alexis Hunte852b102011-05-24 22:41:36 +00003609/// getUnaryTransformationType - We don't unique these, since the memory
3610/// savings are minimal and these are rare.
3611QualType ASTContext::getUnaryTransformType(QualType BaseType,
3612 QualType UnderlyingType,
3613 UnaryTransformType::UTTKind Kind)
3614 const {
3615 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003616 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3617 Kind,
3618 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003619 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003620 Types.push_back(Ty);
3621 return QualType(Ty, 0);
3622}
3623
Richard Smith2a7d4812013-05-04 07:00:32 +00003624/// getAutoType - Return the uniqued reference to the 'auto' type which has been
3625/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3626/// canonical deduced-but-dependent 'auto' type.
3627QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
Richard Smith27d807c2013-04-30 13:56:41 +00003628 bool IsDependent) const {
Richard Smith2a7d4812013-05-04 07:00:32 +00003629 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
3630 return getAutoDeductType();
3631
3632 // Look in the folding set for an existing type.
Richard Smithb2bc2e62011-02-21 20:05:19 +00003633 void *InsertPos = 0;
Richard Smith2a7d4812013-05-04 07:00:32 +00003634 llvm::FoldingSetNodeID ID;
3635 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
3636 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3637 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003638
Richard Smith74aeef52013-04-26 16:15:35 +00003639 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smith27d807c2013-04-30 13:56:41 +00003640 IsDecltypeAuto,
3641 IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003642 Types.push_back(AT);
3643 if (InsertPos)
3644 AutoTypes.InsertNode(AT, InsertPos);
3645 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003646}
3647
Eli Friedman0dfb8892011-10-06 23:00:33 +00003648/// getAtomicType - Return the uniqued reference to the atomic type for
3649/// the given value type.
3650QualType ASTContext::getAtomicType(QualType T) const {
3651 // Unique pointers, to guarantee there is only one pointer of a particular
3652 // structure.
3653 llvm::FoldingSetNodeID ID;
3654 AtomicType::Profile(ID, T);
3655
3656 void *InsertPos = 0;
3657 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3658 return QualType(AT, 0);
3659
3660 // If the atomic value type isn't canonical, this won't be a canonical type
3661 // either, so fill in the canonical type field.
3662 QualType Canonical;
3663 if (!T.isCanonical()) {
3664 Canonical = getAtomicType(getCanonicalType(T));
3665
3666 // Get the new insert position for the node we care about.
3667 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3668 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3669 }
3670 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3671 Types.push_back(New);
3672 AtomicTypes.InsertNode(New, InsertPos);
3673 return QualType(New, 0);
3674}
3675
Richard Smith02e85f32011-04-14 22:09:26 +00003676/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3677QualType ASTContext::getAutoDeductType() const {
3678 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00003679 AutoDeductTy = QualType(
3680 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
3681 /*dependent*/false),
3682 0);
Richard Smith02e85f32011-04-14 22:09:26 +00003683 return AutoDeductTy;
3684}
3685
3686/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3687QualType ASTContext::getAutoRRefDeductType() const {
3688 if (AutoRRefDeductTy.isNull())
3689 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3690 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3691 return AutoRRefDeductTy;
3692}
3693
Chris Lattnerfb072462007-01-23 05:45:31 +00003694/// getTagDeclType - Return the unique reference to the type for the
3695/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003696QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003697 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003698 // FIXME: What is the design on getTagDeclType when it requires casting
3699 // away const? mutable?
3700 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003701}
3702
Mike Stump11289f42009-09-09 15:08:12 +00003703/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3704/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3705/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003706CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003707 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003708}
Chris Lattnerfb072462007-01-23 05:45:31 +00003709
Hans Wennborg27541db2011-10-27 08:29:09 +00003710/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3711CanQualType ASTContext::getIntMaxType() const {
3712 return getFromTargetType(Target->getIntMaxType());
3713}
3714
3715/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3716CanQualType ASTContext::getUIntMaxType() const {
3717 return getFromTargetType(Target->getUIntMaxType());
3718}
3719
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003720/// getSignedWCharType - Return the type of "signed wchar_t".
3721/// Used when in C++, as a GCC extension.
3722QualType ASTContext::getSignedWCharType() const {
3723 // FIXME: derive from "Target" ?
3724 return WCharTy;
3725}
3726
3727/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3728/// Used when in C++, as a GCC extension.
3729QualType ASTContext::getUnsignedWCharType() const {
3730 // FIXME: derive from "Target" ?
3731 return UnsignedIntTy;
3732}
3733
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00003734QualType ASTContext::getIntPtrType() const {
3735 return getFromTargetType(Target->getIntPtrType());
3736}
3737
3738QualType ASTContext::getUIntPtrType() const {
3739 return getCorrespondingUnsignedType(getIntPtrType());
3740}
3741
Hans Wennborg27541db2011-10-27 08:29:09 +00003742/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003743/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3744QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003745 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003746}
3747
Eli Friedman4e91899e2012-11-27 02:58:24 +00003748/// \brief Return the unique type for "pid_t" defined in
3749/// <sys/types.h>. We need this to compute the correct type for vfork().
3750QualType ASTContext::getProcessIDType() const {
3751 return getFromTargetType(Target->getProcessIDType());
3752}
3753
Chris Lattnera21ad802008-04-02 05:18:44 +00003754//===----------------------------------------------------------------------===//
3755// Type Operators
3756//===----------------------------------------------------------------------===//
3757
Jay Foad39c79802011-01-12 09:06:06 +00003758CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003759 // Push qualifiers into arrays, and then discard any remaining
3760 // qualifiers.
3761 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003762 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003763 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003764 QualType Result;
3765 if (isa<ArrayType>(Ty)) {
3766 Result = getArrayDecayedType(QualType(Ty,0));
3767 } else if (isa<FunctionType>(Ty)) {
3768 Result = getPointerType(QualType(Ty, 0));
3769 } else {
3770 Result = QualType(Ty, 0);
3771 }
3772
3773 return CanQualType::CreateUnsafe(Result);
3774}
3775
John McCall6c9dd522011-01-18 07:41:22 +00003776QualType ASTContext::getUnqualifiedArrayType(QualType type,
3777 Qualifiers &quals) {
3778 SplitQualType splitType = type.getSplitUnqualifiedType();
3779
3780 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3781 // the unqualified desugared type and then drops it on the floor.
3782 // We then have to strip that sugar back off with
3783 // getUnqualifiedDesugaredType(), which is silly.
3784 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003785 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003786
3787 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003788 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003789 quals = splitType.Quals;
3790 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003791 }
3792
John McCall6c9dd522011-01-18 07:41:22 +00003793 // Otherwise, recurse on the array's element type.
3794 QualType elementType = AT->getElementType();
3795 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3796
3797 // If that didn't change the element type, AT has no qualifiers, so we
3798 // can just use the results in splitType.
3799 if (elementType == unqualElementType) {
3800 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00003801 quals = splitType.Quals;
3802 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00003803 }
3804
3805 // Otherwise, add in the qualifiers from the outermost type, then
3806 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00003807 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003808
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003809 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003810 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003811 CAT->getSizeModifier(), 0);
3812 }
3813
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003814 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003815 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003816 }
3817
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003818 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003819 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003820 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003821 VAT->getSizeModifier(),
3822 VAT->getIndexTypeCVRQualifiers(),
3823 VAT->getBracketsRange());
3824 }
3825
3826 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003827 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003828 DSAT->getSizeModifier(), 0,
3829 SourceRange());
3830}
3831
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003832/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3833/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3834/// they point to and return true. If T1 and T2 aren't pointer types
3835/// or pointer-to-member types, or if they are not similar at this
3836/// level, returns false and leaves T1 and T2 unchanged. Top-level
3837/// qualifiers on T1 and T2 are ignored. This function will typically
3838/// be called in a loop that successively "unwraps" pointer and
3839/// pointer-to-member types to compare them at each level.
3840bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3841 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3842 *T2PtrType = T2->getAs<PointerType>();
3843 if (T1PtrType && T2PtrType) {
3844 T1 = T1PtrType->getPointeeType();
3845 T2 = T2PtrType->getPointeeType();
3846 return true;
3847 }
3848
3849 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3850 *T2MPType = T2->getAs<MemberPointerType>();
3851 if (T1MPType && T2MPType &&
3852 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3853 QualType(T2MPType->getClass(), 0))) {
3854 T1 = T1MPType->getPointeeType();
3855 T2 = T2MPType->getPointeeType();
3856 return true;
3857 }
3858
David Blaikiebbafb8a2012-03-11 07:00:24 +00003859 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003860 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3861 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3862 if (T1OPType && T2OPType) {
3863 T1 = T1OPType->getPointeeType();
3864 T2 = T2OPType->getPointeeType();
3865 return true;
3866 }
3867 }
3868
3869 // FIXME: Block pointers, too?
3870
3871 return false;
3872}
3873
Jay Foad39c79802011-01-12 09:06:06 +00003874DeclarationNameInfo
3875ASTContext::getNameForTemplate(TemplateName Name,
3876 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003877 switch (Name.getKind()) {
3878 case TemplateName::QualifiedTemplate:
3879 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003880 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00003881 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3882 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003883
John McCalld9dfe3a2011-06-30 08:33:18 +00003884 case TemplateName::OverloadedTemplate: {
3885 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3886 // DNInfo work in progress: CHECKME: what about DNLoc?
3887 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3888 }
3889
3890 case TemplateName::DependentTemplate: {
3891 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003892 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00003893 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003894 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3895 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00003896 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003897 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3898 // DNInfo work in progress: FIXME: source locations?
3899 DeclarationNameLoc DNLoc;
3900 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3901 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3902 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00003903 }
3904 }
3905
John McCalld9dfe3a2011-06-30 08:33:18 +00003906 case TemplateName::SubstTemplateTemplateParm: {
3907 SubstTemplateTemplateParmStorage *subst
3908 = Name.getAsSubstTemplateTemplateParm();
3909 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3910 NameLoc);
3911 }
3912
3913 case TemplateName::SubstTemplateTemplateParmPack: {
3914 SubstTemplateTemplateParmPackStorage *subst
3915 = Name.getAsSubstTemplateTemplateParmPack();
3916 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3917 NameLoc);
3918 }
3919 }
3920
3921 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00003922}
3923
Jay Foad39c79802011-01-12 09:06:06 +00003924TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003925 switch (Name.getKind()) {
3926 case TemplateName::QualifiedTemplate:
3927 case TemplateName::Template: {
3928 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003929 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00003930 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003931 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3932
3933 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00003934 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003935 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00003936
John McCalld9dfe3a2011-06-30 08:33:18 +00003937 case TemplateName::OverloadedTemplate:
3938 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00003939
John McCalld9dfe3a2011-06-30 08:33:18 +00003940 case TemplateName::DependentTemplate: {
3941 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3942 assert(DTN && "Non-dependent template names must refer to template decls.");
3943 return DTN->CanonicalTemplateName;
3944 }
3945
3946 case TemplateName::SubstTemplateTemplateParm: {
3947 SubstTemplateTemplateParmStorage *subst
3948 = Name.getAsSubstTemplateTemplateParm();
3949 return getCanonicalTemplateName(subst->getReplacement());
3950 }
3951
3952 case TemplateName::SubstTemplateTemplateParmPack: {
3953 SubstTemplateTemplateParmPackStorage *subst
3954 = Name.getAsSubstTemplateTemplateParmPack();
3955 TemplateTemplateParmDecl *canonParameter
3956 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3957 TemplateArgument canonArgPack
3958 = getCanonicalTemplateArgument(subst->getArgumentPack());
3959 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3960 }
3961 }
3962
3963 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00003964}
3965
Douglas Gregoradee3e32009-11-11 23:06:43 +00003966bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3967 X = getCanonicalTemplateName(X);
3968 Y = getCanonicalTemplateName(Y);
3969 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3970}
3971
Mike Stump11289f42009-09-09 15:08:12 +00003972TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00003973ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00003974 switch (Arg.getKind()) {
3975 case TemplateArgument::Null:
3976 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003977
Douglas Gregora8e02e72009-07-28 23:00:59 +00003978 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00003979 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003980
Douglas Gregor31f55dc2012-04-06 22:40:38 +00003981 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00003982 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
3983 return TemplateArgument(D, Arg.isDeclForReferenceParam());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00003984 }
Mike Stump11289f42009-09-09 15:08:12 +00003985
Eli Friedmanb826a002012-09-26 02:36:12 +00003986 case TemplateArgument::NullPtr:
3987 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
3988 /*isNullPtr*/true);
3989
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003990 case TemplateArgument::Template:
3991 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003992
3993 case TemplateArgument::TemplateExpansion:
3994 return TemplateArgument(getCanonicalTemplateName(
3995 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00003996 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003997
Douglas Gregora8e02e72009-07-28 23:00:59 +00003998 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00003999 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00004000
Douglas Gregora8e02e72009-07-28 23:00:59 +00004001 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00004002 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00004003
Douglas Gregora8e02e72009-07-28 23:00:59 +00004004 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00004005 if (Arg.pack_size() == 0)
4006 return Arg;
4007
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004008 TemplateArgument *CanonArgs
4009 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00004010 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004011 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00004012 AEnd = Arg.pack_end();
4013 A != AEnd; (void)++A, ++Idx)
4014 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00004015
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004016 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00004017 }
4018 }
4019
4020 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00004021 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00004022}
4023
Douglas Gregor333489b2009-03-27 23:10:48 +00004024NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00004025ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00004026 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00004027 return 0;
4028
4029 switch (NNS->getKind()) {
4030 case NestedNameSpecifier::Identifier:
4031 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00004032 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00004033 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4034 NNS->getAsIdentifier());
4035
4036 case NestedNameSpecifier::Namespace:
4037 // A namespace is canonical; build a nested-name-specifier with
4038 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004039 return NestedNameSpecifier::Create(*this, 0,
4040 NNS->getAsNamespace()->getOriginalNamespace());
4041
4042 case NestedNameSpecifier::NamespaceAlias:
4043 // A namespace is canonical; build a nested-name-specifier with
4044 // this namespace and no prefix.
4045 return NestedNameSpecifier::Create(*this, 0,
4046 NNS->getAsNamespaceAlias()->getNamespace()
4047 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00004048
4049 case NestedNameSpecifier::TypeSpec:
4050 case NestedNameSpecifier::TypeSpecWithTemplate: {
4051 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004052
4053 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4054 // break it apart into its prefix and identifier, then reconsititute those
4055 // as the canonical nested-name-specifier. This is required to canonicalize
4056 // a dependent nested-name-specifier involving typedefs of dependent-name
4057 // types, e.g.,
4058 // typedef typename T::type T1;
4059 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00004060 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4061 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00004062 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004063
Eli Friedman5358a0a2012-03-03 04:09:56 +00004064 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4065 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4066 // first place?
John McCall33ddac02011-01-19 10:06:00 +00004067 return NestedNameSpecifier::Create(*this, 0, false,
4068 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00004069 }
4070
4071 case NestedNameSpecifier::Global:
4072 // The global specifier is canonical and unique.
4073 return NNS;
4074 }
4075
David Blaikie8a40f702012-01-17 06:56:22 +00004076 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00004077}
4078
Chris Lattner7adf0762008-08-04 07:31:14 +00004079
Jay Foad39c79802011-01-12 09:06:06 +00004080const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004081 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004082 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00004083 // Handle the common positive case fast.
4084 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4085 return AT;
4086 }
Mike Stump11289f42009-09-09 15:08:12 +00004087
John McCall8ccfcb52009-09-24 19:53:00 +00004088 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00004089 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00004090 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004091
John McCall8ccfcb52009-09-24 19:53:00 +00004092 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00004093 // implements C99 6.7.3p8: "If the specification of an array type includes
4094 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00004095
Chris Lattner7adf0762008-08-04 07:31:14 +00004096 // If we get here, we either have type qualifiers on the type, or we have
4097 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00004098 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00004099
John McCall33ddac02011-01-19 10:06:00 +00004100 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004101 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00004102
Chris Lattner7adf0762008-08-04 07:31:14 +00004103 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00004104 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall33ddac02011-01-19 10:06:00 +00004105 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00004106 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00004107
Chris Lattner7adf0762008-08-04 07:31:14 +00004108 // Otherwise, we have an array and we have qualifiers on it. Push the
4109 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00004110 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00004111
Chris Lattner7adf0762008-08-04 07:31:14 +00004112 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4113 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4114 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004115 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00004116 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4117 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4118 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004119 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00004120
Mike Stump11289f42009-09-09 15:08:12 +00004121 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00004122 = dyn_cast<DependentSizedArrayType>(ATy))
4123 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00004124 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004125 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00004126 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004127 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004128 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00004129
Chris Lattner7adf0762008-08-04 07:31:14 +00004130 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00004131 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004132 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00004133 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004134 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004135 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00004136}
4137
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004138QualType ASTContext::getAdjustedParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004139 // C99 6.7.5.3p7:
4140 // A declaration of a parameter as "array of type" shall be
4141 // adjusted to "qualified pointer to type", where the type
4142 // qualifiers (if any) are those specified within the [ and ] of
4143 // the array type derivation.
4144 if (T->isArrayType())
4145 return getArrayDecayedType(T);
4146
4147 // C99 6.7.5.3p8:
4148 // A declaration of a parameter as "function returning type"
4149 // shall be adjusted to "pointer to function returning type", as
4150 // in 6.3.2.1.
4151 if (T->isFunctionType())
4152 return getPointerType(T);
4153
4154 return T;
4155}
4156
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004157QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004158 T = getVariableArrayDecayedType(T);
4159 T = getAdjustedParameterType(T);
4160 return T.getUnqualifiedType();
4161}
4162
Chris Lattnera21ad802008-04-02 05:18:44 +00004163/// getArrayDecayedType - Return the properly qualified result of decaying the
4164/// specified array type to a pointer. This operation is non-trivial when
4165/// handling typedefs etc. The canonical type of "T" must be an array type,
4166/// this returns a pointer to a properly qualified element of the array.
4167///
4168/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004169QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004170 // Get the element type with 'getAsArrayType' so that we don't lose any
4171 // typedefs in the element type of the array. This also handles propagation
4172 // of type qualifiers from the array type into the element type if present
4173 // (C99 6.7.3p8).
4174 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4175 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004176
Chris Lattner7adf0762008-08-04 07:31:14 +00004177 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004178
4179 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00004180 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00004181}
4182
John McCall33ddac02011-01-19 10:06:00 +00004183QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4184 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00004185}
4186
John McCall33ddac02011-01-19 10:06:00 +00004187QualType ASTContext::getBaseElementType(QualType type) const {
4188 Qualifiers qs;
4189 while (true) {
4190 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004191 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00004192 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00004193
John McCall33ddac02011-01-19 10:06:00 +00004194 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00004195 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00004196 }
Mike Stump11289f42009-09-09 15:08:12 +00004197
John McCall33ddac02011-01-19 10:06:00 +00004198 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00004199}
4200
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004201/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00004202uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004203ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4204 uint64_t ElementCount = 1;
4205 do {
4206 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00004207 CA = dyn_cast_or_null<ConstantArrayType>(
4208 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004209 } while (CA);
4210 return ElementCount;
4211}
4212
Steve Naroff0af91202007-04-27 21:51:21 +00004213/// getFloatingRank - Return a relative rank for floating point types.
4214/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00004215static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00004216 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00004217 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00004218
John McCall9dd450b2009-09-21 23:43:11 +00004219 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4220 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004221 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004222 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00004223 case BuiltinType::Float: return FloatRank;
4224 case BuiltinType::Double: return DoubleRank;
4225 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00004226 }
4227}
4228
Mike Stump11289f42009-09-09 15:08:12 +00004229/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4230/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00004231/// 'typeDomain' is a real floating point or complex type.
4232/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004233QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4234 QualType Domain) const {
4235 FloatingRank EltRank = getFloatingRank(Size);
4236 if (Domain->isComplexType()) {
4237 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004238 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00004239 case FloatRank: return FloatComplexTy;
4240 case DoubleRank: return DoubleComplexTy;
4241 case LongDoubleRank: return LongDoubleComplexTy;
4242 }
Steve Naroff0af91202007-04-27 21:51:21 +00004243 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004244
4245 assert(Domain->isRealFloatingType() && "Unknown domain!");
4246 switch (EltRank) {
Joey Goulydd7f4562013-01-23 11:56:20 +00004247 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004248 case FloatRank: return FloatTy;
4249 case DoubleRank: return DoubleTy;
4250 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00004251 }
David Blaikief47fa302012-01-17 02:30:50 +00004252 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00004253}
4254
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004255/// getFloatingTypeOrder - Compare the rank of the two specified floating
4256/// point types, ignoring the domain of the type (i.e. 'double' ==
4257/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004258/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004259int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00004260 FloatingRank LHSR = getFloatingRank(LHS);
4261 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004262
Chris Lattnerb90739d2008-04-06 23:38:49 +00004263 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004264 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00004265 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004266 return 1;
4267 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00004268}
4269
Chris Lattner76a00cf2008-04-06 22:59:24 +00004270/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4271/// routine will assert if passed a built-in type that isn't an integer or enum,
4272/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00004273unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00004274 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004275
Chris Lattner76a00cf2008-04-06 22:59:24 +00004276 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004277 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004278 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004279 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004280 case BuiltinType::Char_S:
4281 case BuiltinType::Char_U:
4282 case BuiltinType::SChar:
4283 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004284 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004285 case BuiltinType::Short:
4286 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004287 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004288 case BuiltinType::Int:
4289 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004290 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004291 case BuiltinType::Long:
4292 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004293 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004294 case BuiltinType::LongLong:
4295 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004296 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00004297 case BuiltinType::Int128:
4298 case BuiltinType::UInt128:
4299 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00004300 }
4301}
4302
Eli Friedman629ffb92009-08-20 04:21:42 +00004303/// \brief Whether this is a promotable bitfield reference according
4304/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4305///
4306/// \returns the type this bit-field will promote to, or NULL if no
4307/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004308QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004309 if (E->isTypeDependent() || E->isValueDependent())
4310 return QualType();
4311
John McCalld25db7e2013-05-06 21:39:12 +00004312 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00004313 if (!Field)
4314 return QualType();
4315
4316 QualType FT = Field->getType();
4317
Richard Smithcaf33902011-10-10 18:28:20 +00004318 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004319 uint64_t IntSize = getTypeSize(IntTy);
4320 // GCC extension compatibility: if the bit-field size is less than or equal
4321 // to the size of int, it gets promoted no matter what its type is.
4322 // For instance, unsigned long bf : 4 gets promoted to signed int.
4323 if (BitWidth < IntSize)
4324 return IntTy;
4325
4326 if (BitWidth == IntSize)
4327 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4328
4329 // Types bigger than int are not subject to promotions, and therefore act
4330 // like the base type.
4331 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4332 // is ridiculous.
4333 return QualType();
4334}
4335
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004336/// getPromotedIntegerType - Returns the type that Promotable will
4337/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4338/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004339QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004340 assert(!Promotable.isNull());
4341 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004342 if (const EnumType *ET = Promotable->getAs<EnumType>())
4343 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004344
4345 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4346 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4347 // (3.9.1) can be converted to a prvalue of the first of the following
4348 // types that can represent all the values of its underlying type:
4349 // int, unsigned int, long int, unsigned long int, long long int, or
4350 // unsigned long long int [...]
4351 // FIXME: Is there some better way to compute this?
4352 if (BT->getKind() == BuiltinType::WChar_S ||
4353 BT->getKind() == BuiltinType::WChar_U ||
4354 BT->getKind() == BuiltinType::Char16 ||
4355 BT->getKind() == BuiltinType::Char32) {
4356 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4357 uint64_t FromSize = getTypeSize(BT);
4358 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4359 LongLongTy, UnsignedLongLongTy };
4360 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4361 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4362 if (FromSize < ToSize ||
4363 (FromSize == ToSize &&
4364 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4365 return PromoteTypes[Idx];
4366 }
4367 llvm_unreachable("char type should fit into long long");
4368 }
4369 }
4370
4371 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004372 if (Promotable->isSignedIntegerType())
4373 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00004374 uint64_t PromotableSize = getIntWidth(Promotable);
4375 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004376 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4377 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4378}
4379
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004380/// \brief Recurses in pointer/array types until it finds an objc retainable
4381/// type and returns its ownership.
4382Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4383 while (!T.isNull()) {
4384 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4385 return T.getObjCLifetime();
4386 if (T->isArrayType())
4387 T = getBaseElementType(T);
4388 else if (const PointerType *PT = T->getAs<PointerType>())
4389 T = PT->getPointeeType();
4390 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004391 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004392 else
4393 break;
4394 }
4395
4396 return Qualifiers::OCL_None;
4397}
4398
Mike Stump11289f42009-09-09 15:08:12 +00004399/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004400/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004401/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004402int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004403 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4404 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004405 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004406
Chris Lattner76a00cf2008-04-06 22:59:24 +00004407 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4408 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004409
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004410 unsigned LHSRank = getIntegerRank(LHSC);
4411 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004412
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004413 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4414 if (LHSRank == RHSRank) return 0;
4415 return LHSRank > RHSRank ? 1 : -1;
4416 }
Mike Stump11289f42009-09-09 15:08:12 +00004417
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004418 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4419 if (LHSUnsigned) {
4420 // If the unsigned [LHS] type is larger, return it.
4421 if (LHSRank >= RHSRank)
4422 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004423
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004424 // If the signed type can represent all values of the unsigned type, it
4425 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004426 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004427 return -1;
4428 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004429
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004430 // If the unsigned [RHS] type is larger, return it.
4431 if (RHSRank >= LHSRank)
4432 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004433
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004434 // If the signed type can represent all values of the unsigned type, it
4435 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004436 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004437 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004438}
Anders Carlsson98f07902007-08-17 05:31:46 +00004439
Anders Carlsson6d417272009-11-14 21:45:58 +00004440static RecordDecl *
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004441CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
4442 DeclContext *DC, IdentifierInfo *Id) {
4443 SourceLocation Loc;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004444 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004445 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00004446 else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004447 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00004448}
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004449
Mike Stump11289f42009-09-09 15:08:12 +00004450// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00004451QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004452 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00004453 CFConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004454 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004455 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00004456 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004457
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004458 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00004459
Anders Carlsson98f07902007-08-17 05:31:46 +00004460 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004461 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004462 // int flags;
4463 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00004464 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004465 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00004466 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004467 FieldTypes[3] = LongTy;
4468
Anders Carlsson98f07902007-08-17 05:31:46 +00004469 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004470 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00004471 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004472 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00004473 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00004474 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00004475 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004476 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004477 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004478 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004479 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004480 }
4481
Douglas Gregord5058122010-02-11 01:19:42 +00004482 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00004483 }
Mike Stump11289f42009-09-09 15:08:12 +00004484
Anders Carlsson98f07902007-08-17 05:31:46 +00004485 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00004486}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004487
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004488QualType ASTContext::getObjCSuperType() const {
4489 if (ObjCSuperType.isNull()) {
4490 RecordDecl *ObjCSuperTypeDecl =
4491 CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get("objc_super"));
4492 TUDecl->addDecl(ObjCSuperTypeDecl);
4493 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4494 }
4495 return ObjCSuperType;
4496}
4497
Douglas Gregor512b0772009-04-23 22:29:11 +00004498void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004499 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00004500 assert(Rec && "Invalid CFConstantStringType");
4501 CFConstantStringTypeDecl = Rec->getDecl();
4502}
4503
Jay Foad39c79802011-01-12 09:06:06 +00004504QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004505 if (BlockDescriptorType)
4506 return getTagDeclType(BlockDescriptorType);
4507
4508 RecordDecl *T;
4509 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004510 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004511 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00004512 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004513
4514 QualType FieldTypes[] = {
4515 UnsignedLongTy,
4516 UnsignedLongTy,
4517 };
4518
4519 const char *FieldNames[] = {
4520 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004521 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004522 };
4523
4524 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004525 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00004526 SourceLocation(),
4527 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004528 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00004529 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004530 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004531 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004532 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00004533 T->addDecl(Field);
4534 }
4535
Douglas Gregord5058122010-02-11 01:19:42 +00004536 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004537
4538 BlockDescriptorType = T;
4539
4540 return getTagDeclType(BlockDescriptorType);
4541}
4542
Jay Foad39c79802011-01-12 09:06:06 +00004543QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004544 if (BlockDescriptorExtendedType)
4545 return getTagDeclType(BlockDescriptorExtendedType);
4546
4547 RecordDecl *T;
4548 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004549 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004550 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00004551 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004552
4553 QualType FieldTypes[] = {
4554 UnsignedLongTy,
4555 UnsignedLongTy,
4556 getPointerType(VoidPtrTy),
4557 getPointerType(VoidPtrTy)
4558 };
4559
4560 const char *FieldNames[] = {
4561 "reserved",
4562 "Size",
4563 "CopyFuncPtr",
4564 "DestroyFuncPtr"
4565 };
4566
4567 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004568 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004569 SourceLocation(),
4570 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004571 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004572 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004573 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004574 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004575 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004576 T->addDecl(Field);
4577 }
4578
Douglas Gregord5058122010-02-11 01:19:42 +00004579 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004580
4581 BlockDescriptorExtendedType = T;
4582
4583 return getTagDeclType(BlockDescriptorExtendedType);
4584}
4585
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004586/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4587/// requires copy/dispose. Note that this must match the logic
4588/// in buildByrefHelpers.
4589bool ASTContext::BlockRequiresCopying(QualType Ty,
4590 const VarDecl *D) {
4591 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4592 const Expr *copyExpr = getBlockVarCopyInits(D);
4593 if (!copyExpr && record->hasTrivialDestructor()) return false;
4594
Mike Stump94967902009-10-21 18:16:27 +00004595 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004596 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004597
4598 if (!Ty->isObjCRetainableType()) return false;
4599
4600 Qualifiers qs = Ty.getQualifiers();
4601
4602 // If we have lifetime, that dominates.
4603 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4604 assert(getLangOpts().ObjCAutoRefCount);
4605
4606 switch (lifetime) {
4607 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4608
4609 // These are just bits as far as the runtime is concerned.
4610 case Qualifiers::OCL_ExplicitNone:
4611 case Qualifiers::OCL_Autoreleasing:
4612 return false;
4613
4614 // Tell the runtime that this is ARC __weak, called by the
4615 // byref routines.
4616 case Qualifiers::OCL_Weak:
4617 // ARC __strong __block variables need to be retained.
4618 case Qualifiers::OCL_Strong:
4619 return true;
4620 }
4621 llvm_unreachable("fell out of lifetime switch!");
4622 }
4623 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4624 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00004625}
4626
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004627bool ASTContext::getByrefLifetime(QualType Ty,
4628 Qualifiers::ObjCLifetime &LifeTime,
4629 bool &HasByrefExtendedLayout) const {
4630
4631 if (!getLangOpts().ObjC1 ||
4632 getLangOpts().getGC() != LangOptions::NonGC)
4633 return false;
4634
4635 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00004636 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004637 HasByrefExtendedLayout = true;
4638 LifeTime = Qualifiers::OCL_None;
4639 }
4640 else if (getLangOpts().ObjCAutoRefCount)
4641 LifeTime = Ty.getObjCLifetime();
4642 // MRR.
4643 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4644 LifeTime = Qualifiers::OCL_ExplicitNone;
4645 else
4646 LifeTime = Qualifiers::OCL_None;
4647 return true;
4648}
4649
Douglas Gregorbab8a962011-09-08 01:46:34 +00004650TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4651 if (!ObjCInstanceTypeDecl)
4652 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4653 getTranslationUnitDecl(),
4654 SourceLocation(),
4655 SourceLocation(),
4656 &Idents.get("instancetype"),
4657 getTrivialTypeSourceInfo(getObjCIdType()));
4658 return ObjCInstanceTypeDecl;
4659}
4660
Anders Carlsson18acd442007-10-29 06:33:42 +00004661// This returns true if a type has been typedefed to BOOL:
4662// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004663static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004664 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004665 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4666 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004667
Anders Carlssond8499822007-10-29 05:01:08 +00004668 return false;
4669}
4670
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004671/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004672/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004673CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004674 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4675 return CharUnits::Zero();
4676
Ken Dyck40775002010-01-11 17:06:35 +00004677 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004678
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004679 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004680 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004681 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004682 // Treat arrays as pointers, since that's how they're passed in.
4683 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004684 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004685 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004686}
4687
4688static inline
4689std::string charUnitsToString(const CharUnits &CU) {
4690 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004691}
4692
John McCall351762c2011-02-07 10:33:21 +00004693/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004694/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004695std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4696 std::string S;
4697
David Chisnall950a9512009-11-17 19:33:30 +00004698 const BlockDecl *Decl = Expr->getBlockDecl();
4699 QualType BlockTy =
4700 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4701 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004702 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004703 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None,
4704 BlockTy->getAs<FunctionType>()->getResultType(),
4705 S, true /*Extended*/);
4706 else
4707 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(),
4708 S);
David Chisnall950a9512009-11-17 19:33:30 +00004709 // Compute size of all parameters.
4710 // Start with computing size of a pointer in number of bytes.
4711 // FIXME: There might(should) be a better way of doing this computation!
4712 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004713 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4714 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00004715 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00004716 E = Decl->param_end(); PI != E; ++PI) {
4717 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004718 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00004719 if (sz.isZero())
4720 continue;
Ken Dyck40775002010-01-11 17:06:35 +00004721 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004722 ParmOffset += sz;
4723 }
4724 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004725 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004726 // Block pointer and offset.
4727 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004728
4729 // Argument types.
4730 ParmOffset = PtrSize;
4731 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4732 Decl->param_end(); PI != E; ++PI) {
4733 ParmVarDecl *PVDecl = *PI;
4734 QualType PType = PVDecl->getOriginalType();
4735 if (const ArrayType *AT =
4736 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4737 // Use array's original type only if it has known number of
4738 // elements.
4739 if (!isa<ConstantArrayType>(AT))
4740 PType = PVDecl->getType();
4741 } else if (PType->isFunctionType())
4742 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004743 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004744 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4745 S, true /*Extended*/);
4746 else
4747 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004748 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004749 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004750 }
John McCall351762c2011-02-07 10:33:21 +00004751
4752 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004753}
4754
Douglas Gregora9d84932011-05-27 01:19:52 +00004755bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004756 std::string& S) {
4757 // Encode result type.
4758 getObjCEncodingForType(Decl->getResultType(), S);
4759 CharUnits ParmOffset;
4760 // Compute size of all parameters.
4761 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4762 E = Decl->param_end(); PI != E; ++PI) {
4763 QualType PType = (*PI)->getType();
4764 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004765 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004766 continue;
4767
David Chisnall50e4eba2010-12-30 14:05:53 +00004768 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004769 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004770 ParmOffset += sz;
4771 }
4772 S += charUnitsToString(ParmOffset);
4773 ParmOffset = CharUnits::Zero();
4774
4775 // Argument types.
4776 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4777 E = Decl->param_end(); PI != E; ++PI) {
4778 ParmVarDecl *PVDecl = *PI;
4779 QualType PType = PVDecl->getOriginalType();
4780 if (const ArrayType *AT =
4781 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4782 // Use array's original type only if it has known number of
4783 // elements.
4784 if (!isa<ConstantArrayType>(AT))
4785 PType = PVDecl->getType();
4786 } else if (PType->isFunctionType())
4787 PType = PVDecl->getType();
4788 getObjCEncodingForType(PType, S);
4789 S += charUnitsToString(ParmOffset);
4790 ParmOffset += getObjCEncodingTypeSize(PType);
4791 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004792
4793 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004794}
4795
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004796/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4797/// method parameter or return type. If Extended, include class names and
4798/// block object types.
4799void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4800 QualType T, std::string& S,
4801 bool Extended) const {
4802 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4803 getObjCEncodingForTypeQualifier(QT, S);
4804 // Encode parameter type.
4805 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4806 true /*OutermostType*/,
4807 false /*EncodingProperty*/,
4808 false /*StructField*/,
4809 Extended /*EncodeBlockParameters*/,
4810 Extended /*EncodeClassNames*/);
4811}
4812
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004813/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004814/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004815bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004816 std::string& S,
4817 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004818 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004819 // Encode return type.
4820 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4821 Decl->getResultType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004822 // Compute size of all parameters.
4823 // Start with computing size of a pointer in number of bytes.
4824 // FIXME: There might(should) be a better way of doing this computation!
4825 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004826 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004827 // The first two arguments (self and _cmd) are pointers; account for
4828 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004829 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004830 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004831 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004832 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004833 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004834 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004835 continue;
4836
Ken Dyck40775002010-01-11 17:06:35 +00004837 assert (sz.isPositive() &&
4838 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004839 ParmOffset += sz;
4840 }
Ken Dyck40775002010-01-11 17:06:35 +00004841 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004842 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004843 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004844
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004845 // Argument types.
4846 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004847 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004848 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004849 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004850 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004851 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004852 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4853 // Use array's original type only if it has known number of
4854 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004855 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004856 PType = PVDecl->getType();
4857 } else if (PType->isFunctionType())
4858 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004859 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4860 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00004861 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004862 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004863 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004864
4865 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004866}
4867
Daniel Dunbar4932b362008-08-28 04:38:10 +00004868/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004869/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004870/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4871/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004872/// Property attributes are stored as a comma-delimited C string. The simple
4873/// attributes readonly and bycopy are encoded as single characters. The
4874/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4875/// encoded as single characters, followed by an identifier. Property types
4876/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004877/// these attributes are defined by the following enumeration:
4878/// @code
4879/// enum PropertyAttributes {
4880/// kPropertyReadOnly = 'R', // property is read-only.
4881/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4882/// kPropertyByref = '&', // property is a reference to the value last assigned
4883/// kPropertyDynamic = 'D', // property is dynamic
4884/// kPropertyGetter = 'G', // followed by getter selector name
4885/// kPropertySetter = 'S', // followed by setter selector name
4886/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00004887/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004888/// kPropertyWeak = 'W' // 'weak' property
4889/// kPropertyStrong = 'P' // property GC'able
4890/// kPropertyNonAtomic = 'N' // property non-atomic
4891/// };
4892/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00004893void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00004894 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00004895 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004896 // Collect information from the property implementation decl(s).
4897 bool Dynamic = false;
4898 ObjCPropertyImplDecl *SynthesizePID = 0;
4899
4900 // FIXME: Duplicated code due to poor abstraction.
4901 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00004902 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00004903 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4904 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004905 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004906 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004907 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004908 if (PID->getPropertyDecl() == PD) {
4909 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4910 Dynamic = true;
4911 } else {
4912 SynthesizePID = PID;
4913 }
4914 }
4915 }
4916 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00004917 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004918 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004919 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004920 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004921 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004922 if (PID->getPropertyDecl() == PD) {
4923 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4924 Dynamic = true;
4925 } else {
4926 SynthesizePID = PID;
4927 }
4928 }
Mike Stump11289f42009-09-09 15:08:12 +00004929 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00004930 }
4931 }
4932
4933 // FIXME: This is not very efficient.
4934 S = "T";
4935
4936 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004937 // GCC has some special rules regarding encoding of properties which
4938 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00004939 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004940 true /* outermost type */,
4941 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004942
4943 if (PD->isReadOnly()) {
4944 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00004945 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
4946 S += ",C";
4947 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
4948 S += ",&";
Daniel Dunbar4932b362008-08-28 04:38:10 +00004949 } else {
4950 switch (PD->getSetterKind()) {
4951 case ObjCPropertyDecl::Assign: break;
4952 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00004953 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00004954 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004955 }
4956 }
4957
4958 // It really isn't clear at all what this means, since properties
4959 // are "dynamic by default".
4960 if (Dynamic)
4961 S += ",D";
4962
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004963 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4964 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00004965
Daniel Dunbar4932b362008-08-28 04:38:10 +00004966 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4967 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00004968 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004969 }
4970
4971 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4972 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00004973 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004974 }
4975
4976 if (SynthesizePID) {
4977 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4978 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00004979 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004980 }
4981
4982 // FIXME: OBJCGC: weak & strong
4983}
4984
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004985/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00004986/// Another legacy compatibility encoding: 32-bit longs are encoded as
4987/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004988/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4989///
4990void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00004991 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00004992 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00004993 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004994 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00004995 else
Jay Foad39c79802011-01-12 09:06:06 +00004996 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004997 PointeeTy = IntTy;
4998 }
4999 }
5000}
5001
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005002void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00005003 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005004 // We follow the behavior of gcc, expanding structures which are
5005 // directly pointed to, and expanding embedded structures. Note that
5006 // these rules are sufficient to prevent recursive encoding of the
5007 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00005008 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00005009 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005010}
5011
John McCall393a78d2012-12-20 02:45:14 +00005012static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5013 BuiltinType::Kind kind) {
5014 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005015 case BuiltinType::Void: return 'v';
5016 case BuiltinType::Bool: return 'B';
5017 case BuiltinType::Char_U:
5018 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00005019 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00005020 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00005021 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00005022 case BuiltinType::UInt: return 'I';
5023 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00005024 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005025 case BuiltinType::UInt128: return 'T';
5026 case BuiltinType::ULongLong: return 'Q';
5027 case BuiltinType::Char_S:
5028 case BuiltinType::SChar: return 'c';
5029 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00005030 case BuiltinType::WChar_S:
5031 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00005032 case BuiltinType::Int: return 'i';
5033 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00005034 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005035 case BuiltinType::LongLong: return 'q';
5036 case BuiltinType::Int128: return 't';
5037 case BuiltinType::Float: return 'f';
5038 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00005039 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00005040 case BuiltinType::NullPtr: return '*'; // like char*
5041
5042 case BuiltinType::Half:
5043 // FIXME: potentially need @encodes for these!
5044 return ' ';
5045
5046 case BuiltinType::ObjCId:
5047 case BuiltinType::ObjCClass:
5048 case BuiltinType::ObjCSel:
5049 llvm_unreachable("@encoding ObjC primitive type");
5050
5051 // OpenCL and placeholder types don't need @encodings.
5052 case BuiltinType::OCLImage1d:
5053 case BuiltinType::OCLImage1dArray:
5054 case BuiltinType::OCLImage1dBuffer:
5055 case BuiltinType::OCLImage2d:
5056 case BuiltinType::OCLImage2dArray:
5057 case BuiltinType::OCLImage3d:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005058 case BuiltinType::OCLEvent:
Guy Benyei61054192013-02-07 10:55:47 +00005059 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00005060 case BuiltinType::Dependent:
5061#define BUILTIN_TYPE(KIND, ID)
5062#define PLACEHOLDER_TYPE(KIND, ID) \
5063 case BuiltinType::KIND:
5064#include "clang/AST/BuiltinTypes.def"
5065 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00005066 }
David Blaikie5a6a0202013-01-09 17:48:41 +00005067 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00005068}
5069
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005070static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5071 EnumDecl *Enum = ET->getDecl();
5072
5073 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5074 if (!Enum->isFixed())
5075 return 'i';
5076
5077 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00005078 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5079 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005080}
5081
Jay Foad39c79802011-01-12 09:06:06 +00005082static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00005083 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00005084 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005085 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00005086 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5087 // The GNU runtime requires more information; bitfields are encoded as b,
5088 // then the offset (in bits) of the first element, then the type of the
5089 // bitfield, then the size in bits. For example, in this structure:
5090 //
5091 // struct
5092 // {
5093 // int integer;
5094 // int flags:2;
5095 // };
5096 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5097 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5098 // information is not especially sensible, but we're stuck with it for
5099 // compatibility with GCC, although providing it breaks anything that
5100 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00005101 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005102 const RecordDecl *RD = FD->getParent();
5103 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00005104 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005105 if (const EnumType *ET = T->getAs<EnumType>())
5106 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00005107 else {
5108 const BuiltinType *BT = T->castAs<BuiltinType>();
5109 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5110 }
David Chisnallb190a2c2010-06-04 01:10:52 +00005111 }
Richard Smithcaf33902011-10-10 18:28:20 +00005112 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005113}
5114
Daniel Dunbar07d07852009-10-18 21:17:35 +00005115// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005116void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5117 bool ExpandPointedToStructures,
5118 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00005119 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005120 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005121 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005122 bool StructField,
5123 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005124 bool EncodeClassNames,
5125 bool EncodePointerToObjCTypedef) const {
John McCall393a78d2012-12-20 02:45:14 +00005126 CanQualType CT = getCanonicalType(T);
5127 switch (CT->getTypeClass()) {
5128 case Type::Builtin:
5129 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00005130 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00005131 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00005132 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5133 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5134 else
5135 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00005136 return;
Mike Stump11289f42009-09-09 15:08:12 +00005137
John McCall393a78d2012-12-20 02:45:14 +00005138 case Type::Complex: {
5139 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00005140 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00005141 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00005142 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005143 return;
5144 }
John McCall393a78d2012-12-20 02:45:14 +00005145
5146 case Type::Atomic: {
5147 const AtomicType *AT = T->castAs<AtomicType>();
5148 S += 'A';
5149 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, 0,
5150 false, false);
5151 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00005152 }
John McCall393a78d2012-12-20 02:45:14 +00005153
5154 // encoding for pointer or reference types.
5155 case Type::Pointer:
5156 case Type::LValueReference:
5157 case Type::RValueReference: {
5158 QualType PointeeTy;
5159 if (isa<PointerType>(CT)) {
5160 const PointerType *PT = T->castAs<PointerType>();
5161 if (PT->isObjCSelType()) {
5162 S += ':';
5163 return;
5164 }
5165 PointeeTy = PT->getPointeeType();
5166 } else {
5167 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5168 }
5169
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005170 bool isReadOnly = false;
5171 // For historical/compatibility reasons, the read-only qualifier of the
5172 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5173 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00005174 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00005175 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005176 if (OutermostType && T.isConstQualified()) {
5177 isReadOnly = true;
5178 S += 'r';
5179 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00005180 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005181 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005182 while (P->getAs<PointerType>())
5183 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005184 if (P.isConstQualified()) {
5185 isReadOnly = true;
5186 S += 'r';
5187 }
5188 }
5189 if (isReadOnly) {
5190 // Another legacy compatibility encoding. Some ObjC qualifier and type
5191 // combinations need to be rearranged.
5192 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005193 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00005194 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005195 }
Mike Stump11289f42009-09-09 15:08:12 +00005196
Anders Carlssond8499822007-10-29 05:01:08 +00005197 if (PointeeTy->isCharType()) {
5198 // char pointer types should be encoded as '*' unless it is a
5199 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00005200 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00005201 S += '*';
5202 return;
5203 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005204 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00005205 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5206 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5207 S += '#';
5208 return;
5209 }
5210 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5211 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5212 S += '@';
5213 return;
5214 }
5215 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00005216 }
Anders Carlssond8499822007-10-29 05:01:08 +00005217 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005218 getLegacyIntegralTypeEncoding(PointeeTy);
5219
Mike Stump11289f42009-09-09 15:08:12 +00005220 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005221 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005222 return;
5223 }
John McCall393a78d2012-12-20 02:45:14 +00005224
5225 case Type::ConstantArray:
5226 case Type::IncompleteArray:
5227 case Type::VariableArray: {
5228 const ArrayType *AT = cast<ArrayType>(CT);
5229
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005230 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005231 // Incomplete arrays are encoded as a pointer to the array element.
5232 S += '^';
5233
Mike Stump11289f42009-09-09 15:08:12 +00005234 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005235 false, ExpandStructures, FD);
5236 } else {
5237 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00005238
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005239 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
5240 if (getTypeSize(CAT->getElementType()) == 0)
5241 S += '0';
5242 else
5243 S += llvm::utostr(CAT->getSize().getZExtValue());
5244 } else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005245 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005246 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5247 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00005248 S += '0';
5249 }
Mike Stump11289f42009-09-09 15:08:12 +00005250
5251 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005252 false, ExpandStructures, FD);
5253 S += ']';
5254 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005255 return;
5256 }
Mike Stump11289f42009-09-09 15:08:12 +00005257
John McCall393a78d2012-12-20 02:45:14 +00005258 case Type::FunctionNoProto:
5259 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00005260 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005261 return;
Mike Stump11289f42009-09-09 15:08:12 +00005262
John McCall393a78d2012-12-20 02:45:14 +00005263 case Type::Record: {
5264 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005265 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00005266 // Anonymous structures print as '?'
5267 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5268 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005269 if (ClassTemplateSpecializationDecl *Spec
5270 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5271 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00005272 llvm::raw_string_ostream OS(S);
5273 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005274 TemplateArgs.data(),
5275 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00005276 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005277 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00005278 } else {
5279 S += '?';
5280 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00005281 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005282 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005283 if (!RDecl->isUnion()) {
5284 getObjCEncodingForStructureImpl(RDecl, S, FD);
5285 } else {
5286 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5287 FieldEnd = RDecl->field_end();
5288 Field != FieldEnd; ++Field) {
5289 if (FD) {
5290 S += '"';
5291 S += Field->getNameAsString();
5292 S += '"';
5293 }
Mike Stump11289f42009-09-09 15:08:12 +00005294
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005295 // Special case bit-fields.
5296 if (Field->isBitField()) {
5297 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie40ed2972012-06-06 20:45:41 +00005298 *Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005299 } else {
5300 QualType qt = Field->getType();
5301 getLegacyIntegralTypeEncoding(qt);
5302 getObjCEncodingForTypeImpl(qt, S, false, true,
5303 FD, /*OutermostType*/false,
5304 /*EncodingProperty*/false,
5305 /*StructField*/true);
5306 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005307 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005308 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00005309 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005310 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005311 return;
5312 }
Mike Stump11289f42009-09-09 15:08:12 +00005313
John McCall393a78d2012-12-20 02:45:14 +00005314 case Type::BlockPointer: {
5315 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00005316 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005317 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00005318 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005319
5320 S += '<';
5321 // Block return type
5322 getObjCEncodingForTypeImpl(FT->getResultType(), S,
5323 ExpandPointedToStructures, ExpandStructures,
5324 FD,
5325 false /* OutermostType */,
5326 EncodingProperty,
5327 false /* StructField */,
5328 EncodeBlockParameters,
5329 EncodeClassNames);
5330 // Block self
5331 S += "@?";
5332 // Block parameters
5333 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
5334 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
5335 E = FPT->arg_type_end(); I && (I != E); ++I) {
5336 getObjCEncodingForTypeImpl(*I, S,
5337 ExpandPointedToStructures,
5338 ExpandStructures,
5339 FD,
5340 false /* OutermostType */,
5341 EncodingProperty,
5342 false /* StructField */,
5343 EncodeBlockParameters,
5344 EncodeClassNames);
5345 }
5346 }
5347 S += '>';
5348 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005349 return;
5350 }
Mike Stump11289f42009-09-09 15:08:12 +00005351
John McCall393a78d2012-12-20 02:45:14 +00005352 case Type::ObjCObject:
5353 case Type::ObjCInterface: {
5354 // Ignore protocol qualifiers when mangling at this level.
5355 T = T->castAs<ObjCObjectType>()->getBaseType();
John McCall8b07ec22010-05-15 11:32:37 +00005356
John McCall393a78d2012-12-20 02:45:14 +00005357 // The assumption seems to be that this assert will succeed
5358 // because nested levels will have filtered out 'id' and 'Class'.
5359 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005360 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00005361 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005362 S += '{';
5363 const IdentifierInfo *II = OI->getIdentifier();
5364 S += II->getName();
5365 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005366 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005367 DeepCollectObjCIvars(OI, true, Ivars);
5368 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005369 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005370 if (Field->isBitField())
5371 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005372 else
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005373 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5374 false, false, false, false, false,
5375 EncodePointerToObjCTypedef);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005376 }
5377 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005378 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005379 }
Mike Stump11289f42009-09-09 15:08:12 +00005380
John McCall393a78d2012-12-20 02:45:14 +00005381 case Type::ObjCObjectPointer: {
5382 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005383 if (OPT->isObjCIdType()) {
5384 S += '@';
5385 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005386 }
Mike Stump11289f42009-09-09 15:08:12 +00005387
Steve Narofff0c86112009-10-28 22:03:49 +00005388 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5389 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5390 // Since this is a binary compatibility issue, need to consult with runtime
5391 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005392 S += '#';
5393 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005394 }
Mike Stump11289f42009-09-09 15:08:12 +00005395
Chris Lattnere7cabb92009-07-13 00:10:46 +00005396 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005397 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005398 ExpandPointedToStructures,
5399 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005400 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005401 // Note that we do extended encoding of protocol qualifer list
5402 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005403 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00005404 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5405 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005406 S += '<';
5407 S += (*I)->getNameAsString();
5408 S += '>';
5409 }
5410 S += '"';
5411 }
5412 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005413 }
Mike Stump11289f42009-09-09 15:08:12 +00005414
Chris Lattnere7cabb92009-07-13 00:10:46 +00005415 QualType PointeeTy = OPT->getPointeeType();
5416 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005417 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5418 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005419 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005420 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005421 // {...};
5422 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00005423 getObjCEncodingForTypeImpl(PointeeTy, S,
5424 false, ExpandPointedToStructures,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005425 NULL,
5426 false, false, false, false, false,
5427 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005428 return;
5429 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005430
5431 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005432 if (OPT->getInterfaceDecl() &&
5433 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005434 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00005435 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00005436 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5437 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005438 S += '<';
5439 S += (*I)->getNameAsString();
5440 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005441 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005442 S += '"';
5443 }
5444 return;
5445 }
Mike Stump11289f42009-09-09 15:08:12 +00005446
John McCalla9e6e8d2010-05-17 23:56:34 +00005447 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00005448 // FIXME: we shoul do better than that. 'M' is available.
5449 case Type::MemberPointer:
John McCalla9e6e8d2010-05-17 23:56:34 +00005450 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005451
John McCall393a78d2012-12-20 02:45:14 +00005452 case Type::Vector:
5453 case Type::ExtVector:
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005454 // This matches gcc's encoding, even though technically it is
5455 // insufficient.
5456 // FIXME. We should do a better job than gcc.
5457 return;
John McCall393a78d2012-12-20 02:45:14 +00005458
Richard Smith27d807c2013-04-30 13:56:41 +00005459 case Type::Auto:
5460 // We could see an undeduced auto type here during error recovery.
5461 // Just ignore it.
5462 return;
5463
John McCall393a78d2012-12-20 02:45:14 +00005464#define ABSTRACT_TYPE(KIND, BASE)
5465#define TYPE(KIND, BASE)
5466#define DEPENDENT_TYPE(KIND, BASE) \
5467 case Type::KIND:
5468#define NON_CANONICAL_TYPE(KIND, BASE) \
5469 case Type::KIND:
5470#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5471 case Type::KIND:
5472#include "clang/AST/TypeNodes.def"
5473 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005474 }
John McCall393a78d2012-12-20 02:45:14 +00005475 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00005476}
5477
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005478void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5479 std::string &S,
5480 const FieldDecl *FD,
5481 bool includeVBases) const {
5482 assert(RDecl && "Expected non-null RecordDecl");
5483 assert(!RDecl->isUnion() && "Should not be called for unions");
5484 if (!RDecl->getDefinition())
5485 return;
5486
5487 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5488 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5489 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5490
5491 if (CXXRec) {
5492 for (CXXRecordDecl::base_class_iterator
5493 BI = CXXRec->bases_begin(),
5494 BE = CXXRec->bases_end(); BI != BE; ++BI) {
5495 if (!BI->isVirtual()) {
5496 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005497 if (base->isEmpty())
5498 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005499 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005500 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5501 std::make_pair(offs, base));
5502 }
5503 }
5504 }
5505
5506 unsigned i = 0;
5507 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5508 FieldEnd = RDecl->field_end();
5509 Field != FieldEnd; ++Field, ++i) {
5510 uint64_t offs = layout.getFieldOffset(i);
5511 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie40ed2972012-06-06 20:45:41 +00005512 std::make_pair(offs, *Field));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005513 }
5514
5515 if (CXXRec && includeVBases) {
5516 for (CXXRecordDecl::base_class_iterator
5517 BI = CXXRec->vbases_begin(),
5518 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
5519 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005520 if (base->isEmpty())
5521 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005522 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00005523 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
5524 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5525 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005526 }
5527 }
5528
5529 CharUnits size;
5530 if (CXXRec) {
5531 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5532 } else {
5533 size = layout.getSize();
5534 }
5535
5536 uint64_t CurOffs = 0;
5537 std::multimap<uint64_t, NamedDecl *>::iterator
5538 CurLayObj = FieldOrBaseOffsets.begin();
5539
Douglas Gregorf5d6c742012-04-27 22:30:01 +00005540 if (CXXRec && CXXRec->isDynamicClass() &&
5541 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005542 if (FD) {
5543 S += "\"_vptr$";
5544 std::string recname = CXXRec->getNameAsString();
5545 if (recname.empty()) recname = "?";
5546 S += recname;
5547 S += '"';
5548 }
5549 S += "^^?";
5550 CurOffs += getTypeSize(VoidPtrTy);
5551 }
5552
5553 if (!RDecl->hasFlexibleArrayMember()) {
5554 // Mark the end of the structure.
5555 uint64_t offs = toBits(size);
5556 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5557 std::make_pair(offs, (NamedDecl*)0));
5558 }
5559
5560 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5561 assert(CurOffs <= CurLayObj->first);
5562
5563 if (CurOffs < CurLayObj->first) {
5564 uint64_t padding = CurLayObj->first - CurOffs;
5565 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5566 // packing/alignment of members is different that normal, in which case
5567 // the encoding will be out-of-sync with the real layout.
5568 // If the runtime switches to just consider the size of types without
5569 // taking into account alignment, we could make padding explicit in the
5570 // encoding (e.g. using arrays of chars). The encoding strings would be
5571 // longer then though.
5572 CurOffs += padding;
5573 }
5574
5575 NamedDecl *dcl = CurLayObj->second;
5576 if (dcl == 0)
5577 break; // reached end of structure.
5578
5579 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5580 // We expand the bases without their virtual bases since those are going
5581 // in the initial structure. Note that this differs from gcc which
5582 // expands virtual bases each time one is encountered in the hierarchy,
5583 // making the encoding type bigger than it really is.
5584 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005585 assert(!base->isEmpty());
5586 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005587 } else {
5588 FieldDecl *field = cast<FieldDecl>(dcl);
5589 if (FD) {
5590 S += '"';
5591 S += field->getNameAsString();
5592 S += '"';
5593 }
5594
5595 if (field->isBitField()) {
5596 EncodeBitField(this, S, field->getType(), field);
Richard Smithcaf33902011-10-10 18:28:20 +00005597 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005598 } else {
5599 QualType qt = field->getType();
5600 getLegacyIntegralTypeEncoding(qt);
5601 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5602 /*OutermostType*/false,
5603 /*EncodingProperty*/false,
5604 /*StructField*/true);
5605 CurOffs += getTypeSize(field->getType());
5606 }
5607 }
5608 }
5609}
5610
Mike Stump11289f42009-09-09 15:08:12 +00005611void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005612 std::string& S) const {
5613 if (QT & Decl::OBJC_TQ_In)
5614 S += 'n';
5615 if (QT & Decl::OBJC_TQ_Inout)
5616 S += 'N';
5617 if (QT & Decl::OBJC_TQ_Out)
5618 S += 'o';
5619 if (QT & Decl::OBJC_TQ_Bycopy)
5620 S += 'O';
5621 if (QT & Decl::OBJC_TQ_Byref)
5622 S += 'R';
5623 if (QT & Decl::OBJC_TQ_Oneway)
5624 S += 'V';
5625}
5626
Douglas Gregor3ea72692011-08-12 05:46:01 +00005627TypedefDecl *ASTContext::getObjCIdDecl() const {
5628 if (!ObjCIdDecl) {
5629 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5630 T = getObjCObjectPointerType(T);
5631 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
5632 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5633 getTranslationUnitDecl(),
5634 SourceLocation(), SourceLocation(),
5635 &Idents.get("id"), IdInfo);
5636 }
5637
5638 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00005639}
5640
Douglas Gregor52e02802011-08-12 06:17:30 +00005641TypedefDecl *ASTContext::getObjCSelDecl() const {
5642 if (!ObjCSelDecl) {
5643 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5644 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5645 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5646 getTranslationUnitDecl(),
5647 SourceLocation(), SourceLocation(),
5648 &Idents.get("SEL"), SelInfo);
5649 }
5650 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00005651}
5652
Douglas Gregor0a586182011-08-12 05:59:41 +00005653TypedefDecl *ASTContext::getObjCClassDecl() const {
5654 if (!ObjCClassDecl) {
5655 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5656 T = getObjCObjectPointerType(T);
5657 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5658 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5659 getTranslationUnitDecl(),
5660 SourceLocation(), SourceLocation(),
5661 &Idents.get("Class"), ClassInfo);
5662 }
5663
5664 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00005665}
5666
Douglas Gregord53ae832012-01-17 18:09:05 +00005667ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5668 if (!ObjCProtocolClassDecl) {
5669 ObjCProtocolClassDecl
5670 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5671 SourceLocation(),
5672 &Idents.get("Protocol"),
5673 /*PrevDecl=*/0,
5674 SourceLocation(), true);
5675 }
5676
5677 return ObjCProtocolClassDecl;
5678}
5679
Meador Inge5d3fb222012-06-16 03:34:49 +00005680//===----------------------------------------------------------------------===//
5681// __builtin_va_list Construction Functions
5682//===----------------------------------------------------------------------===//
5683
5684static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5685 // typedef char* __builtin_va_list;
5686 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5687 TypeSourceInfo *TInfo
5688 = Context->getTrivialTypeSourceInfo(CharPtrType);
5689
5690 TypedefDecl *VaListTypeDecl
5691 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5692 Context->getTranslationUnitDecl(),
5693 SourceLocation(), SourceLocation(),
5694 &Context->Idents.get("__builtin_va_list"),
5695 TInfo);
5696 return VaListTypeDecl;
5697}
5698
5699static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5700 // typedef void* __builtin_va_list;
5701 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5702 TypeSourceInfo *TInfo
5703 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5704
5705 TypedefDecl *VaListTypeDecl
5706 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5707 Context->getTranslationUnitDecl(),
5708 SourceLocation(), SourceLocation(),
5709 &Context->Idents.get("__builtin_va_list"),
5710 TInfo);
5711 return VaListTypeDecl;
5712}
5713
Tim Northover9bb857a2013-01-31 12:13:10 +00005714static TypedefDecl *
5715CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
5716 RecordDecl *VaListTagDecl;
5717 if (Context->getLangOpts().CPlusPlus) {
5718 // namespace std { struct __va_list {
5719 NamespaceDecl *NS;
5720 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5721 Context->getTranslationUnitDecl(),
5722 /*Inline*/false, SourceLocation(),
5723 SourceLocation(), &Context->Idents.get("std"),
5724 /*PrevDecl*/0);
5725
5726 VaListTagDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5727 Context->getTranslationUnitDecl(),
5728 SourceLocation(), SourceLocation(),
5729 &Context->Idents.get("__va_list"));
5730 VaListTagDecl->setDeclContext(NS);
5731 } else {
5732 // struct __va_list
5733 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5734 Context->getTranslationUnitDecl(),
5735 &Context->Idents.get("__va_list"));
5736 }
5737
5738 VaListTagDecl->startDefinition();
5739
5740 const size_t NumFields = 5;
5741 QualType FieldTypes[NumFields];
5742 const char *FieldNames[NumFields];
5743
5744 // void *__stack;
5745 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
5746 FieldNames[0] = "__stack";
5747
5748 // void *__gr_top;
5749 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
5750 FieldNames[1] = "__gr_top";
5751
5752 // void *__vr_top;
5753 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5754 FieldNames[2] = "__vr_top";
5755
5756 // int __gr_offs;
5757 FieldTypes[3] = Context->IntTy;
5758 FieldNames[3] = "__gr_offs";
5759
5760 // int __vr_offs;
5761 FieldTypes[4] = Context->IntTy;
5762 FieldNames[4] = "__vr_offs";
5763
5764 // Create fields
5765 for (unsigned i = 0; i < NumFields; ++i) {
5766 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5767 VaListTagDecl,
5768 SourceLocation(),
5769 SourceLocation(),
5770 &Context->Idents.get(FieldNames[i]),
5771 FieldTypes[i], /*TInfo=*/0,
5772 /*BitWidth=*/0,
5773 /*Mutable=*/false,
5774 ICIS_NoInit);
5775 Field->setAccess(AS_public);
5776 VaListTagDecl->addDecl(Field);
5777 }
5778 VaListTagDecl->completeDefinition();
5779 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5780 Context->VaListTagTy = VaListTagType;
5781
5782 // } __builtin_va_list;
5783 TypedefDecl *VaListTypedefDecl
5784 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5785 Context->getTranslationUnitDecl(),
5786 SourceLocation(), SourceLocation(),
5787 &Context->Idents.get("__builtin_va_list"),
5788 Context->getTrivialTypeSourceInfo(VaListTagType));
5789
5790 return VaListTypedefDecl;
5791}
5792
Meador Inge5d3fb222012-06-16 03:34:49 +00005793static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5794 // typedef struct __va_list_tag {
5795 RecordDecl *VaListTagDecl;
5796
5797 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5798 Context->getTranslationUnitDecl(),
5799 &Context->Idents.get("__va_list_tag"));
5800 VaListTagDecl->startDefinition();
5801
5802 const size_t NumFields = 5;
5803 QualType FieldTypes[NumFields];
5804 const char *FieldNames[NumFields];
5805
5806 // unsigned char gpr;
5807 FieldTypes[0] = Context->UnsignedCharTy;
5808 FieldNames[0] = "gpr";
5809
5810 // unsigned char fpr;
5811 FieldTypes[1] = Context->UnsignedCharTy;
5812 FieldNames[1] = "fpr";
5813
5814 // unsigned short reserved;
5815 FieldTypes[2] = Context->UnsignedShortTy;
5816 FieldNames[2] = "reserved";
5817
5818 // void* overflow_arg_area;
5819 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5820 FieldNames[3] = "overflow_arg_area";
5821
5822 // void* reg_save_area;
5823 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5824 FieldNames[4] = "reg_save_area";
5825
5826 // Create fields
5827 for (unsigned i = 0; i < NumFields; ++i) {
5828 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5829 SourceLocation(),
5830 SourceLocation(),
5831 &Context->Idents.get(FieldNames[i]),
5832 FieldTypes[i], /*TInfo=*/0,
5833 /*BitWidth=*/0,
5834 /*Mutable=*/false,
5835 ICIS_NoInit);
5836 Field->setAccess(AS_public);
5837 VaListTagDecl->addDecl(Field);
5838 }
5839 VaListTagDecl->completeDefinition();
5840 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005841 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005842
5843 // } __va_list_tag;
5844 TypedefDecl *VaListTagTypedefDecl
5845 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5846 Context->getTranslationUnitDecl(),
5847 SourceLocation(), SourceLocation(),
5848 &Context->Idents.get("__va_list_tag"),
5849 Context->getTrivialTypeSourceInfo(VaListTagType));
5850 QualType VaListTagTypedefType =
5851 Context->getTypedefType(VaListTagTypedefDecl);
5852
5853 // typedef __va_list_tag __builtin_va_list[1];
5854 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5855 QualType VaListTagArrayType
5856 = Context->getConstantArrayType(VaListTagTypedefType,
5857 Size, ArrayType::Normal, 0);
5858 TypeSourceInfo *TInfo
5859 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5860 TypedefDecl *VaListTypedefDecl
5861 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5862 Context->getTranslationUnitDecl(),
5863 SourceLocation(), SourceLocation(),
5864 &Context->Idents.get("__builtin_va_list"),
5865 TInfo);
5866
5867 return VaListTypedefDecl;
5868}
5869
5870static TypedefDecl *
5871CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5872 // typedef struct __va_list_tag {
5873 RecordDecl *VaListTagDecl;
5874 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5875 Context->getTranslationUnitDecl(),
5876 &Context->Idents.get("__va_list_tag"));
5877 VaListTagDecl->startDefinition();
5878
5879 const size_t NumFields = 4;
5880 QualType FieldTypes[NumFields];
5881 const char *FieldNames[NumFields];
5882
5883 // unsigned gp_offset;
5884 FieldTypes[0] = Context->UnsignedIntTy;
5885 FieldNames[0] = "gp_offset";
5886
5887 // unsigned fp_offset;
5888 FieldTypes[1] = Context->UnsignedIntTy;
5889 FieldNames[1] = "fp_offset";
5890
5891 // void* overflow_arg_area;
5892 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5893 FieldNames[2] = "overflow_arg_area";
5894
5895 // void* reg_save_area;
5896 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5897 FieldNames[3] = "reg_save_area";
5898
5899 // Create fields
5900 for (unsigned i = 0; i < NumFields; ++i) {
5901 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5902 VaListTagDecl,
5903 SourceLocation(),
5904 SourceLocation(),
5905 &Context->Idents.get(FieldNames[i]),
5906 FieldTypes[i], /*TInfo=*/0,
5907 /*BitWidth=*/0,
5908 /*Mutable=*/false,
5909 ICIS_NoInit);
5910 Field->setAccess(AS_public);
5911 VaListTagDecl->addDecl(Field);
5912 }
5913 VaListTagDecl->completeDefinition();
5914 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005915 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005916
5917 // } __va_list_tag;
5918 TypedefDecl *VaListTagTypedefDecl
5919 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5920 Context->getTranslationUnitDecl(),
5921 SourceLocation(), SourceLocation(),
5922 &Context->Idents.get("__va_list_tag"),
5923 Context->getTrivialTypeSourceInfo(VaListTagType));
5924 QualType VaListTagTypedefType =
5925 Context->getTypedefType(VaListTagTypedefDecl);
5926
5927 // typedef __va_list_tag __builtin_va_list[1];
5928 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5929 QualType VaListTagArrayType
5930 = Context->getConstantArrayType(VaListTagTypedefType,
5931 Size, ArrayType::Normal,0);
5932 TypeSourceInfo *TInfo
5933 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5934 TypedefDecl *VaListTypedefDecl
5935 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5936 Context->getTranslationUnitDecl(),
5937 SourceLocation(), SourceLocation(),
5938 &Context->Idents.get("__builtin_va_list"),
5939 TInfo);
5940
5941 return VaListTypedefDecl;
5942}
5943
5944static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5945 // typedef int __builtin_va_list[4];
5946 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5947 QualType IntArrayType
5948 = Context->getConstantArrayType(Context->IntTy,
5949 Size, ArrayType::Normal, 0);
5950 TypedefDecl *VaListTypedefDecl
5951 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5952 Context->getTranslationUnitDecl(),
5953 SourceLocation(), SourceLocation(),
5954 &Context->Idents.get("__builtin_va_list"),
5955 Context->getTrivialTypeSourceInfo(IntArrayType));
5956
5957 return VaListTypedefDecl;
5958}
5959
Logan Chien57086ce2012-10-10 06:56:20 +00005960static TypedefDecl *
5961CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
5962 RecordDecl *VaListDecl;
5963 if (Context->getLangOpts().CPlusPlus) {
5964 // namespace std { struct __va_list {
5965 NamespaceDecl *NS;
5966 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5967 Context->getTranslationUnitDecl(),
5968 /*Inline*/false, SourceLocation(),
5969 SourceLocation(), &Context->Idents.get("std"),
5970 /*PrevDecl*/0);
5971
5972 VaListDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5973 Context->getTranslationUnitDecl(),
5974 SourceLocation(), SourceLocation(),
5975 &Context->Idents.get("__va_list"));
5976
5977 VaListDecl->setDeclContext(NS);
5978
5979 } else {
5980 // struct __va_list {
5981 VaListDecl = CreateRecordDecl(*Context, TTK_Struct,
5982 Context->getTranslationUnitDecl(),
5983 &Context->Idents.get("__va_list"));
5984 }
5985
5986 VaListDecl->startDefinition();
5987
5988 // void * __ap;
5989 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5990 VaListDecl,
5991 SourceLocation(),
5992 SourceLocation(),
5993 &Context->Idents.get("__ap"),
5994 Context->getPointerType(Context->VoidTy),
5995 /*TInfo=*/0,
5996 /*BitWidth=*/0,
5997 /*Mutable=*/false,
5998 ICIS_NoInit);
5999 Field->setAccess(AS_public);
6000 VaListDecl->addDecl(Field);
6001
6002 // };
6003 VaListDecl->completeDefinition();
6004
6005 // typedef struct __va_list __builtin_va_list;
6006 TypeSourceInfo *TInfo
6007 = Context->getTrivialTypeSourceInfo(Context->getRecordType(VaListDecl));
6008
6009 TypedefDecl *VaListTypeDecl
6010 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6011 Context->getTranslationUnitDecl(),
6012 SourceLocation(), SourceLocation(),
6013 &Context->Idents.get("__builtin_va_list"),
6014 TInfo);
6015
6016 return VaListTypeDecl;
6017}
6018
Ulrich Weigand47445072013-05-06 16:26:41 +00006019static TypedefDecl *
6020CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
6021 // typedef struct __va_list_tag {
6022 RecordDecl *VaListTagDecl;
6023 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
6024 Context->getTranslationUnitDecl(),
6025 &Context->Idents.get("__va_list_tag"));
6026 VaListTagDecl->startDefinition();
6027
6028 const size_t NumFields = 4;
6029 QualType FieldTypes[NumFields];
6030 const char *FieldNames[NumFields];
6031
6032 // long __gpr;
6033 FieldTypes[0] = Context->LongTy;
6034 FieldNames[0] = "__gpr";
6035
6036 // long __fpr;
6037 FieldTypes[1] = Context->LongTy;
6038 FieldNames[1] = "__fpr";
6039
6040 // void *__overflow_arg_area;
6041 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6042 FieldNames[2] = "__overflow_arg_area";
6043
6044 // void *__reg_save_area;
6045 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6046 FieldNames[3] = "__reg_save_area";
6047
6048 // Create fields
6049 for (unsigned i = 0; i < NumFields; ++i) {
6050 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6051 VaListTagDecl,
6052 SourceLocation(),
6053 SourceLocation(),
6054 &Context->Idents.get(FieldNames[i]),
6055 FieldTypes[i], /*TInfo=*/0,
6056 /*BitWidth=*/0,
6057 /*Mutable=*/false,
6058 ICIS_NoInit);
6059 Field->setAccess(AS_public);
6060 VaListTagDecl->addDecl(Field);
6061 }
6062 VaListTagDecl->completeDefinition();
6063 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6064 Context->VaListTagTy = VaListTagType;
6065
6066 // } __va_list_tag;
6067 TypedefDecl *VaListTagTypedefDecl
6068 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6069 Context->getTranslationUnitDecl(),
6070 SourceLocation(), SourceLocation(),
6071 &Context->Idents.get("__va_list_tag"),
6072 Context->getTrivialTypeSourceInfo(VaListTagType));
6073 QualType VaListTagTypedefType =
6074 Context->getTypedefType(VaListTagTypedefDecl);
6075
6076 // typedef __va_list_tag __builtin_va_list[1];
6077 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6078 QualType VaListTagArrayType
6079 = Context->getConstantArrayType(VaListTagTypedefType,
6080 Size, ArrayType::Normal,0);
6081 TypeSourceInfo *TInfo
6082 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
6083 TypedefDecl *VaListTypedefDecl
6084 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6085 Context->getTranslationUnitDecl(),
6086 SourceLocation(), SourceLocation(),
6087 &Context->Idents.get("__builtin_va_list"),
6088 TInfo);
6089
6090 return VaListTypedefDecl;
6091}
6092
Meador Inge5d3fb222012-06-16 03:34:49 +00006093static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6094 TargetInfo::BuiltinVaListKind Kind) {
6095 switch (Kind) {
6096 case TargetInfo::CharPtrBuiltinVaList:
6097 return CreateCharPtrBuiltinVaListDecl(Context);
6098 case TargetInfo::VoidPtrBuiltinVaList:
6099 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00006100 case TargetInfo::AArch64ABIBuiltinVaList:
6101 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006102 case TargetInfo::PowerABIBuiltinVaList:
6103 return CreatePowerABIBuiltinVaListDecl(Context);
6104 case TargetInfo::X86_64ABIBuiltinVaList:
6105 return CreateX86_64ABIBuiltinVaListDecl(Context);
6106 case TargetInfo::PNaClABIBuiltinVaList:
6107 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00006108 case TargetInfo::AAPCSABIBuiltinVaList:
6109 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00006110 case TargetInfo::SystemZBuiltinVaList:
6111 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006112 }
6113
6114 llvm_unreachable("Unhandled __builtin_va_list type kind");
6115}
6116
6117TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
6118 if (!BuiltinVaListDecl)
6119 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
6120
6121 return BuiltinVaListDecl;
6122}
6123
Meador Ingecfb60902012-07-01 15:57:25 +00006124QualType ASTContext::getVaListTagType() const {
6125 // Force the creation of VaListTagTy by building the __builtin_va_list
6126 // declaration.
6127 if (VaListTagTy.isNull())
6128 (void) getBuiltinVaListDecl();
6129
6130 return VaListTagTy;
6131}
6132
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006133void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00006134 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00006135 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00006136
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006137 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00006138}
6139
John McCalld28ae272009-12-02 08:04:21 +00006140/// \brief Retrieve the template name that corresponds to a non-empty
6141/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00006142TemplateName
6143ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6144 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00006145 unsigned size = End - Begin;
6146 assert(size > 1 && "set is not overloaded!");
6147
6148 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6149 size * sizeof(FunctionTemplateDecl*));
6150 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6151
6152 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00006153 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00006154 NamedDecl *D = *I;
6155 assert(isa<FunctionTemplateDecl>(D) ||
6156 (isa<UsingShadowDecl>(D) &&
6157 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6158 *Storage++ = D;
6159 }
6160
6161 return TemplateName(OT);
6162}
6163
Douglas Gregordc572a32009-03-30 22:58:21 +00006164/// \brief Retrieve the template name that represents a qualified
6165/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00006166TemplateName
6167ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6168 bool TemplateKeyword,
6169 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00006170 assert(NNS && "Missing nested-name-specifier in qualified template name");
6171
Douglas Gregorc42075a2010-02-04 18:10:26 +00006172 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00006173 llvm::FoldingSetNodeID ID;
6174 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6175
6176 void *InsertPos = 0;
6177 QualifiedTemplateName *QTN =
6178 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6179 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00006180 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6181 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00006182 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6183 }
6184
6185 return TemplateName(QTN);
6186}
6187
6188/// \brief Retrieve the template name that represents a dependent
6189/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00006190TemplateName
6191ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6192 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00006193 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00006194 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00006195
6196 llvm::FoldingSetNodeID ID;
6197 DependentTemplateName::Profile(ID, NNS, Name);
6198
6199 void *InsertPos = 0;
6200 DependentTemplateName *QTN =
6201 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6202
6203 if (QTN)
6204 return TemplateName(QTN);
6205
6206 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6207 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006208 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6209 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00006210 } else {
6211 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00006212 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6213 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006214 DependentTemplateName *CheckQTN =
6215 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6216 assert(!CheckQTN && "Dependent type name canonicalization broken");
6217 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00006218 }
6219
6220 DependentTemplateNames.InsertNode(QTN, InsertPos);
6221 return TemplateName(QTN);
6222}
6223
Douglas Gregor71395fa2009-11-04 00:56:37 +00006224/// \brief Retrieve the template name that represents a dependent
6225/// template name such as \c MetaFun::template operator+.
6226TemplateName
6227ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00006228 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00006229 assert((!NNS || NNS->isDependent()) &&
6230 "Nested name specifier must be dependent");
6231
6232 llvm::FoldingSetNodeID ID;
6233 DependentTemplateName::Profile(ID, NNS, Operator);
6234
6235 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00006236 DependentTemplateName *QTN
6237 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006238
6239 if (QTN)
6240 return TemplateName(QTN);
6241
6242 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6243 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006244 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6245 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006246 } else {
6247 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00006248 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6249 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006250
6251 DependentTemplateName *CheckQTN
6252 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6253 assert(!CheckQTN && "Dependent template name canonicalization broken");
6254 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00006255 }
6256
6257 DependentTemplateNames.InsertNode(QTN, InsertPos);
6258 return TemplateName(QTN);
6259}
6260
Douglas Gregor5590be02011-01-15 06:45:20 +00006261TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00006262ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6263 TemplateName replacement) const {
6264 llvm::FoldingSetNodeID ID;
6265 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
6266
6267 void *insertPos = 0;
6268 SubstTemplateTemplateParmStorage *subst
6269 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6270
6271 if (!subst) {
6272 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6273 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6274 }
6275
6276 return TemplateName(subst);
6277}
6278
6279TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00006280ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6281 const TemplateArgument &ArgPack) const {
6282 ASTContext &Self = const_cast<ASTContext &>(*this);
6283 llvm::FoldingSetNodeID ID;
6284 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
6285
6286 void *InsertPos = 0;
6287 SubstTemplateTemplateParmPackStorage *Subst
6288 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6289
6290 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00006291 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00006292 ArgPack.pack_size(),
6293 ArgPack.pack_begin());
6294 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6295 }
6296
6297 return TemplateName(Subst);
6298}
6299
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006300/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00006301/// TargetInfo, produce the corresponding type. The unsigned @p Type
6302/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00006303CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006304 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00006305 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006306 case TargetInfo::SignedShort: return ShortTy;
6307 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6308 case TargetInfo::SignedInt: return IntTy;
6309 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6310 case TargetInfo::SignedLong: return LongTy;
6311 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6312 case TargetInfo::SignedLongLong: return LongLongTy;
6313 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6314 }
6315
David Blaikie83d382b2011-09-23 05:06:16 +00006316 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006317}
Ted Kremenek77c51b22008-07-24 23:58:27 +00006318
6319//===----------------------------------------------------------------------===//
6320// Type Predicates.
6321//===----------------------------------------------------------------------===//
6322
Fariborz Jahanian96207692009-02-18 21:49:28 +00006323/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6324/// garbage collection attribute.
6325///
John McCall553d45a2011-01-12 00:34:59 +00006326Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006327 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00006328 return Qualifiers::GCNone;
6329
David Blaikiebbafb8a2012-03-11 07:00:24 +00006330 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00006331 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6332
6333 // Default behaviour under objective-C's gc is for ObjC pointers
6334 // (or pointers to them) be treated as though they were declared
6335 // as __strong.
6336 if (GCAttrs == Qualifiers::GCNone) {
6337 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6338 return Qualifiers::Strong;
6339 else if (Ty->isPointerType())
6340 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6341 } else {
6342 // It's not valid to set GC attributes on anything that isn't a
6343 // pointer.
6344#ifndef NDEBUG
6345 QualType CT = Ty->getCanonicalTypeInternal();
6346 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6347 CT = AT->getElementType();
6348 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6349#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00006350 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00006351 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00006352}
6353
Chris Lattner49af6a42008-04-07 06:51:04 +00006354//===----------------------------------------------------------------------===//
6355// Type Compatibility Testing
6356//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00006357
Mike Stump11289f42009-09-09 15:08:12 +00006358/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006359/// compatible.
6360static bool areCompatVectorTypes(const VectorType *LHS,
6361 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00006362 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00006363 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00006364 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00006365}
6366
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006367bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6368 QualType SecondVec) {
6369 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6370 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6371
6372 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6373 return true;
6374
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006375 // Treat Neon vector types and most AltiVec vector types as if they are the
6376 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006377 const VectorType *First = FirstVec->getAs<VectorType>();
6378 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006379 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006380 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006381 First->getVectorKind() != VectorType::AltiVecPixel &&
6382 First->getVectorKind() != VectorType::AltiVecBool &&
6383 Second->getVectorKind() != VectorType::AltiVecPixel &&
6384 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006385 return true;
6386
6387 return false;
6388}
6389
Steve Naroff8e6aee52009-07-23 01:01:38 +00006390//===----------------------------------------------------------------------===//
6391// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6392//===----------------------------------------------------------------------===//
6393
6394/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6395/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00006396bool
6397ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6398 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00006399 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006400 return true;
6401 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
6402 E = rProto->protocol_end(); PI != E; ++PI)
6403 if (ProtocolCompatibleWithProtocol(lProto, *PI))
6404 return true;
6405 return false;
6406}
6407
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006408/// QualifiedIdConformsQualifiedId - compare id<pr,...> with id<pr1,...>
Steve Naroff8e6aee52009-07-23 01:01:38 +00006409/// return true if lhs's protocols conform to rhs's protocol; false
6410/// otherwise.
6411bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
6412 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
6413 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
6414 return false;
6415}
6416
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006417/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6418/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006419bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6420 QualType rhs) {
6421 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6422 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6423 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6424
6425 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6426 E = lhsQID->qual_end(); I != E; ++I) {
6427 bool match = false;
6428 ObjCProtocolDecl *lhsProto = *I;
6429 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6430 E = rhsOPT->qual_end(); J != E; ++J) {
6431 ObjCProtocolDecl *rhsProto = *J;
6432 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6433 match = true;
6434 break;
6435 }
6436 }
6437 if (!match)
6438 return false;
6439 }
6440 return true;
6441}
6442
Steve Naroff8e6aee52009-07-23 01:01:38 +00006443/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6444/// ObjCQualifiedIDType.
6445bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6446 bool compare) {
6447 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00006448 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006449 lhs->isObjCIdType() || lhs->isObjCClassType())
6450 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006451 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006452 rhs->isObjCIdType() || rhs->isObjCClassType())
6453 return true;
6454
6455 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00006456 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006457
Steve Naroff8e6aee52009-07-23 01:01:38 +00006458 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00006459
Steve Naroff8e6aee52009-07-23 01:01:38 +00006460 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00006461 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006462 // make sure we check the class hierarchy.
6463 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6464 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6465 E = lhsQID->qual_end(); I != E; ++I) {
6466 // when comparing an id<P> on lhs with a static type on rhs,
6467 // see if static class implements all of id's protocols, directly or
6468 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00006469 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006470 return false;
6471 }
6472 }
6473 // If there are no qualifiers and no interface, we have an 'id'.
6474 return true;
6475 }
Mike Stump11289f42009-09-09 15:08:12 +00006476 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006477 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6478 E = lhsQID->qual_end(); I != E; ++I) {
6479 ObjCProtocolDecl *lhsProto = *I;
6480 bool match = false;
6481
6482 // when comparing an id<P> on lhs with a static type on rhs,
6483 // see if static class implements all of id's protocols, directly or
6484 // through its super class and categories.
6485 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6486 E = rhsOPT->qual_end(); J != E; ++J) {
6487 ObjCProtocolDecl *rhsProto = *J;
6488 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6489 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6490 match = true;
6491 break;
6492 }
6493 }
Mike Stump11289f42009-09-09 15:08:12 +00006494 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006495 // make sure we check the class hierarchy.
6496 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6497 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6498 E = lhsQID->qual_end(); I != E; ++I) {
6499 // when comparing an id<P> on lhs with a static type on rhs,
6500 // see if static class implements all of id's protocols, directly or
6501 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00006502 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006503 match = true;
6504 break;
6505 }
6506 }
6507 }
6508 if (!match)
6509 return false;
6510 }
Mike Stump11289f42009-09-09 15:08:12 +00006511
Steve Naroff8e6aee52009-07-23 01:01:38 +00006512 return true;
6513 }
Mike Stump11289f42009-09-09 15:08:12 +00006514
Steve Naroff8e6aee52009-07-23 01:01:38 +00006515 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6516 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6517
Mike Stump11289f42009-09-09 15:08:12 +00006518 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00006519 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006520 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006521 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
6522 E = lhsOPT->qual_end(); I != E; ++I) {
6523 ObjCProtocolDecl *lhsProto = *I;
6524 bool match = false;
6525
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006526 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00006527 // see if static class implements all of id's protocols, directly or
6528 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006529 // First, lhs protocols in the qualifier list must be found, direct
6530 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006531 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6532 E = rhsQID->qual_end(); J != E; ++J) {
6533 ObjCProtocolDecl *rhsProto = *J;
6534 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6535 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6536 match = true;
6537 break;
6538 }
6539 }
6540 if (!match)
6541 return false;
6542 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006543
6544 // Static class's protocols, or its super class or category protocols
6545 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6546 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6547 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6548 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6549 // This is rather dubious but matches gcc's behavior. If lhs has
6550 // no type qualifier and its class has no static protocol(s)
6551 // assume that it is mismatch.
6552 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6553 return false;
6554 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6555 LHSInheritedProtocols.begin(),
6556 E = LHSInheritedProtocols.end(); I != E; ++I) {
6557 bool match = false;
6558 ObjCProtocolDecl *lhsProto = (*I);
6559 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6560 E = rhsQID->qual_end(); J != E; ++J) {
6561 ObjCProtocolDecl *rhsProto = *J;
6562 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6563 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6564 match = true;
6565 break;
6566 }
6567 }
6568 if (!match)
6569 return false;
6570 }
6571 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00006572 return true;
6573 }
6574 return false;
6575}
6576
Eli Friedman47f77112008-08-22 00:56:42 +00006577/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006578/// compatible for assignment from RHS to LHS. This handles validation of any
6579/// protocol qualifiers on the LHS or RHS.
6580///
Steve Naroff7cae42b2009-07-10 23:34:53 +00006581bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6582 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00006583 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6584 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6585
Steve Naroff1329fa02009-07-15 18:40:39 +00006586 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00006587 if (LHS->isObjCUnqualifiedIdOrClass() ||
6588 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00006589 return true;
6590
John McCall8b07ec22010-05-15 11:32:37 +00006591 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00006592 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6593 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00006594 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006595
6596 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6597 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6598 QualType(RHSOPT,0));
6599
John McCall8b07ec22010-05-15 11:32:37 +00006600 // If we have 2 user-defined types, fall into that path.
6601 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00006602 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006603
Steve Naroff8e6aee52009-07-23 01:01:38 +00006604 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006605}
6606
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006607/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00006608/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006609/// arguments in block literals. When passed as arguments, passing 'A*' where
6610/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6611/// not OK. For the return type, the opposite is not OK.
6612bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6613 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006614 const ObjCObjectPointerType *RHSOPT,
6615 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006616 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006617 return true;
6618
6619 if (LHSOPT->isObjCBuiltinType()) {
6620 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6621 }
6622
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006623 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006624 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6625 QualType(RHSOPT,0),
6626 false);
6627
6628 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6629 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6630 if (LHS && RHS) { // We have 2 user-defined types.
6631 if (LHS != RHS) {
6632 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006633 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006634 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006635 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006636 }
6637 else
6638 return true;
6639 }
6640 return false;
6641}
6642
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006643/// getIntersectionOfProtocols - This routine finds the intersection of set
6644/// of protocols inherited from two distinct objective-c pointer objects.
6645/// It is used to build composite qualifier list of the composite type of
6646/// the conditional expression involving two objective-c pointer objects.
6647static
6648void getIntersectionOfProtocols(ASTContext &Context,
6649 const ObjCObjectPointerType *LHSOPT,
6650 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006651 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006652
John McCall8b07ec22010-05-15 11:32:37 +00006653 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6654 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6655 assert(LHS->getInterface() && "LHS must have an interface base");
6656 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006657
6658 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6659 unsigned LHSNumProtocols = LHS->getNumProtocols();
6660 if (LHSNumProtocols > 0)
6661 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6662 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006663 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006664 Context.CollectInheritedProtocols(LHS->getInterface(),
6665 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006666 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6667 LHSInheritedProtocols.end());
6668 }
6669
6670 unsigned RHSNumProtocols = RHS->getNumProtocols();
6671 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00006672 ObjCProtocolDecl **RHSProtocols =
6673 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006674 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6675 if (InheritedProtocolSet.count(RHSProtocols[i]))
6676 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00006677 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006678 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006679 Context.CollectInheritedProtocols(RHS->getInterface(),
6680 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006681 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6682 RHSInheritedProtocols.begin(),
6683 E = RHSInheritedProtocols.end(); I != E; ++I)
6684 if (InheritedProtocolSet.count((*I)))
6685 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006686 }
6687}
6688
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006689/// areCommonBaseCompatible - Returns common base class of the two classes if
6690/// one found. Note that this is O'2 algorithm. But it will be called as the
6691/// last type comparison in a ?-exp of ObjC pointer types before a
6692/// warning is issued. So, its invokation is extremely rare.
6693QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00006694 const ObjCObjectPointerType *Lptr,
6695 const ObjCObjectPointerType *Rptr) {
6696 const ObjCObjectType *LHS = Lptr->getObjectType();
6697 const ObjCObjectType *RHS = Rptr->getObjectType();
6698 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6699 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00006700 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006701 return QualType();
6702
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006703 do {
John McCall8b07ec22010-05-15 11:32:37 +00006704 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006705 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006706 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00006707 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6708
6709 QualType Result = QualType(LHS, 0);
6710 if (!Protocols.empty())
6711 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6712 Result = getObjCObjectPointerType(Result);
6713 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006714 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006715 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006716
6717 return QualType();
6718}
6719
John McCall8b07ec22010-05-15 11:32:37 +00006720bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6721 const ObjCObjectType *RHS) {
6722 assert(LHS->getInterface() && "LHS is not an interface type");
6723 assert(RHS->getInterface() && "RHS is not an interface type");
6724
Chris Lattner49af6a42008-04-07 06:51:04 +00006725 // Verify that the base decls are compatible: the RHS must be a subclass of
6726 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00006727 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00006728 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006729
Chris Lattner49af6a42008-04-07 06:51:04 +00006730 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6731 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00006732 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00006733 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006734
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006735 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6736 // more detailed analysis is required.
6737 if (RHS->getNumProtocols() == 0) {
6738 // OK, if LHS is a superclass of RHS *and*
6739 // this superclass is assignment compatible with LHS.
6740 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006741 bool IsSuperClass =
6742 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6743 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006744 // OK if conversion of LHS to SuperClass results in narrowing of types
6745 // ; i.e., SuperClass may implement at least one of the protocols
6746 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6747 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6748 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006749 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006750 // If super class has no protocols, it is not a match.
6751 if (SuperClassInheritedProtocols.empty())
6752 return false;
6753
6754 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6755 LHSPE = LHS->qual_end();
6756 LHSPI != LHSPE; LHSPI++) {
6757 bool SuperImplementsProtocol = false;
6758 ObjCProtocolDecl *LHSProto = (*LHSPI);
6759
6760 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6761 SuperClassInheritedProtocols.begin(),
6762 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6763 ObjCProtocolDecl *SuperClassProto = (*I);
6764 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6765 SuperImplementsProtocol = true;
6766 break;
6767 }
6768 }
6769 if (!SuperImplementsProtocol)
6770 return false;
6771 }
6772 return true;
6773 }
6774 return false;
6775 }
Mike Stump11289f42009-09-09 15:08:12 +00006776
John McCall8b07ec22010-05-15 11:32:37 +00006777 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6778 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00006779 LHSPI != LHSPE; LHSPI++) {
6780 bool RHSImplementsProtocol = false;
6781
6782 // If the RHS doesn't implement the protocol on the left, the types
6783 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00006784 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6785 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00006786 RHSPI != RHSPE; RHSPI++) {
6787 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00006788 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00006789 break;
6790 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006791 }
6792 // FIXME: For better diagnostics, consider passing back the protocol name.
6793 if (!RHSImplementsProtocol)
6794 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00006795 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006796 // The RHS implements all protocols listed on the LHS.
6797 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00006798}
6799
Steve Naroffb7605152009-02-12 17:52:19 +00006800bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6801 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00006802 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6803 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006804
Steve Naroff7cae42b2009-07-10 23:34:53 +00006805 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00006806 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006807
6808 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6809 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00006810}
6811
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006812bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6813 return canAssignObjCInterfaces(
6814 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6815 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6816}
6817
Mike Stump11289f42009-09-09 15:08:12 +00006818/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00006819/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00006820/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00006821/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006822bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6823 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006824 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00006825 return hasSameType(LHS, RHS);
6826
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006827 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00006828}
6829
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006830bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00006831 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006832}
6833
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006834bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6835 return !mergeTypes(LHS, RHS, true).isNull();
6836}
6837
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006838/// mergeTransparentUnionType - if T is a transparent union type and a member
6839/// of T is compatible with SubType, return the merged type, else return
6840/// QualType()
6841QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6842 bool OfBlockPointer,
6843 bool Unqualified) {
6844 if (const RecordType *UT = T->getAsUnionType()) {
6845 RecordDecl *UD = UT->getDecl();
6846 if (UD->hasAttr<TransparentUnionAttr>()) {
6847 for (RecordDecl::field_iterator it = UD->field_begin(),
6848 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00006849 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006850 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6851 if (!MT.isNull())
6852 return MT;
6853 }
6854 }
6855 }
6856
6857 return QualType();
6858}
6859
6860/// mergeFunctionArgumentTypes - merge two types which appear as function
6861/// argument types
6862QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
6863 bool OfBlockPointer,
6864 bool Unqualified) {
6865 // GNU extension: two types are compatible if they appear as a function
6866 // argument, one of the types is a transparent union type and the other
6867 // type is compatible with a union member
6868 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6869 Unqualified);
6870 if (!lmerge.isNull())
6871 return lmerge;
6872
6873 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6874 Unqualified);
6875 if (!rmerge.isNull())
6876 return rmerge;
6877
6878 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6879}
6880
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006881QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006882 bool OfBlockPointer,
6883 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00006884 const FunctionType *lbase = lhs->getAs<FunctionType>();
6885 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006886 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6887 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00006888 bool allLTypes = true;
6889 bool allRTypes = true;
6890
6891 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006892 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00006893 if (OfBlockPointer) {
6894 QualType RHS = rbase->getResultType();
6895 QualType LHS = lbase->getResultType();
6896 bool UnqualifiedResult = Unqualified;
6897 if (!UnqualifiedResult)
6898 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006899 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00006900 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006901 else
John McCall8c6b56f2010-12-15 01:06:38 +00006902 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6903 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006904 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006905
6906 if (Unqualified)
6907 retType = retType.getUnqualifiedType();
6908
6909 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6910 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6911 if (Unqualified) {
6912 LRetType = LRetType.getUnqualifiedType();
6913 RRetType = RRetType.getUnqualifiedType();
6914 }
6915
6916 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006917 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006918 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006919 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006920
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00006921 // FIXME: double check this
6922 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6923 // rbase->getRegParmAttr() != 0 &&
6924 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00006925 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6926 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00006927
Douglas Gregor8c940862010-01-18 17:14:39 +00006928 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00006929 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00006930 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006931
John McCall8c6b56f2010-12-15 01:06:38 +00006932 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00006933 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6934 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00006935 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6936 return QualType();
6937
John McCall31168b02011-06-15 23:02:42 +00006938 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6939 return QualType();
6940
John McCall8c6b56f2010-12-15 01:06:38 +00006941 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6942 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00006943
Rafael Espindola8778c282012-11-29 16:09:03 +00006944 if (lbaseInfo.getNoReturn() != NoReturn)
6945 allLTypes = false;
6946 if (rbaseInfo.getNoReturn() != NoReturn)
6947 allRTypes = false;
6948
John McCall31168b02011-06-15 23:02:42 +00006949 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00006950
Eli Friedman47f77112008-08-22 00:56:42 +00006951 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006952 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6953 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00006954 unsigned lproto_nargs = lproto->getNumArgs();
6955 unsigned rproto_nargs = rproto->getNumArgs();
6956
6957 // Compatible functions must have the same number of arguments
6958 if (lproto_nargs != rproto_nargs)
6959 return QualType();
6960
6961 // Variadic and non-variadic functions aren't compatible
6962 if (lproto->isVariadic() != rproto->isVariadic())
6963 return QualType();
6964
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00006965 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6966 return QualType();
6967
Fariborz Jahanian97676972011-09-28 21:52:05 +00006968 if (LangOpts.ObjCAutoRefCount &&
6969 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6970 return QualType();
6971
Eli Friedman47f77112008-08-22 00:56:42 +00006972 // Check argument compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006973 SmallVector<QualType, 10> types;
Eli Friedman47f77112008-08-22 00:56:42 +00006974 for (unsigned i = 0; i < lproto_nargs; i++) {
6975 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
6976 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006977 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
6978 OfBlockPointer,
6979 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006980 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006981
6982 if (Unqualified)
6983 argtype = argtype.getUnqualifiedType();
6984
Eli Friedman47f77112008-08-22 00:56:42 +00006985 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006986 if (Unqualified) {
6987 largtype = largtype.getUnqualifiedType();
6988 rargtype = rargtype.getUnqualifiedType();
6989 }
6990
Chris Lattner465fa322008-10-05 17:34:18 +00006991 if (getCanonicalType(argtype) != getCanonicalType(largtype))
6992 allLTypes = false;
6993 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
6994 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00006995 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00006996
Eli Friedman47f77112008-08-22 00:56:42 +00006997 if (allLTypes) return lhs;
6998 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00006999
7000 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7001 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00007002 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007003 }
7004
7005 if (lproto) allRTypes = false;
7006 if (rproto) allLTypes = false;
7007
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007008 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00007009 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007010 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00007011 if (proto->isVariadic()) return QualType();
7012 // Check that the types are compatible with the types that
7013 // would result from default argument promotions (C99 6.7.5.3p15).
7014 // The only types actually affected are promotable integer
7015 // types and floats, which would be passed as a different
7016 // type depending on whether the prototype is visible.
7017 unsigned proto_nargs = proto->getNumArgs();
7018 for (unsigned i = 0; i < proto_nargs; ++i) {
7019 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00007020
Eli Friedman448ce402012-08-30 00:44:15 +00007021 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00007022 // to pass enum values.
Eli Friedman448ce402012-08-30 00:44:15 +00007023 if (const EnumType *Enum = argTy->getAs<EnumType>()) {
7024 argTy = Enum->getDecl()->getIntegerType();
7025 if (argTy.isNull())
7026 return QualType();
7027 }
Douglas Gregor2973d402010-02-03 19:27:29 +00007028
Eli Friedman47f77112008-08-22 00:56:42 +00007029 if (argTy->isPromotableIntegerType() ||
7030 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
7031 return QualType();
7032 }
7033
7034 if (allLTypes) return lhs;
7035 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007036
7037 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7038 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00007039 return getFunctionType(retType,
7040 ArrayRef<QualType>(proto->arg_type_begin(),
7041 proto->getNumArgs()),
7042 EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007043 }
7044
7045 if (allLTypes) return lhs;
7046 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00007047 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00007048}
7049
John McCall433c2e62013-03-21 00:10:07 +00007050/// Given that we have an enum type and a non-enum type, try to merge them.
7051static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7052 QualType other, bool isBlockReturnType) {
7053 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7054 // a signed integer type, or an unsigned integer type.
7055 // Compatibility is based on the underlying type, not the promotion
7056 // type.
7057 QualType underlyingType = ET->getDecl()->getIntegerType();
7058 if (underlyingType.isNull()) return QualType();
7059 if (Context.hasSameType(underlyingType, other))
7060 return other;
7061
7062 // In block return types, we're more permissive and accept any
7063 // integral type of the same size.
7064 if (isBlockReturnType && other->isIntegerType() &&
7065 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7066 return other;
7067
7068 return QualType();
7069}
7070
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007071QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007072 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007073 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00007074 // C++ [expr]: If an expression initially has the type "reference to T", the
7075 // type is adjusted to "T" prior to any further analysis, the expression
7076 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007077 // expression is an lvalue unless the reference is an rvalue reference and
7078 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00007079 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7080 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007081
7082 if (Unqualified) {
7083 LHS = LHS.getUnqualifiedType();
7084 RHS = RHS.getUnqualifiedType();
7085 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00007086
Eli Friedman47f77112008-08-22 00:56:42 +00007087 QualType LHSCan = getCanonicalType(LHS),
7088 RHSCan = getCanonicalType(RHS);
7089
7090 // If two types are identical, they are compatible.
7091 if (LHSCan == RHSCan)
7092 return LHS;
7093
John McCall8ccfcb52009-09-24 19:53:00 +00007094 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007095 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7096 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00007097 if (LQuals != RQuals) {
7098 // If any of these qualifiers are different, we have a type
7099 // mismatch.
7100 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00007101 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7102 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00007103 return QualType();
7104
7105 // Exactly one GC qualifier difference is allowed: __strong is
7106 // okay if the other type has no GC qualifier but is an Objective
7107 // C object pointer (i.e. implicitly strong by default). We fix
7108 // this by pretending that the unqualified type was actually
7109 // qualified __strong.
7110 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7111 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7112 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7113
7114 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7115 return QualType();
7116
7117 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7118 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7119 }
7120 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7121 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7122 }
Eli Friedman47f77112008-08-22 00:56:42 +00007123 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00007124 }
7125
7126 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00007127
Eli Friedmandcca6332009-06-01 01:22:52 +00007128 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7129 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00007130
Chris Lattnerfd652912008-01-14 05:45:46 +00007131 // We want to consider the two function types to be the same for these
7132 // comparisons, just force one to the other.
7133 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7134 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00007135
7136 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00007137 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7138 LHSClass = Type::ConstantArray;
7139 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7140 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00007141
John McCall8b07ec22010-05-15 11:32:37 +00007142 // ObjCInterfaces are just specialized ObjCObjects.
7143 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7144 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7145
Nate Begemance4d7fc2008-04-18 23:10:10 +00007146 // Canonicalize ExtVector -> Vector.
7147 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7148 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00007149
Chris Lattner95554662008-04-07 05:43:21 +00007150 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007151 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00007152 // Note that we only have special rules for turning block enum
7153 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00007154 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007155 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007156 }
John McCall9dd450b2009-09-21 23:43:11 +00007157 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007158 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007159 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007160 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00007161 if (OfBlockPointer && !BlockReturnType) {
7162 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7163 return LHS;
7164 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7165 return RHS;
7166 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007167
Eli Friedman47f77112008-08-22 00:56:42 +00007168 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00007169 }
Eli Friedman47f77112008-08-22 00:56:42 +00007170
Steve Naroffc6edcbd2008-01-09 22:43:08 +00007171 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007172 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007173#define TYPE(Class, Base)
7174#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00007175#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007176#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7177#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7178#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00007179 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007180
Richard Smith27d807c2013-04-30 13:56:41 +00007181 case Type::Auto:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007182 case Type::LValueReference:
7183 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007184 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00007185 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007186
John McCall8b07ec22010-05-15 11:32:37 +00007187 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007188 case Type::IncompleteArray:
7189 case Type::VariableArray:
7190 case Type::FunctionProto:
7191 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00007192 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007193
Chris Lattnerfd652912008-01-14 05:45:46 +00007194 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00007195 {
7196 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007197 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7198 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007199 if (Unqualified) {
7200 LHSPointee = LHSPointee.getUnqualifiedType();
7201 RHSPointee = RHSPointee.getUnqualifiedType();
7202 }
7203 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7204 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007205 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00007206 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007207 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00007208 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007209 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007210 return getPointerType(ResultType);
7211 }
Steve Naroff68e167d2008-12-10 17:49:55 +00007212 case Type::BlockPointer:
7213 {
7214 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007215 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7216 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007217 if (Unqualified) {
7218 LHSPointee = LHSPointee.getUnqualifiedType();
7219 RHSPointee = RHSPointee.getUnqualifiedType();
7220 }
7221 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7222 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00007223 if (ResultType.isNull()) return QualType();
7224 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7225 return LHS;
7226 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7227 return RHS;
7228 return getBlockPointerType(ResultType);
7229 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00007230 case Type::Atomic:
7231 {
7232 // Merge two pointer types, while trying to preserve typedef info
7233 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7234 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7235 if (Unqualified) {
7236 LHSValue = LHSValue.getUnqualifiedType();
7237 RHSValue = RHSValue.getUnqualifiedType();
7238 }
7239 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7240 Unqualified);
7241 if (ResultType.isNull()) return QualType();
7242 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7243 return LHS;
7244 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7245 return RHS;
7246 return getAtomicType(ResultType);
7247 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007248 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00007249 {
7250 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7251 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7252 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7253 return QualType();
7254
7255 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7256 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007257 if (Unqualified) {
7258 LHSElem = LHSElem.getUnqualifiedType();
7259 RHSElem = RHSElem.getUnqualifiedType();
7260 }
7261
7262 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007263 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00007264 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7265 return LHS;
7266 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7267 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00007268 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7269 ArrayType::ArraySizeModifier(), 0);
7270 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7271 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007272 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7273 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00007274 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7275 return LHS;
7276 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7277 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007278 if (LVAT) {
7279 // FIXME: This isn't correct! But tricky to implement because
7280 // the array's size has to be the size of LHS, but the type
7281 // has to be different.
7282 return LHS;
7283 }
7284 if (RVAT) {
7285 // FIXME: This isn't correct! But tricky to implement because
7286 // the array's size has to be the size of RHS, but the type
7287 // has to be different.
7288 return RHS;
7289 }
Eli Friedman3e62c212008-08-22 01:48:21 +00007290 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7291 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00007292 return getIncompleteArrayType(ResultType,
7293 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007294 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007295 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007296 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007297 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007298 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00007299 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00007300 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007301 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00007302 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00007303 case Type::Complex:
7304 // Distinct complex types are incompatible.
7305 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007306 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00007307 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00007308 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7309 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00007310 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00007311 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00007312 case Type::ObjCObject: {
7313 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00007314 // FIXME: This should be type compatibility, e.g. whether
7315 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00007316 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7317 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7318 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00007319 return LHS;
7320
Eli Friedman47f77112008-08-22 00:56:42 +00007321 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00007322 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007323 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007324 if (OfBlockPointer) {
7325 if (canAssignObjCInterfacesInBlockPointer(
7326 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007327 RHS->getAs<ObjCObjectPointerType>(),
7328 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00007329 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007330 return QualType();
7331 }
John McCall9dd450b2009-09-21 23:43:11 +00007332 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7333 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007334 return LHS;
7335
Steve Naroffc68cfcf2008-12-10 22:14:21 +00007336 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00007337 }
Steve Naroff32e44c02007-10-15 20:41:53 +00007338 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007339
David Blaikie8a40f702012-01-17 06:56:22 +00007340 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00007341}
Ted Kremenekfc581a92007-10-31 17:10:13 +00007342
Fariborz Jahanian97676972011-09-28 21:52:05 +00007343bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7344 const FunctionProtoType *FromFunctionType,
7345 const FunctionProtoType *ToFunctionType) {
7346 if (FromFunctionType->hasAnyConsumedArgs() !=
7347 ToFunctionType->hasAnyConsumedArgs())
7348 return false;
7349 FunctionProtoType::ExtProtoInfo FromEPI =
7350 FromFunctionType->getExtProtoInfo();
7351 FunctionProtoType::ExtProtoInfo ToEPI =
7352 ToFunctionType->getExtProtoInfo();
7353 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
7354 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
7355 ArgIdx != NumArgs; ++ArgIdx) {
7356 if (FromEPI.ConsumedArguments[ArgIdx] !=
7357 ToEPI.ConsumedArguments[ArgIdx])
7358 return false;
7359 }
7360 return true;
7361}
7362
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007363/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7364/// 'RHS' attributes and returns the merged version; including for function
7365/// return types.
7366QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7367 QualType LHSCan = getCanonicalType(LHS),
7368 RHSCan = getCanonicalType(RHS);
7369 // If two types are identical, they are compatible.
7370 if (LHSCan == RHSCan)
7371 return LHS;
7372 if (RHSCan->isFunctionType()) {
7373 if (!LHSCan->isFunctionType())
7374 return QualType();
7375 QualType OldReturnType =
7376 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
7377 QualType NewReturnType =
7378 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
7379 QualType ResReturnType =
7380 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7381 if (ResReturnType.isNull())
7382 return QualType();
7383 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7384 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7385 // In either case, use OldReturnType to build the new function type.
7386 const FunctionType *F = LHS->getAs<FunctionType>();
7387 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00007388 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7389 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007390 QualType ResultType
Jordan Rose5c382722013-03-08 21:51:21 +00007391 = getFunctionType(OldReturnType,
7392 ArrayRef<QualType>(FPT->arg_type_begin(),
7393 FPT->getNumArgs()),
7394 EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007395 return ResultType;
7396 }
7397 }
7398 return QualType();
7399 }
7400
7401 // If the qualifiers are different, the types can still be merged.
7402 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7403 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7404 if (LQuals != RQuals) {
7405 // If any of these qualifiers are different, we have a type mismatch.
7406 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7407 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7408 return QualType();
7409
7410 // Exactly one GC qualifier difference is allowed: __strong is
7411 // okay if the other type has no GC qualifier but is an Objective
7412 // C object pointer (i.e. implicitly strong by default). We fix
7413 // this by pretending that the unqualified type was actually
7414 // qualified __strong.
7415 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7416 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7417 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7418
7419 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7420 return QualType();
7421
7422 if (GC_L == Qualifiers::Strong)
7423 return LHS;
7424 if (GC_R == Qualifiers::Strong)
7425 return RHS;
7426 return QualType();
7427 }
7428
7429 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7430 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7431 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7432 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7433 if (ResQT == LHSBaseQT)
7434 return LHS;
7435 if (ResQT == RHSBaseQT)
7436 return RHS;
7437 }
7438 return QualType();
7439}
7440
Chris Lattner4ba0cef2008-04-07 07:01:58 +00007441//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007442// Integer Predicates
7443//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00007444
Jay Foad39c79802011-01-12 09:06:06 +00007445unsigned ASTContext::getIntWidth(QualType T) const {
John McCall424cec92011-01-19 06:33:43 +00007446 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00007447 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00007448 if (T->isBooleanType())
7449 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00007450 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007451 return (unsigned)getTypeSize(T);
7452}
7453
Abramo Bagnara13640492012-09-09 10:21:24 +00007454QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007455 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00007456
7457 // Turn <4 x signed int> -> <4 x unsigned int>
7458 if (const VectorType *VTy = T->getAs<VectorType>())
7459 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00007460 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00007461
7462 // For enums, we return the unsigned version of the base type.
7463 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007464 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00007465
7466 const BuiltinType *BTy = T->getAs<BuiltinType>();
7467 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007468 switch (BTy->getKind()) {
7469 case BuiltinType::Char_S:
7470 case BuiltinType::SChar:
7471 return UnsignedCharTy;
7472 case BuiltinType::Short:
7473 return UnsignedShortTy;
7474 case BuiltinType::Int:
7475 return UnsignedIntTy;
7476 case BuiltinType::Long:
7477 return UnsignedLongTy;
7478 case BuiltinType::LongLong:
7479 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00007480 case BuiltinType::Int128:
7481 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007482 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007483 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007484 }
7485}
7486
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00007487ASTMutationListener::~ASTMutationListener() { }
7488
Richard Smith1fa5d642013-05-11 05:45:24 +00007489void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7490 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00007491
7492//===----------------------------------------------------------------------===//
7493// Builtin Type Computation
7494//===----------------------------------------------------------------------===//
7495
7496/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00007497/// pointer over the consumed characters. This returns the resultant type. If
7498/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7499/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7500/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007501///
7502/// RequiresICE is filled in on return to indicate whether the value is required
7503/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00007504static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00007505 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007506 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00007507 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00007508 // Modifiers.
7509 int HowLong = 0;
7510 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007511 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00007512
Chris Lattnerdc226c22010-10-01 22:42:38 +00007513 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00007514 bool Done = false;
7515 while (!Done) {
7516 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00007517 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00007518 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007519 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00007520 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007521 case 'S':
7522 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7523 assert(!Signed && "Can't use 'S' modifier multiple times!");
7524 Signed = true;
7525 break;
7526 case 'U':
7527 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7528 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7529 Unsigned = true;
7530 break;
7531 case 'L':
7532 assert(HowLong <= 2 && "Can't have LLLL modifier");
7533 ++HowLong;
7534 break;
7535 }
7536 }
7537
7538 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00007539
Chris Lattnerecd79c62009-06-14 00:45:47 +00007540 // Read the base type.
7541 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00007542 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007543 case 'v':
7544 assert(HowLong == 0 && !Signed && !Unsigned &&
7545 "Bad modifiers used with 'v'!");
7546 Type = Context.VoidTy;
7547 break;
7548 case 'f':
7549 assert(HowLong == 0 && !Signed && !Unsigned &&
7550 "Bad modifiers used with 'f'!");
7551 Type = Context.FloatTy;
7552 break;
7553 case 'd':
7554 assert(HowLong < 2 && !Signed && !Unsigned &&
7555 "Bad modifiers used with 'd'!");
7556 if (HowLong)
7557 Type = Context.LongDoubleTy;
7558 else
7559 Type = Context.DoubleTy;
7560 break;
7561 case 's':
7562 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7563 if (Unsigned)
7564 Type = Context.UnsignedShortTy;
7565 else
7566 Type = Context.ShortTy;
7567 break;
7568 case 'i':
7569 if (HowLong == 3)
7570 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7571 else if (HowLong == 2)
7572 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7573 else if (HowLong == 1)
7574 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7575 else
7576 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7577 break;
7578 case 'c':
7579 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7580 if (Signed)
7581 Type = Context.SignedCharTy;
7582 else if (Unsigned)
7583 Type = Context.UnsignedCharTy;
7584 else
7585 Type = Context.CharTy;
7586 break;
7587 case 'b': // boolean
7588 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7589 Type = Context.BoolTy;
7590 break;
7591 case 'z': // size_t.
7592 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7593 Type = Context.getSizeType();
7594 break;
7595 case 'F':
7596 Type = Context.getCFConstantStringType();
7597 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00007598 case 'G':
7599 Type = Context.getObjCIdType();
7600 break;
7601 case 'H':
7602 Type = Context.getObjCSelType();
7603 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00007604 case 'M':
7605 Type = Context.getObjCSuperType();
7606 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007607 case 'a':
7608 Type = Context.getBuiltinVaListType();
7609 assert(!Type.isNull() && "builtin va list type not initialized!");
7610 break;
7611 case 'A':
7612 // This is a "reference" to a va_list; however, what exactly
7613 // this means depends on how va_list is defined. There are two
7614 // different kinds of va_list: ones passed by value, and ones
7615 // passed by reference. An example of a by-value va_list is
7616 // x86, where va_list is a char*. An example of by-ref va_list
7617 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7618 // we want this argument to be a char*&; for x86-64, we want
7619 // it to be a __va_list_tag*.
7620 Type = Context.getBuiltinVaListType();
7621 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007622 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00007623 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007624 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00007625 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007626 break;
7627 case 'V': {
7628 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007629 unsigned NumElements = strtoul(Str, &End, 10);
7630 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007631 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00007632
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007633 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7634 RequiresICE, false);
7635 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00007636
7637 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00007638 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00007639 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007640 break;
7641 }
Douglas Gregorfed66992012-06-07 18:08:25 +00007642 case 'E': {
7643 char *End;
7644
7645 unsigned NumElements = strtoul(Str, &End, 10);
7646 assert(End != Str && "Missing vector size");
7647
7648 Str = End;
7649
7650 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7651 false);
7652 Type = Context.getExtVectorType(ElementType, NumElements);
7653 break;
7654 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007655 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007656 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7657 false);
7658 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007659 Type = Context.getComplexType(ElementType);
7660 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00007661 }
7662 case 'Y' : {
7663 Type = Context.getPointerDiffType();
7664 break;
7665 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00007666 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00007667 Type = Context.getFILEType();
7668 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007669 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007670 return QualType();
7671 }
Mike Stump2adb4da2009-07-28 23:47:15 +00007672 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00007673 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00007674 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00007675 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00007676 else
7677 Type = Context.getjmp_bufType();
7678
Mike Stump2adb4da2009-07-28 23:47:15 +00007679 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007680 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00007681 return QualType();
7682 }
7683 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00007684 case 'K':
7685 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7686 Type = Context.getucontext_tType();
7687
7688 if (Type.isNull()) {
7689 Error = ASTContext::GE_Missing_ucontext;
7690 return QualType();
7691 }
7692 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00007693 case 'p':
7694 Type = Context.getProcessIDType();
7695 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00007696 }
Mike Stump11289f42009-09-09 15:08:12 +00007697
Chris Lattnerdc226c22010-10-01 22:42:38 +00007698 // If there are modifiers and if we're allowed to parse them, go for it.
7699 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007700 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00007701 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007702 default: Done = true; --Str; break;
7703 case '*':
7704 case '&': {
7705 // Both pointers and references can have their pointee types
7706 // qualified with an address space.
7707 char *End;
7708 unsigned AddrSpace = strtoul(Str, &End, 10);
7709 if (End != Str && AddrSpace != 0) {
7710 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7711 Str = End;
7712 }
7713 if (c == '*')
7714 Type = Context.getPointerType(Type);
7715 else
7716 Type = Context.getLValueReferenceType(Type);
7717 break;
7718 }
7719 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7720 case 'C':
7721 Type = Type.withConst();
7722 break;
7723 case 'D':
7724 Type = Context.getVolatileType(Type);
7725 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00007726 case 'R':
7727 Type = Type.withRestrict();
7728 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007729 }
7730 }
Chris Lattner84733392010-10-01 07:13:18 +00007731
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007732 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00007733 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00007734
Chris Lattnerecd79c62009-06-14 00:45:47 +00007735 return Type;
7736}
7737
7738/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00007739QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007740 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00007741 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007742 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00007743
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007744 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00007745
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007746 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007747 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007748 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7749 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007750 if (Error != GE_None)
7751 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007752
7753 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7754
Chris Lattnerecd79c62009-06-14 00:45:47 +00007755 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007756 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007757 if (Error != GE_None)
7758 return QualType();
7759
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007760 // If this argument is required to be an IntegerConstantExpression and the
7761 // caller cares, fill in the bitmask we return.
7762 if (RequiresICE && IntegerConstantArgs)
7763 *IntegerConstantArgs |= 1 << ArgTypes.size();
7764
Chris Lattnerecd79c62009-06-14 00:45:47 +00007765 // Do array -> pointer decay. The builtin should use the decayed type.
7766 if (Ty->isArrayType())
7767 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00007768
Chris Lattnerecd79c62009-06-14 00:45:47 +00007769 ArgTypes.push_back(Ty);
7770 }
7771
7772 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7773 "'.' should only occur at end of builtin type list!");
7774
John McCall991eb4b2010-12-21 00:44:39 +00007775 FunctionType::ExtInfo EI;
7776 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7777
7778 bool Variadic = (TypeStr[0] == '.');
7779
7780 // We really shouldn't be making a no-proto type here, especially in C++.
7781 if (ArgTypes.empty() && Variadic)
7782 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00007783
John McCalldb40c7f2010-12-14 08:05:40 +00007784 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00007785 EPI.ExtInfo = EI;
7786 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00007787
Jordan Rose5c382722013-03-08 21:51:21 +00007788 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007789}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00007790
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007791GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007792 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007793 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007794
Rafael Espindola3ae00052013-05-13 00:12:11 +00007795 GVALinkage External = GVA_StrongExternal;
7796 switch (FD->getTemplateSpecializationKind()) {
7797 case TSK_Undeclared:
7798 case TSK_ExplicitSpecialization:
7799 External = GVA_StrongExternal;
7800 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007801
Rafael Espindola3ae00052013-05-13 00:12:11 +00007802 case TSK_ExplicitInstantiationDefinition:
7803 return GVA_ExplicitTemplateInstantiation;
7804
7805 case TSK_ExplicitInstantiationDeclaration:
7806 case TSK_ImplicitInstantiation:
7807 External = GVA_TemplateInstantiation;
7808 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007809 }
7810
7811 if (!FD->isInlined())
7812 return External;
7813
David Blaikiebbafb8a2012-03-11 07:00:24 +00007814 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007815 // GNU or C99 inline semantics. Determine whether this symbol should be
7816 // externally visible.
7817 if (FD->isInlineDefinitionExternallyVisible())
7818 return External;
7819
7820 // C99 inline semantics, where the symbol is not externally visible.
7821 return GVA_C99Inline;
7822 }
7823
7824 // C++0x [temp.explicit]p9:
7825 // [ Note: The intent is that an inline function that is the subject of
7826 // an explicit instantiation declaration will still be implicitly
7827 // instantiated when used so that the body can be considered for
7828 // inlining, but that no out-of-line copy of the inline function would be
7829 // generated in the translation unit. -- end note ]
7830 if (FD->getTemplateSpecializationKind()
7831 == TSK_ExplicitInstantiationDeclaration)
7832 return GVA_C99Inline;
7833
7834 return GVA_CXXInline;
7835}
7836
7837GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007838 if (!VD->isExternallyVisible())
7839 return GVA_Internal;
7840
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007841 // If this is a static data member, compute the kind of template
7842 // specialization. Otherwise, this variable is not part of a
7843 // template.
7844 TemplateSpecializationKind TSK = TSK_Undeclared;
7845 if (VD->isStaticDataMember())
7846 TSK = VD->getTemplateSpecializationKind();
7847
Rafael Espindola3ae00052013-05-13 00:12:11 +00007848 switch (TSK) {
7849 case TSK_Undeclared:
7850 case TSK_ExplicitSpecialization:
7851 return GVA_StrongExternal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007852
Rafael Espindola3ae00052013-05-13 00:12:11 +00007853 case TSK_ExplicitInstantiationDeclaration:
7854 llvm_unreachable("Variable should not be instantiated");
7855 // Fall through to treat this like any other instantiation.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007856
Rafael Espindola3ae00052013-05-13 00:12:11 +00007857 case TSK_ExplicitInstantiationDefinition:
7858 return GVA_ExplicitTemplateInstantiation;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007859
Rafael Espindola3ae00052013-05-13 00:12:11 +00007860 case TSK_ImplicitInstantiation:
7861 return GVA_TemplateInstantiation;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007862 }
Rafael Espindola27699c82013-05-13 14:05:53 +00007863
7864 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007865}
7866
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00007867bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007868 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7869 if (!VD->isFileVarDecl())
7870 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00007871 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7872 // We never need to emit an uninstantiated function template.
7873 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
7874 return false;
7875 } else
7876 return false;
7877
7878 // If this is a member of a class template, we do not need to emit it.
7879 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007880 return false;
7881
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007882 // Weak references don't produce any output by themselves.
7883 if (D->hasAttr<WeakRefAttr>())
7884 return false;
7885
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007886 // Aliases and used decls are required.
7887 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7888 return true;
7889
7890 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7891 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00007892 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00007893 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007894
7895 // Constructors and destructors are required.
7896 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7897 return true;
7898
John McCall6bd2a892013-01-25 22:31:03 +00007899 // The key function for a class is required. This rule only comes
7900 // into play when inline functions can be key functions, though.
7901 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7902 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7903 const CXXRecordDecl *RD = MD->getParent();
7904 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7905 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
7906 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7907 return true;
7908 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007909 }
7910 }
7911
7912 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7913
7914 // static, static inline, always_inline, and extern inline functions can
7915 // always be deferred. Normal inline functions can be deferred in C99/C++.
7916 // Implicit template instantiations can also be deferred in C++.
7917 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev79de4d42012-02-02 06:06:34 +00007918 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007919 return false;
7920 return true;
7921 }
Douglas Gregor87d81242011-09-10 00:22:34 +00007922
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007923 const VarDecl *VD = cast<VarDecl>(D);
7924 assert(VD->isFileVarDecl() && "Expected file scoped var");
7925
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007926 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7927 return false;
7928
Richard Smitha0e5e542012-11-12 21:38:00 +00007929 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007930 GVALinkage L = GetGVALinkageForVariable(VD);
Richard Smitha0e5e542012-11-12 21:38:00 +00007931 if (L != GVA_Internal && L != GVA_TemplateInstantiation)
7932 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007933
Richard Smitha0e5e542012-11-12 21:38:00 +00007934 // Variables that have destruction with side-effects are required.
7935 if (VD->getType().isDestructedType())
7936 return true;
7937
7938 // Variables that have initialization with side-effects are required.
7939 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
7940 return true;
7941
7942 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007943}
Charles Davis53c59df2010-08-16 03:33:14 +00007944
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007945CallingConv ASTContext::getDefaultCXXMethodCallConv(bool isVariadic) {
Charles Davis99202b32010-11-09 18:04:24 +00007946 // Pass through to the C++ ABI object
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007947 return ABI->getDefaultMethodCallConv(isVariadic);
7948}
7949
7950CallingConv ASTContext::getCanonicalCallConv(CallingConv CC) const {
John McCall359b8852013-01-25 22:30:49 +00007951 if (CC == CC_C && !LangOpts.MRTD &&
7952 getTargetInfo().getCXXABI().isMemberFunctionCCDefault())
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007953 return CC_Default;
7954 return CC;
Charles Davis99202b32010-11-09 18:04:24 +00007955}
7956
Jay Foad39c79802011-01-12 09:06:06 +00007957bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00007958 // Pass through to the C++ ABI object
7959 return ABI->isNearlyEmpty(RD);
7960}
7961
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007962MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00007963 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00007964 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00007965 case TargetCXXABI::GenericItanium:
7966 case TargetCXXABI::GenericARM:
7967 case TargetCXXABI::iOS:
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007968 return createItaniumMangleContext(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00007969 case TargetCXXABI::Microsoft:
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007970 return createMicrosoftMangleContext(*this, getDiagnostics());
7971 }
David Blaikie83d382b2011-09-23 05:06:16 +00007972 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007973}
7974
Charles Davis53c59df2010-08-16 03:33:14 +00007975CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007976
7977size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek7d39c9a2011-07-27 18:41:12 +00007978 return ASTRecordLayouts.getMemorySize()
7979 + llvm::capacity_in_bytes(ObjCLayouts)
7980 + llvm::capacity_in_bytes(KeyFunctions)
7981 + llvm::capacity_in_bytes(ObjCImpls)
7982 + llvm::capacity_in_bytes(BlockVarCopyInits)
7983 + llvm::capacity_in_bytes(DeclAttrs)
7984 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
7985 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
7986 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
7987 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
7988 + llvm::capacity_in_bytes(OverriddenMethods)
7989 + llvm::capacity_in_bytes(Types)
Francois Pichet00c7e6c2011-08-14 03:52:19 +00007990 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet57928252011-08-14 14:28:49 +00007991 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007992}
Ted Kremenek540017e2011-10-06 05:00:56 +00007993
David Blaikie095deba2012-11-14 01:52:05 +00007994void ASTContext::addUnnamedTag(const TagDecl *Tag) {
7995 // FIXME: This mangling should be applied to function local classes too
7996 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl() ||
Rafael Espindola3ae00052013-05-13 00:12:11 +00007997 !isa<CXXRecordDecl>(Tag->getParent()) ||
7998 !Tag->isExternallyVisible())
David Blaikie095deba2012-11-14 01:52:05 +00007999 return;
8000
8001 std::pair<llvm::DenseMap<const DeclContext *, unsigned>::iterator, bool> P =
8002 UnnamedMangleContexts.insert(std::make_pair(Tag->getParent(), 0));
8003 UnnamedMangleNumbers.insert(std::make_pair(Tag, P.first->second++));
8004}
8005
8006int ASTContext::getUnnamedTagManglingNumber(const TagDecl *Tag) const {
8007 llvm::DenseMap<const TagDecl *, unsigned>::const_iterator I =
8008 UnnamedMangleNumbers.find(Tag);
8009 return I != UnnamedMangleNumbers.end() ? I->second : -1;
8010}
8011
Douglas Gregor63798542012-02-20 19:44:39 +00008012unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
8013 CXXRecordDecl *Lambda = CallOperator->getParent();
8014 return LambdaMangleContexts[Lambda->getDeclContext()]
8015 .getManglingNumber(CallOperator);
8016}
8017
8018
Ted Kremenek540017e2011-10-06 05:00:56 +00008019void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8020 ParamIndices[D] = index;
8021}
8022
8023unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8024 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8025 assert(I != ParamIndices.end() &&
8026 "ParmIndices lacks entry set by ParmVarDecl");
8027 return I->second;
8028}