blob: 0d1dc4e4d176317e638bfcb29f11a87e712778e8 [file] [log] [blame]
Chris Lattnerddc135e2006-11-10 06:34:16 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerddc135e2006-11-10 06:34:16 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "CXXABI.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000016#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/Attr.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000018#include "clang/AST/CharUnits.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000019#include "clang/AST/Comment.h"
Dmitri Gribenkoca7f80a2012-08-09 00:03:17 +000020#include "clang/AST/CommentCommandTraits.h"
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +000021#include "clang/AST/DeclCXX.h"
Steve Naroff67391b82007-10-01 19:00:59 +000022#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000023#include "clang/AST/DeclTemplate.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000024#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000025#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000026#include "clang/AST/ExternalASTSource.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000027#include "clang/AST/Mangle.h"
Reid Klecknerd8110b62013-09-10 20:14:30 +000028#include "clang/AST/MangleNumberingContext.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000029#include "clang/AST/RecordLayout.h"
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000030#include "clang/AST/RecursiveASTVisitor.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000031#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000032#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000033#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000034#include "clang/Basic/TargetInfo.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000035#include "llvm/ADT/SmallString.h"
Anders Carlssond8499822007-10-29 05:01:08 +000036#include "llvm/ADT/StringExtras.h"
Robert Lyttoneaf6f362013-11-12 10:09:34 +000037#include "llvm/ADT/Triple.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000038#include "llvm/Support/Capacity.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000039#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000040#include "llvm/Support/raw_ostream.h"
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +000041#include <map>
Anders Carlssona4267a62009-07-18 21:19:52 +000042
Chris Lattnerddc135e2006-11-10 06:34:16 +000043using namespace clang;
44
Douglas Gregor9672f922010-07-03 00:47:00 +000045unsigned ASTContext::NumImplicitDefaultConstructors;
46unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000047unsigned ASTContext::NumImplicitCopyConstructors;
48unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000049unsigned ASTContext::NumImplicitMoveConstructors;
50unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +000051unsigned ASTContext::NumImplicitCopyAssignmentOperators;
52unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000053unsigned ASTContext::NumImplicitMoveAssignmentOperators;
54unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +000055unsigned ASTContext::NumImplicitDestructors;
56unsigned ASTContext::NumImplicitDestructorsDeclared;
57
Steve Naroff0af91202007-04-27 21:51:21 +000058enum FloatingRank {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +000059 HalfRank, FloatRank, DoubleRank, LongDoubleRank
Steve Naroff0af91202007-04-27 21:51:21 +000060};
61
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000062RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000063 if (!CommentsLoaded && ExternalSource) {
64 ExternalSource->ReadComments();
65 CommentsLoaded = true;
66 }
67
68 assert(D);
69
Dmitri Gribenkodf17d642012-06-28 16:19:39 +000070 // User can not attach documentation to implicit declarations.
71 if (D->isImplicit())
72 return NULL;
73
Dmitri Gribenkob2610882012-08-14 17:17:18 +000074 // User can not attach documentation to implicit instantiations.
75 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
76 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
77 return NULL;
78 }
79
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000080 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
81 if (VD->isStaticDataMember() &&
82 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
83 return NULL;
84 }
85
86 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
87 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
88 return NULL;
89 }
90
Dmitri Gribenko01b06512013-01-27 21:18:39 +000091 if (const ClassTemplateSpecializationDecl *CTSD =
92 dyn_cast<ClassTemplateSpecializationDecl>(D)) {
93 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
94 if (TSK == TSK_ImplicitInstantiation ||
95 TSK == TSK_Undeclared)
96 return NULL;
97 }
98
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000099 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
100 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
101 return NULL;
102 }
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000103 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
104 // When tag declaration (but not definition!) is part of the
105 // decl-specifier-seq of some other declaration, it doesn't get comment
106 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
107 return NULL;
108 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000109 // TODO: handle comments for function parameters properly.
110 if (isa<ParmVarDecl>(D))
111 return NULL;
112
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000113 // TODO: we could look up template parameter documentation in the template
114 // documentation.
115 if (isa<TemplateTypeParmDecl>(D) ||
116 isa<NonTypeTemplateParmDecl>(D) ||
117 isa<TemplateTemplateParmDecl>(D))
118 return NULL;
119
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000120 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000121
122 // If there are no comments anywhere, we won't find anything.
123 if (RawComments.empty())
124 return NULL;
125
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000126 // Find declaration location.
127 // For Objective-C declarations we generally don't expect to have multiple
128 // declarators, thus use declaration starting location as the "declaration
129 // location".
130 // For all other declarations multiple declarators are used quite frequently,
131 // so we use the location of the identifier as the "declaration location".
132 SourceLocation DeclLoc;
133 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000134 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +0000135 isa<RedeclarableTemplateDecl>(D) ||
136 isa<ClassTemplateSpecializationDecl>(D))
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000137 DeclLoc = D->getLocStart();
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000138 else {
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000139 DeclLoc = D->getLocation();
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000140 // If location of the typedef name is in a macro, it is because being
141 // declared via a macro. Try using declaration's starting location
142 // as the "declaration location".
143 if (DeclLoc.isMacroID() && isa<TypedefDecl>(D))
144 DeclLoc = D->getLocStart();
145 }
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000146
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000147 // If the declaration doesn't map directly to a location in a file, we
148 // can't find the comment.
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000149 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
150 return NULL;
151
152 // Find the comment that occurs just after this declaration.
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000153 ArrayRef<RawComment *>::iterator Comment;
154 {
155 // When searching for comments during parsing, the comment we are looking
156 // for is usually among the last two comments we parsed -- check them
157 // first.
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +0000158 RawComment CommentAtDeclLoc(
159 SourceMgr, SourceRange(DeclLoc), false,
160 LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000161 BeforeThanCompare<RawComment> Compare(SourceMgr);
162 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
163 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
164 if (!Found && RawComments.size() >= 2) {
165 MaybeBeforeDecl--;
166 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
167 }
168
169 if (Found) {
170 Comment = MaybeBeforeDecl + 1;
171 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
172 &CommentAtDeclLoc, Compare));
173 } else {
174 // Slow path.
175 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
176 &CommentAtDeclLoc, Compare);
177 }
178 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000179
180 // Decompose the location for the declaration and find the beginning of the
181 // file buffer.
182 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
183
184 // First check whether we have a trailing comment.
185 if (Comment != RawComments.end() &&
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000186 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
Fariborz Jahanianfad28542013-08-06 23:29:00 +0000187 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
Fariborz Jahanian3ab62222013-08-07 16:40:29 +0000188 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000189 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000190 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000191 // Check that Doxygen trailing comment comes after the declaration, starts
192 // on the same line and in the same file as the declaration.
193 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
194 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
195 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
196 CommentBeginDecomp.second)) {
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000197 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000198 }
199 }
200
201 // The comment just after the declaration was not a trailing comment.
202 // Let's look at the previous comment.
203 if (Comment == RawComments.begin())
204 return NULL;
205 --Comment;
206
207 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000208 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000209 return NULL;
210
211 // Decompose the end of the comment.
212 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000213 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000214
215 // If the comment and the declaration aren't in the same file, then they
216 // aren't related.
217 if (DeclLocDecomp.first != CommentEndDecomp.first)
218 return NULL;
219
220 // Get the corresponding buffer.
221 bool Invalid = false;
222 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
223 &Invalid).data();
224 if (Invalid)
225 return NULL;
226
227 // Extract text between the comment and declaration.
228 StringRef Text(Buffer + CommentEndDecomp.second,
229 DeclLocDecomp.second - CommentEndDecomp.second);
230
Dmitri Gribenko7e8729b2012-06-27 23:43:37 +0000231 // There should be no other declarations or preprocessor directives between
232 // comment and declaration.
Argyrios Kyrtzidisb534d3a2013-07-26 18:38:12 +0000233 if (Text.find_first_of(";{}#@") != StringRef::npos)
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000234 return NULL;
235
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000236 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000237}
238
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000239namespace {
240/// If we have a 'templated' declaration for a template, adjust 'D' to
241/// refer to the actual template.
Dmitri Gribenko90631802012-08-22 17:44:32 +0000242/// If we have an implicit instantiation, adjust 'D' to refer to template.
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000243const Decl *adjustDeclToTemplate(const Decl *D) {
Douglas Gregor35ceb272012-08-13 16:37:30 +0000244 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000245 // Is this function declaration part of a function template?
Douglas Gregor35ceb272012-08-13 16:37:30 +0000246 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko90631802012-08-22 17:44:32 +0000247 return FTD;
248
249 // Nothing to do if function is not an implicit instantiation.
250 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
251 return D;
252
253 // Function is an implicit instantiation of a function template?
254 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
255 return FTD;
256
257 // Function is instantiated from a member definition of a class template?
258 if (const FunctionDecl *MemberDecl =
259 FD->getInstantiatedFromMemberFunction())
260 return MemberDecl;
261
262 return D;
Douglas Gregor35ceb272012-08-13 16:37:30 +0000263 }
Dmitri Gribenko90631802012-08-22 17:44:32 +0000264 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
265 // Static data member is instantiated from a member definition of a class
266 // template?
267 if (VD->isStaticDataMember())
268 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
269 return MemberDecl;
270
271 return D;
272 }
273 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
274 // Is this class declaration part of a class template?
275 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
276 return CTD;
277
278 // Class is an implicit instantiation of a class template or partial
279 // specialization?
280 if (const ClassTemplateSpecializationDecl *CTSD =
281 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
282 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
283 return D;
284 llvm::PointerUnion<ClassTemplateDecl *,
285 ClassTemplatePartialSpecializationDecl *>
286 PU = CTSD->getSpecializedTemplateOrPartial();
287 return PU.is<ClassTemplateDecl*>() ?
288 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
289 static_cast<const Decl*>(
290 PU.get<ClassTemplatePartialSpecializationDecl *>());
291 }
292
293 // Class is instantiated from a member definition of a class template?
294 if (const MemberSpecializationInfo *Info =
295 CRD->getMemberSpecializationInfo())
296 return Info->getInstantiatedFrom();
297
298 return D;
299 }
300 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
301 // Enum is instantiated from a member definition of a class template?
302 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
303 return MemberDecl;
304
305 return D;
306 }
307 // FIXME: Adjust alias templates?
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000308 return D;
309}
310} // unnamed namespace
311
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000312const RawComment *ASTContext::getRawCommentForAnyRedecl(
313 const Decl *D,
314 const Decl **OriginalDecl) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000315 D = adjustDeclToTemplate(D);
Douglas Gregor35ceb272012-08-13 16:37:30 +0000316
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000317 // Check whether we have cached a comment for this declaration already.
318 {
319 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
320 RedeclComments.find(D);
321 if (Pos != RedeclComments.end()) {
322 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000323 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
324 if (OriginalDecl)
325 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000326 return Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000327 }
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000328 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000329 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000330
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000331 // Search for comments attached to declarations in the redeclaration chain.
332 const RawComment *RC = NULL;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000333 const Decl *OriginalDeclForRC = NULL;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000334 for (Decl::redecl_iterator I = D->redecls_begin(),
335 E = D->redecls_end();
336 I != E; ++I) {
337 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
338 RedeclComments.find(*I);
339 if (Pos != RedeclComments.end()) {
340 const RawCommentAndCacheFlags &Raw = Pos->second;
341 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
342 RC = Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000343 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000344 break;
345 }
346 } else {
347 RC = getRawCommentForDeclNoCache(*I);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000348 OriginalDeclForRC = *I;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000349 RawCommentAndCacheFlags Raw;
350 if (RC) {
351 Raw.setRaw(RC);
352 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
353 } else
354 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000355 Raw.setOriginalDecl(*I);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000356 RedeclComments[*I] = Raw;
357 if (RC)
358 break;
359 }
360 }
361
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000362 // If we found a comment, it should be a documentation comment.
363 assert(!RC || RC->isDocumentation());
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000364
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000365 if (OriginalDecl)
366 *OriginalDecl = OriginalDeclForRC;
367
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000368 // Update cache for every declaration in the redeclaration chain.
369 RawCommentAndCacheFlags Raw;
370 Raw.setRaw(RC);
371 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000372 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000373
374 for (Decl::redecl_iterator I = D->redecls_begin(),
375 E = D->redecls_end();
376 I != E; ++I) {
377 RawCommentAndCacheFlags &R = RedeclComments[*I];
378 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
379 R = Raw;
380 }
381
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000382 return RC;
383}
384
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000385static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
386 SmallVectorImpl<const NamedDecl *> &Redeclared) {
387 const DeclContext *DC = ObjCMethod->getDeclContext();
388 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
389 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
390 if (!ID)
391 return;
392 // Add redeclared method here.
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000393 for (ObjCInterfaceDecl::known_extensions_iterator
394 Ext = ID->known_extensions_begin(),
395 ExtEnd = ID->known_extensions_end();
396 Ext != ExtEnd; ++Ext) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000397 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000398 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000399 ObjCMethod->isInstanceMethod()))
400 Redeclared.push_back(RedeclaredMethod);
401 }
402 }
403}
404
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000405comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
406 const Decl *D) const {
407 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
408 ThisDeclInfo->CommentDecl = D;
409 ThisDeclInfo->IsFilled = false;
410 ThisDeclInfo->fill();
411 ThisDeclInfo->CommentDecl = FC->getDecl();
412 comments::FullComment *CFC =
413 new (*this) comments::FullComment(FC->getBlocks(),
414 ThisDeclInfo);
415 return CFC;
416
417}
418
Richard Smithb39b9d52013-05-21 05:24:00 +0000419comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
420 const RawComment *RC = getRawCommentForDeclNoCache(D);
421 return RC ? RC->parse(*this, 0, D) : 0;
422}
423
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000424comments::FullComment *ASTContext::getCommentForDecl(
425 const Decl *D,
426 const Preprocessor *PP) const {
Fariborz Jahanian096f7c12013-05-13 17:27:00 +0000427 if (D->isInvalidDecl())
428 return NULL;
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000429 D = adjustDeclToTemplate(D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000430
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000431 const Decl *Canonical = D->getCanonicalDecl();
432 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
433 ParsedComments.find(Canonical);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000434
435 if (Pos != ParsedComments.end()) {
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000436 if (Canonical != D) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000437 comments::FullComment *FC = Pos->second;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000438 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000439 return CFC;
440 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000441 return Pos->second;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000442 }
443
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000444 const Decl *OriginalDecl;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000445
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000446 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000447 if (!RC) {
448 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000449 SmallVector<const NamedDecl*, 8> Overridden;
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000450 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000451 if (OMD && OMD->isPropertyAccessor())
452 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
453 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
454 return cloneFullComment(FC, D);
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000455 if (OMD)
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000456 addRedeclaredMethods(OMD, Overridden);
457 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000458 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
459 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
460 return cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000461 }
Fariborz Jahanian6384fbb2013-05-02 15:44:16 +0000462 else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000463 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000464 // does not have one of its own.
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000465 QualType QT = TD->getUnderlyingType();
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000466 if (const TagType *TT = QT->getAs<TagType>())
467 if (const Decl *TD = TT->getDecl())
468 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000469 return cloneFullComment(FC, D);
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000470 }
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000471 else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
472 while (IC->getSuperClass()) {
473 IC = IC->getSuperClass();
474 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
475 return cloneFullComment(FC, D);
476 }
477 }
478 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
479 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
480 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
481 return cloneFullComment(FC, D);
482 }
483 else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
484 if (!(RD = RD->getDefinition()))
485 return NULL;
486 // Check non-virtual bases.
487 for (CXXRecordDecl::base_class_const_iterator I =
488 RD->bases_begin(), E = RD->bases_end(); I != E; ++I) {
Fariborz Jahanian5a2e4a22013-04-26 23:34:36 +0000489 if (I->isVirtual() || (I->getAccessSpecifier() != AS_public))
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000490 continue;
491 QualType Ty = I->getType();
492 if (Ty.isNull())
493 continue;
494 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
495 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
496 continue;
497
498 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
499 return cloneFullComment(FC, D);
500 }
501 }
502 // Check virtual bases.
503 for (CXXRecordDecl::base_class_const_iterator I =
504 RD->vbases_begin(), E = RD->vbases_end(); I != E; ++I) {
Fariborz Jahanian5a2e4a22013-04-26 23:34:36 +0000505 if (I->getAccessSpecifier() != AS_public)
506 continue;
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000507 QualType Ty = I->getType();
508 if (Ty.isNull())
509 continue;
510 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
511 if (!(VirtualBase= VirtualBase->getDefinition()))
512 continue;
513 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
514 return cloneFullComment(FC, D);
515 }
516 }
517 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000518 return NULL;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000519 }
520
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000521 // If the RawComment was attached to other redeclaration of this Decl, we
522 // should parse the comment in context of that other Decl. This is important
523 // because comments can contain references to parameter names which can be
524 // different across redeclarations.
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000525 if (D != OriginalDecl)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000526 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000527
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000528 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000529 ParsedComments[Canonical] = FC;
530 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000531}
532
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000533void
534ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
535 TemplateTemplateParmDecl *Parm) {
536 ID.AddInteger(Parm->getDepth());
537 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000538 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000539
540 TemplateParameterList *Params = Parm->getTemplateParameters();
541 ID.AddInteger(Params->size());
542 for (TemplateParameterList::const_iterator P = Params->begin(),
543 PEnd = Params->end();
544 P != PEnd; ++P) {
545 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
546 ID.AddInteger(0);
547 ID.AddBoolean(TTP->isParameterPack());
548 continue;
549 }
550
551 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
552 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000553 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000554 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000555 if (NTTP->isExpandedParameterPack()) {
556 ID.AddBoolean(true);
557 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000558 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
559 QualType T = NTTP->getExpansionType(I);
560 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
561 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000562 } else
563 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000564 continue;
565 }
566
567 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
568 ID.AddInteger(2);
569 Profile(ID, TTP);
570 }
571}
572
573TemplateTemplateParmDecl *
574ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000575 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000576 // Check if we already have a canonical template template parameter.
577 llvm::FoldingSetNodeID ID;
578 CanonicalTemplateTemplateParm::Profile(ID, TTP);
579 void *InsertPos = 0;
580 CanonicalTemplateTemplateParm *Canonical
581 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
582 if (Canonical)
583 return Canonical->getParam();
584
585 // Build a canonical template parameter list.
586 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000587 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000588 CanonParams.reserve(Params->size());
589 for (TemplateParameterList::const_iterator P = Params->begin(),
590 PEnd = Params->end();
591 P != PEnd; ++P) {
592 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
593 CanonParams.push_back(
594 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000595 SourceLocation(),
596 SourceLocation(),
597 TTP->getDepth(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000598 TTP->getIndex(), 0, false,
599 TTP->isParameterPack()));
600 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000601 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
602 QualType T = getCanonicalType(NTTP->getType());
603 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
604 NonTypeTemplateParmDecl *Param;
605 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000606 SmallVector<QualType, 2> ExpandedTypes;
607 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000608 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
609 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
610 ExpandedTInfos.push_back(
611 getTrivialTypeSourceInfo(ExpandedTypes.back()));
612 }
613
614 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000615 SourceLocation(),
616 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000617 NTTP->getDepth(),
618 NTTP->getPosition(), 0,
619 T,
620 TInfo,
621 ExpandedTypes.data(),
622 ExpandedTypes.size(),
623 ExpandedTInfos.data());
624 } else {
625 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000626 SourceLocation(),
627 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000628 NTTP->getDepth(),
629 NTTP->getPosition(), 0,
630 T,
631 NTTP->isParameterPack(),
632 TInfo);
633 }
634 CanonParams.push_back(Param);
635
636 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000637 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
638 cast<TemplateTemplateParmDecl>(*P)));
639 }
640
641 TemplateTemplateParmDecl *CanonTTP
642 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
643 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000644 TTP->getPosition(),
645 TTP->isParameterPack(),
646 0,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000647 TemplateParameterList::Create(*this, SourceLocation(),
648 SourceLocation(),
649 CanonParams.data(),
650 CanonParams.size(),
651 SourceLocation()));
652
653 // Get the new insert position for the node we care about.
654 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
655 assert(Canonical == 0 && "Shouldn't be in the map!");
656 (void)Canonical;
657
658 // Create the canonical template template parameter entry.
659 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
660 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
661 return CanonTTP;
662}
663
Charles Davis53c59df2010-08-16 03:33:14 +0000664CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000665 if (!LangOpts.CPlusPlus) return 0;
666
John McCall359b8852013-01-25 22:30:49 +0000667 switch (T.getCXXABI().getKind()) {
668 case TargetCXXABI::GenericARM:
669 case TargetCXXABI::iOS:
John McCall86353412010-08-21 22:46:04 +0000670 return CreateARMCXXABI(*this);
Tim Northover9bb857a2013-01-31 12:13:10 +0000671 case TargetCXXABI::GenericAArch64: // Same as Itanium at this level
John McCall359b8852013-01-25 22:30:49 +0000672 case TargetCXXABI::GenericItanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000673 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000674 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000675 return CreateMicrosoftCXXABI(*this);
676 }
David Blaikie8a40f702012-01-17 06:56:22 +0000677 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000678}
679
Douglas Gregore8bbc122011-09-02 00:18:52 +0000680static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000681 const LangOptions &LOpts) {
682 if (LOpts.FakeAddressSpaceMap) {
683 // The fake address space map must have a distinct entry for each
684 // language-specific address space.
685 static const unsigned FakeAddrSpaceMap[] = {
686 1, // opencl_global
687 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000688 3, // opencl_constant
689 4, // cuda_device
690 5, // cuda_constant
691 6 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000692 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000693 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000694 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000695 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000696 }
697}
698
David Tweed31d09b02013-09-13 12:04:22 +0000699static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
700 const LangOptions &LangOpts) {
701 switch (LangOpts.getAddressSpaceMapMangling()) {
David Tweed31d09b02013-09-13 12:04:22 +0000702 case LangOptions::ASMM_Target:
703 return TI.useAddressSpaceMapMangling();
704 case LangOptions::ASMM_On:
705 return true;
706 case LangOptions::ASMM_Off:
707 return false;
708 }
NAKAMURA Takumi5c81ca42013-09-13 17:12:09 +0000709 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
David Tweed31d09b02013-09-13 12:04:22 +0000710}
711
Douglas Gregor7018d5b2011-09-01 20:23:19 +0000712ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000713 const TargetInfo *t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000714 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000715 Builtin::Context &builtins,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000716 unsigned size_reserve,
717 bool DelayInitialization)
718 : FunctionProtoTypes(this_()),
719 TemplateSpecializationTypes(this_()),
720 DependentTemplateSpecializationTypes(this_()),
721 SubstTemplateTemplateParmPacks(this_()),
722 GlobalNestedNameSpecifier(0),
Nico Webere1687c52013-06-20 21:44:55 +0000723 Int128Decl(0), UInt128Decl(0), Float128StubDecl(0),
Meador Inge5d3fb222012-06-16 03:34:49 +0000724 BuiltinVaListDecl(0),
Douglas Gregord53ae832012-01-17 18:09:05 +0000725 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Fariborz Jahanianf2578572012-08-30 18:49:41 +0000726 BOOLDecl(0),
Douglas Gregorbab8a962011-09-08 01:46:34 +0000727 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000728 FILEDecl(0),
Rafael Espindola6cfa82b2011-11-13 21:51:09 +0000729 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
730 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
731 cudaConfigureCallDecl(0),
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000732 NullTypeSourceInfo(QualType()),
733 FirstLocalImport(), LastLocalImport(),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000734 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000735 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000736 Idents(idents), Selectors(sels),
737 BuiltinInfo(builtins),
738 DeclarationNames(*this),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000739 ExternalSource(0), Listener(0),
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000740 Comments(SM), CommentsLoaded(false),
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000741 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
Rafael Espindolace2168f2013-05-29 19:51:12 +0000742 LastSDM(0, 0)
Douglas Gregore8bbc122011-09-02 00:18:52 +0000743{
Mike Stump11289f42009-09-09 15:08:12 +0000744 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000745 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000746
747 if (!DelayInitialization) {
748 assert(t && "No target supplied for ASTContext initialization");
749 InitBuiltinTypes(*t);
750 }
Daniel Dunbar221fa942008-08-11 04:54:23 +0000751}
752
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000753ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000754 // Release the DenseMaps associated with DeclContext objects.
755 // FIXME: Is this the ideal solution?
756 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000757
Manuel Klimeka7328992013-06-03 13:51:33 +0000758 // Call all of the deallocation functions on all of their targets.
759 for (DeallocationMap::const_iterator I = Deallocations.begin(),
760 E = Deallocations.end(); I != E; ++I)
761 for (unsigned J = 0, N = I->second.size(); J != N; ++J)
762 (I->first)((I->second)[J]);
763
Ted Kremenek076baeb2010-06-08 23:00:58 +0000764 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000765 // because they can contain DenseMaps.
766 for (llvm::DenseMap<const ObjCContainerDecl*,
767 const ASTRecordLayout*>::iterator
768 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
769 // Increment in loop to prevent using deallocated memory.
770 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
771 R->Destroy(*this);
772
Ted Kremenek076baeb2010-06-08 23:00:58 +0000773 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
774 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
775 // Increment in loop to prevent using deallocated memory.
776 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
777 R->Destroy(*this);
778 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000779
780 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
781 AEnd = DeclAttrs.end();
782 A != AEnd; ++A)
783 A->second->~AttrVec();
Reid Klecknerd8110b62013-09-10 20:14:30 +0000784
785 for (llvm::DenseMap<const DeclContext *, MangleNumberingContext *>::iterator
786 I = MangleNumberingContexts.begin(),
787 E = MangleNumberingContexts.end();
788 I != E; ++I)
789 delete I->second;
Douglas Gregor561eceb2010-08-30 16:49:28 +0000790}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000791
Douglas Gregor1a809332010-05-23 18:26:36 +0000792void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Manuel Klimeka7328992013-06-03 13:51:33 +0000793 Deallocations[Callback].push_back(Data);
Douglas Gregor1a809332010-05-23 18:26:36 +0000794}
795
Mike Stump11289f42009-09-09 15:08:12 +0000796void
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000797ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000798 ExternalSource.reset(Source.take());
799}
800
Chris Lattner4eb445d2007-01-26 01:27:23 +0000801void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000802 llvm::errs() << "\n*** AST Context Stats:\n";
803 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000804
Douglas Gregora30d0462009-05-26 14:40:08 +0000805 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000806#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000807#define ABSTRACT_TYPE(Name, Parent)
808#include "clang/AST/TypeNodes.def"
809 0 // Extra
810 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000811
Chris Lattner4eb445d2007-01-26 01:27:23 +0000812 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
813 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000814 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000815 }
816
Douglas Gregora30d0462009-05-26 14:40:08 +0000817 unsigned Idx = 0;
818 unsigned TotalBytes = 0;
819#define TYPE(Name, Parent) \
820 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000821 llvm::errs() << " " << counts[Idx] << " " << #Name \
822 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000823 TotalBytes += counts[Idx] * sizeof(Name##Type); \
824 ++Idx;
825#define ABSTRACT_TYPE(Name, Parent)
826#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000827
Chandler Carruth3c147a72011-07-04 05:32:14 +0000828 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
829
Douglas Gregor7454c562010-07-02 20:37:36 +0000830 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000831 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
832 << NumImplicitDefaultConstructors
833 << " implicit default constructors created\n";
834 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
835 << NumImplicitCopyConstructors
836 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000837 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000838 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
839 << NumImplicitMoveConstructors
840 << " implicit move constructors created\n";
841 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
842 << NumImplicitCopyAssignmentOperators
843 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000844 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000845 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
846 << NumImplicitMoveAssignmentOperators
847 << " implicit move assignment operators created\n";
848 llvm::errs() << NumImplicitDestructorsDeclared << "/"
849 << NumImplicitDestructors
850 << " implicit destructors created\n";
851
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000852 if (ExternalSource.get()) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000853 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000854 ExternalSource->PrintStats();
855 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000856
Douglas Gregor5b11d492010-07-25 17:53:33 +0000857 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000858}
859
Douglas Gregor801c99d2011-08-12 06:49:56 +0000860TypedefDecl *ASTContext::getInt128Decl() const {
861 if (!Int128Decl) {
862 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
863 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
864 getTranslationUnitDecl(),
865 SourceLocation(),
866 SourceLocation(),
867 &Idents.get("__int128_t"),
868 TInfo);
869 }
870
871 return Int128Decl;
872}
873
874TypedefDecl *ASTContext::getUInt128Decl() const {
875 if (!UInt128Decl) {
876 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
877 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
878 getTranslationUnitDecl(),
879 SourceLocation(),
880 SourceLocation(),
881 &Idents.get("__uint128_t"),
882 TInfo);
883 }
884
885 return UInt128Decl;
886}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000887
Nico Webere1687c52013-06-20 21:44:55 +0000888TypeDecl *ASTContext::getFloat128StubType() const {
Nico Weber5b0b46f2013-06-21 01:29:36 +0000889 assert(LangOpts.CPlusPlus && "should only be called for c++");
Nico Webere1687c52013-06-20 21:44:55 +0000890 if (!Float128StubDecl) {
Nico Weber95296d42013-06-20 23:30:30 +0000891 Float128StubDecl = CXXRecordDecl::Create(const_cast<ASTContext &>(*this),
892 TTK_Struct,
893 getTranslationUnitDecl(),
894 SourceLocation(),
895 SourceLocation(),
896 &Idents.get("__float128"));
Nico Webere1687c52013-06-20 21:44:55 +0000897 }
898
899 return Float128StubDecl;
900}
901
John McCall48f2d582009-10-23 23:03:21 +0000902void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000903 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000904 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000905 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000906}
907
Douglas Gregore8bbc122011-09-02 00:18:52 +0000908void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
909 assert((!this->Target || this->Target == &Target) &&
910 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000911 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000912
Douglas Gregore8bbc122011-09-02 00:18:52 +0000913 this->Target = &Target;
914
915 ABI.reset(createCXXABI(Target));
916 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +0000917 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000918
Chris Lattner970e54e2006-11-12 00:37:36 +0000919 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000920 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000921
Chris Lattner970e54e2006-11-12 00:37:36 +0000922 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000923 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000924 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000925 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000926 InitBuiltinType(CharTy, BuiltinType::Char_S);
927 else
928 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000929 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000930 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
931 InitBuiltinType(ShortTy, BuiltinType::Short);
932 InitBuiltinType(IntTy, BuiltinType::Int);
933 InitBuiltinType(LongTy, BuiltinType::Long);
934 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000935
Chris Lattner970e54e2006-11-12 00:37:36 +0000936 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000937 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
938 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
939 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
940 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
941 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000942
Chris Lattner970e54e2006-11-12 00:37:36 +0000943 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000944 InitBuiltinType(FloatTy, BuiltinType::Float);
945 InitBuiltinType(DoubleTy, BuiltinType::Double);
946 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000947
Chris Lattnerf122cef2009-04-30 02:43:43 +0000948 // GNU extension, 128-bit integers.
949 InitBuiltinType(Int128Ty, BuiltinType::Int128);
950 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
951
Hans Wennborg0d81e012013-05-10 10:08:40 +0000952 // C++ 3.9.1p5
953 if (TargetInfo::isTypeSigned(Target.getWCharType()))
954 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
955 else // -fshort-wchar makes wchar_t be unsigned.
956 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
957 if (LangOpts.CPlusPlus && LangOpts.WChar)
958 WideCharTy = WCharTy;
959 else {
960 // C99 (or C++ using -fno-wchar).
961 WideCharTy = getFromTargetType(Target.getWCharType());
962 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000963
James Molloy36365542012-05-04 10:55:22 +0000964 WIntTy = getFromTargetType(Target.getWIntType());
965
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000966 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
967 InitBuiltinType(Char16Ty, BuiltinType::Char16);
968 else // C99
969 Char16Ty = getFromTargetType(Target.getChar16Type());
970
971 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
972 InitBuiltinType(Char32Ty, BuiltinType::Char32);
973 else // C99
974 Char32Ty = getFromTargetType(Target.getChar32Type());
975
Douglas Gregor4619e432008-12-05 23:32:09 +0000976 // Placeholder type for type-dependent expressions whose type is
977 // completely unknown. No code should ever check a type against
978 // DependentTy and users should never see it; however, it is here to
979 // help diagnose failures to properly check for type-dependent
980 // expressions.
981 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000982
John McCall36e7fe32010-10-12 00:20:44 +0000983 // Placeholder type for functions.
984 InitBuiltinType(OverloadTy, BuiltinType::Overload);
985
John McCall0009fcc2011-04-26 20:42:42 +0000986 // Placeholder type for bound members.
987 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
988
John McCall526ab472011-10-25 17:37:35 +0000989 // Placeholder type for pseudo-objects.
990 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
991
John McCall31996342011-04-07 08:22:57 +0000992 // "any" type; useful for debugger-like clients.
993 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
994
John McCall8a6b59a2011-10-17 18:09:15 +0000995 // Placeholder type for unbridged ARC casts.
996 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
997
Eli Friedman34866c72012-08-31 00:14:07 +0000998 // Placeholder type for builtin functions.
999 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1000
Chris Lattner970e54e2006-11-12 00:37:36 +00001001 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +00001002 FloatComplexTy = getComplexType(FloatTy);
1003 DoubleComplexTy = getComplexType(DoubleTy);
1004 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001005
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001006 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001007 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1008 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001009 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001010
1011 if (LangOpts.OpenCL) {
1012 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
1013 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
1014 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
1015 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
1016 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
1017 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001018
Guy Benyei61054192013-02-07 10:55:47 +00001019 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001020 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001021 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001022
1023 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001024 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1025 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001026
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001027 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001028
1029 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001030
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001031 // void * type
1032 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +00001033
1034 // nullptr type (C++0x 2.14.7)
1035 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001036
1037 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1038 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001039
1040 // Builtin type used to help define __builtin_va_list.
1041 VaListTagTy = QualType();
Chris Lattner970e54e2006-11-12 00:37:36 +00001042}
1043
David Blaikie9c902b52011-09-25 23:23:43 +00001044DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001045 return SourceMgr.getDiagnostics();
1046}
1047
Douglas Gregor561eceb2010-08-30 16:49:28 +00001048AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1049 AttrVec *&Result = DeclAttrs[D];
1050 if (!Result) {
1051 void *Mem = Allocate(sizeof(AttrVec));
1052 Result = new (Mem) AttrVec;
1053 }
1054
1055 return *Result;
1056}
1057
1058/// \brief Erase the attributes corresponding to the given declaration.
1059void ASTContext::eraseDeclAttrs(const Decl *D) {
1060 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1061 if (Pos != DeclAttrs.end()) {
1062 Pos->second->~AttrVec();
1063 DeclAttrs.erase(Pos);
1064 }
1065}
1066
Larisse Voufo39a1e502013-08-06 01:03:05 +00001067// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001068MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001069ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001070 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001071 return getTemplateOrSpecializationInfo(Var)
1072 .dyn_cast<MemberSpecializationInfo *>();
1073}
1074
1075ASTContext::TemplateOrSpecializationInfo
1076ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1077 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1078 TemplateOrInstantiation.find(Var);
1079 if (Pos == TemplateOrInstantiation.end())
1080 return TemplateOrSpecializationInfo();
Mike Stump11289f42009-09-09 15:08:12 +00001081
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001082 return Pos->second;
1083}
1084
Mike Stump11289f42009-09-09 15:08:12 +00001085void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001086ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001087 TemplateSpecializationKind TSK,
1088 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001089 assert(Inst->isStaticDataMember() && "Not a static data member");
1090 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001091 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1092 Tmpl, TSK, PointOfInstantiation));
1093}
1094
1095void
1096ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1097 TemplateOrSpecializationInfo TSI) {
1098 assert(!TemplateOrInstantiation[Inst] &&
1099 "Already noted what the variable was instantiated from");
1100 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001101}
1102
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001103FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1104 const FunctionDecl *FD){
1105 assert(FD && "Specialization is 0");
1106 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001107 = ClassScopeSpecializationPattern.find(FD);
1108 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001109 return 0;
1110
1111 return Pos->second;
1112}
1113
1114void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1115 FunctionDecl *Pattern) {
1116 assert(FD && "Specialization is 0");
1117 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001118 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001119}
1120
John McCalle61f2ba2009-11-18 02:36:19 +00001121NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +00001122ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +00001123 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +00001124 = InstantiatedFromUsingDecl.find(UUD);
1125 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001126 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001127
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001128 return Pos->second;
1129}
1130
1131void
John McCallb96ec562009-12-04 22:46:56 +00001132ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1133 assert((isa<UsingDecl>(Pattern) ||
1134 isa<UnresolvedUsingValueDecl>(Pattern) ||
1135 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1136 "pattern decl is not a using decl");
1137 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1138 InstantiatedFromUsingDecl[Inst] = Pattern;
1139}
1140
1141UsingShadowDecl *
1142ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1143 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1144 = InstantiatedFromUsingShadowDecl.find(Inst);
1145 if (Pos == InstantiatedFromUsingShadowDecl.end())
1146 return 0;
1147
1148 return Pos->second;
1149}
1150
1151void
1152ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1153 UsingShadowDecl *Pattern) {
1154 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1155 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001156}
1157
Anders Carlsson5da84842009-09-01 04:26:58 +00001158FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1159 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1160 = InstantiatedFromUnnamedFieldDecl.find(Field);
1161 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1162 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001163
Anders Carlsson5da84842009-09-01 04:26:58 +00001164 return Pos->second;
1165}
1166
1167void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1168 FieldDecl *Tmpl) {
1169 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1170 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1171 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1172 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001173
Anders Carlsson5da84842009-09-01 04:26:58 +00001174 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1175}
1176
Douglas Gregor832940b2010-03-02 23:58:15 +00001177ASTContext::overridden_cxx_method_iterator
1178ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1179 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001180 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001181 if (Pos == OverriddenMethods.end())
1182 return 0;
1183
1184 return Pos->second.begin();
1185}
1186
1187ASTContext::overridden_cxx_method_iterator
1188ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1189 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001190 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001191 if (Pos == OverriddenMethods.end())
1192 return 0;
1193
1194 return Pos->second.end();
1195}
1196
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001197unsigned
1198ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1199 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001200 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001201 if (Pos == OverriddenMethods.end())
1202 return 0;
1203
1204 return Pos->second.size();
1205}
1206
Douglas Gregor832940b2010-03-02 23:58:15 +00001207void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1208 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001209 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001210 OverriddenMethods[Method].push_back(Overridden);
1211}
1212
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001213void ASTContext::getOverriddenMethods(
1214 const NamedDecl *D,
1215 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001216 assert(D);
1217
1218 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001219 Overridden.append(overridden_methods_begin(CXXMethod),
1220 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001221 return;
1222 }
1223
1224 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1225 if (!Method)
1226 return;
1227
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001228 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1229 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001230 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001231}
1232
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001233void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1234 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1235 assert(!Import->isFromASTFile() && "Non-local import declaration");
1236 if (!FirstLocalImport) {
1237 FirstLocalImport = Import;
1238 LastLocalImport = Import;
1239 return;
1240 }
1241
1242 LastLocalImport->NextLocalImport = Import;
1243 LastLocalImport = Import;
1244}
1245
Chris Lattner53cfe802007-07-18 17:52:12 +00001246//===----------------------------------------------------------------------===//
1247// Type Sizing and Analysis
1248//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001249
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001250/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1251/// scalar floating point type.
1252const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001253 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001254 assert(BT && "Not a floating point type!");
1255 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001256 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001257 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001258 case BuiltinType::Float: return Target->getFloatFormat();
1259 case BuiltinType::Double: return Target->getDoubleFormat();
1260 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001261 }
1262}
1263
Rafael Espindola71eccb32013-08-08 19:53:46 +00001264CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001265 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001266
John McCall94268702010-10-08 18:24:19 +00001267 bool UseAlignAttrOnly = false;
1268 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1269 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001270
John McCall94268702010-10-08 18:24:19 +00001271 // __attribute__((aligned)) can increase or decrease alignment
1272 // *except* on a struct or struct member, where it only increases
1273 // alignment unless 'packed' is also specified.
1274 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001275 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001276 // ignore that possibility; Sema should diagnose it.
1277 if (isa<FieldDecl>(D)) {
1278 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1279 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1280 } else {
1281 UseAlignAttrOnly = true;
1282 }
1283 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001284 else if (isa<FieldDecl>(D))
1285 UseAlignAttrOnly =
1286 D->hasAttr<PackedAttr>() ||
1287 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001288
John McCall4e819612011-01-20 07:57:12 +00001289 // If we're using the align attribute only, just ignore everything
1290 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001291 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001292 // do nothing
1293
John McCall94268702010-10-08 18:24:19 +00001294 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001295 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001296 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001297 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001298 T = RT->getPointeeType();
1299 else
1300 T = getPointerType(RT->getPointeeType());
1301 }
1302 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +00001303 // Adjust alignments of declarations with array type by the
1304 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001305 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001306 unsigned MinWidth = Target->getLargeArrayMinWidth();
1307 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001308 if (isa<VariableArrayType>(arrayType))
1309 Align = std::max(Align, Target->getLargeArrayAlign());
1310 else if (isa<ConstantArrayType>(arrayType) &&
1311 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1312 Align = std::max(Align, Target->getLargeArrayAlign());
1313 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001314
John McCall33ddac02011-01-19 10:06:00 +00001315 // Walk through any array types while we're at it.
1316 T = getBaseElementType(arrayType);
1317 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001318 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Ulrich Weigandfa806422013-05-06 16:23:57 +00001319 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1320 if (VD->hasGlobalStorage())
1321 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1322 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001323 }
John McCall4e819612011-01-20 07:57:12 +00001324
1325 // Fields can be subject to extra alignment constraints, like if
1326 // the field is packed, the struct is packed, or the struct has a
1327 // a max-field-alignment constraint (#pragma pack). So calculate
1328 // the actual alignment of the field within the struct, and then
1329 // (as we're expected to) constrain that by the alignment of the type.
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001330 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1331 const RecordDecl *Parent = Field->getParent();
1332 // We can only produce a sensible answer if the record is valid.
1333 if (!Parent->isInvalidDecl()) {
1334 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001335
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001336 // Start with the record's overall alignment.
1337 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001338
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001339 // Use the GCD of that and the offset within the record.
1340 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1341 if (Offset > 0) {
1342 // Alignment is always a power of 2, so the GCD will be a power of 2,
1343 // which means we get to do this crazy thing instead of Euclid's.
1344 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1345 if (LowBitOfOffset < FieldAlign)
1346 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1347 }
1348
1349 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001350 }
Charles Davis3fc51072010-02-23 04:52:00 +00001351 }
Chris Lattner68061312009-01-24 21:53:27 +00001352 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001353
Ken Dyckcc56c542011-01-15 18:38:59 +00001354 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001355}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001356
John McCallf1249922012-08-21 04:10:00 +00001357// getTypeInfoDataSizeInChars - Return the size of a type, in
1358// chars. If the type is a record, its data size is returned. This is
1359// the size of the memcpy that's performed when assigning this type
1360// using a trivial copy/move assignment operator.
1361std::pair<CharUnits, CharUnits>
1362ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1363 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1364
1365 // In C++, objects can sometimes be allocated into the tail padding
1366 // of a base-class subobject. We decide whether that's possible
1367 // during class layout, so here we can just trust the layout results.
1368 if (getLangOpts().CPlusPlus) {
1369 if (const RecordType *RT = T->getAs<RecordType>()) {
1370 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1371 sizeAndAlign.first = layout.getDataSize();
1372 }
1373 }
1374
1375 return sizeAndAlign;
1376}
1377
Richard Trieu04d2d942013-05-14 21:59:17 +00001378/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1379/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1380std::pair<CharUnits, CharUnits>
1381static getConstantArrayInfoInChars(const ASTContext &Context,
1382 const ConstantArrayType *CAT) {
1383 std::pair<CharUnits, CharUnits> EltInfo =
1384 Context.getTypeInfoInChars(CAT->getElementType());
1385 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001386 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1387 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001388 "Overflow in array type char size evaluation");
1389 uint64_t Width = EltInfo.first.getQuantity() * Size;
1390 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001391 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1392 Context.getTargetInfo().getPointerWidth(0) == 64)
1393 Width = llvm::RoundUpToAlignment(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001394 return std::make_pair(CharUnits::fromQuantity(Width),
1395 CharUnits::fromQuantity(Align));
1396}
1397
John McCall87fe5d52010-05-20 01:18:31 +00001398std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001399ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001400 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1401 return getConstantArrayInfoInChars(*this, CAT);
John McCall87fe5d52010-05-20 01:18:31 +00001402 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +00001403 return std::make_pair(toCharUnitsFromBits(Info.first),
1404 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +00001405}
1406
1407std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001408ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001409 return getTypeInfoInChars(T.getTypePtr());
1410}
1411
Daniel Dunbarc6475872012-03-09 04:12:54 +00001412std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1413 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1414 if (it != MemoizedTypeInfo.end())
1415 return it->second;
1416
1417 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1418 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1419 return Info;
1420}
1421
1422/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1423/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001424///
1425/// FIXME: Pointers into different addr spaces could have different sizes and
1426/// alignment requirements: getPointerInfo should take an AddrSpace, this
1427/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +00001428std::pair<uint64_t, unsigned>
Daniel Dunbarc6475872012-03-09 04:12:54 +00001429ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +00001430 uint64_t Width=0;
1431 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001432 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001433#define TYPE(Class, Base)
1434#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001435#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001436#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001437#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1438 case Type::Class: \
1439 assert(!T->isDependentType() && "should not see dependent types here"); \
1440 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001441#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001442 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001443
Chris Lattner355332d2007-07-13 22:27:08 +00001444 case Type::FunctionNoProto:
1445 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001446 // GCC extension: alignof(function) = 32 bits
1447 Width = 0;
1448 Align = 32;
1449 break;
1450
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001451 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001452 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001453 Width = 0;
1454 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1455 break;
1456
Steve Naroff5c131802007-08-30 01:06:46 +00001457 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001458 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001459
Chris Lattner37e05872008-03-05 18:54:05 +00001460 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001461 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarc6475872012-03-09 04:12:54 +00001462 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1463 "Overflow in array type bit size evaluation");
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001464 Width = EltInfo.first*Size;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001465 Align = EltInfo.second;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001466 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1467 getTargetInfo().getPointerWidth(0) == 64)
1468 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001469 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001470 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001471 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001472 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001473 const VectorType *VT = cast<VectorType>(T);
1474 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1475 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001476 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001477 // If the alignment is not a power of 2, round up to the next power of 2.
1478 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001479 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001480 Align = llvm::NextPowerOf2(Align);
1481 Width = llvm::RoundUpToAlignment(Width, Align);
1482 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001483 // Adjust the alignment based on the target max.
1484 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1485 if (TargetVectorAlign && TargetVectorAlign < Align)
1486 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001487 break;
1488 }
Chris Lattner647fb222007-07-18 18:26:58 +00001489
Chris Lattner7570e9c2008-03-08 08:52:55 +00001490 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001491 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001492 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001493 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001494 // GCC extension: alignof(void) = 8 bits.
1495 Width = 0;
1496 Align = 8;
1497 break;
1498
Chris Lattner6a4f7452007-12-19 19:23:28 +00001499 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001500 Width = Target->getBoolWidth();
1501 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001502 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001503 case BuiltinType::Char_S:
1504 case BuiltinType::Char_U:
1505 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001506 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001507 Width = Target->getCharWidth();
1508 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001509 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001510 case BuiltinType::WChar_S:
1511 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001512 Width = Target->getWCharWidth();
1513 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001514 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001515 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001516 Width = Target->getChar16Width();
1517 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001518 break;
1519 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001520 Width = Target->getChar32Width();
1521 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001522 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001523 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001524 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001525 Width = Target->getShortWidth();
1526 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001527 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001528 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001529 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001530 Width = Target->getIntWidth();
1531 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001532 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001533 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001534 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001535 Width = Target->getLongWidth();
1536 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001537 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001538 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001539 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001540 Width = Target->getLongLongWidth();
1541 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001542 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001543 case BuiltinType::Int128:
1544 case BuiltinType::UInt128:
1545 Width = 128;
1546 Align = 128; // int128_t is 128-bit aligned on all targets.
1547 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001548 case BuiltinType::Half:
1549 Width = Target->getHalfWidth();
1550 Align = Target->getHalfAlign();
1551 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001552 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001553 Width = Target->getFloatWidth();
1554 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001555 break;
1556 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001557 Width = Target->getDoubleWidth();
1558 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001559 break;
1560 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001561 Width = Target->getLongDoubleWidth();
1562 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001563 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001564 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001565 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1566 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001567 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001568 case BuiltinType::ObjCId:
1569 case BuiltinType::ObjCClass:
1570 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001571 Width = Target->getPointerWidth(0);
1572 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001573 break;
Guy Benyei61054192013-02-07 10:55:47 +00001574 case BuiltinType::OCLSampler:
1575 // Samplers are modeled as integers.
1576 Width = Target->getIntWidth();
1577 Align = Target->getIntAlign();
1578 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001579 case BuiltinType::OCLEvent:
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001580 case BuiltinType::OCLImage1d:
1581 case BuiltinType::OCLImage1dArray:
1582 case BuiltinType::OCLImage1dBuffer:
1583 case BuiltinType::OCLImage2d:
1584 case BuiltinType::OCLImage2dArray:
1585 case BuiltinType::OCLImage3d:
1586 // Currently these types are pointers to opaque types.
1587 Width = Target->getPointerWidth(0);
1588 Align = Target->getPointerAlign(0);
1589 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001590 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001591 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001592 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001593 Width = Target->getPointerWidth(0);
1594 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001595 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001596 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001597 unsigned AS = getTargetAddressSpace(
1598 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001599 Width = Target->getPointerWidth(AS);
1600 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001601 break;
1602 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001603 case Type::LValueReference:
1604 case Type::RValueReference: {
1605 // alignof and sizeof should never enter this code path here, so we go
1606 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001607 unsigned AS = getTargetAddressSpace(
1608 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001609 Width = Target->getPointerWidth(AS);
1610 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001611 break;
1612 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001613 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001614 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001615 Width = Target->getPointerWidth(AS);
1616 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001617 break;
1618 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001619 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001620 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Reid Kleckner3a52abf2013-03-28 20:02:56 +00001621 llvm::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001622 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001623 }
Chris Lattner647fb222007-07-18 18:26:58 +00001624 case Type::Complex: {
1625 // Complex types have the same alignment as their elements, but twice the
1626 // size.
Mike Stump11289f42009-09-09 15:08:12 +00001627 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +00001628 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +00001629 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +00001630 Align = EltInfo.second;
1631 break;
1632 }
John McCall8b07ec22010-05-15 11:32:37 +00001633 case Type::ObjCObject:
1634 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner8a365022013-06-24 17:51:48 +00001635 case Type::Decayed:
1636 return getTypeInfo(cast<DecayedType>(T)->getDecayedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001637 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001638 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001639 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001640 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001641 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001642 break;
1643 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001644 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001645 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001646 const TagType *TT = cast<TagType>(T);
1647
1648 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001649 Width = 8;
1650 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001651 break;
1652 }
Mike Stump11289f42009-09-09 15:08:12 +00001653
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001654 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +00001655 return getTypeInfo(ET->getDecl()->getIntegerType());
1656
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001657 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +00001658 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001659 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001660 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +00001661 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001662 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001663
Chris Lattner63d2b362009-10-22 05:17:15 +00001664 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001665 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1666 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001667
Richard Smith30482bc2011-02-20 03:19:35 +00001668 case Type::Auto: {
1669 const AutoType *A = cast<AutoType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00001670 assert(!A->getDeducedType().isNull() &&
1671 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001672 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001673 }
1674
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001675 case Type::Paren:
1676 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1677
Douglas Gregoref462e62009-04-30 17:32:17 +00001678 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001679 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +00001680 std::pair<uint64_t, unsigned> Info
1681 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001682 // If the typedef has an aligned attribute on it, it overrides any computed
1683 // alignment we have. This violates the GCC documentation (which says that
1684 // attribute(aligned) can only round up) but matches its implementation.
1685 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1686 Align = AttrAlign;
1687 else
1688 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +00001689 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +00001690 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001691 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001692
Abramo Bagnara6150c882010-05-11 21:36:43 +00001693 case Type::Elaborated:
1694 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001695
John McCall81904512011-01-06 01:58:22 +00001696 case Type::Attributed:
1697 return getTypeInfo(
1698 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1699
Eli Friedman0dfb8892011-10-06 23:00:33 +00001700 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00001701 // Start with the base type information.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001702 std::pair<uint64_t, unsigned> Info
1703 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1704 Width = Info.first;
1705 Align = Info.second;
John McCalla8ec7eb2013-03-07 21:37:17 +00001706
1707 // If the size of the type doesn't exceed the platform's max
1708 // atomic promotion width, make the size and alignment more
1709 // favorable to atomic operations:
1710 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1711 // Round the size up to a power of 2.
1712 if (!llvm::isPowerOf2_64(Width))
1713 Width = llvm::NextPowerOf2(Width);
1714
1715 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001716 Align = static_cast<unsigned>(Width);
1717 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001718 }
1719
Douglas Gregoref462e62009-04-30 17:32:17 +00001720 }
Mike Stump11289f42009-09-09 15:08:12 +00001721
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001722 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +00001723 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001724}
1725
Ken Dyckcc56c542011-01-15 18:38:59 +00001726/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1727CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1728 return CharUnits::fromQuantity(BitSize / getCharWidth());
1729}
1730
Ken Dyckb0fcc592011-02-11 01:54:29 +00001731/// toBits - Convert a size in characters to a size in characters.
1732int64_t ASTContext::toBits(CharUnits CharSize) const {
1733 return CharSize.getQuantity() * getCharWidth();
1734}
1735
Ken Dyck8c89d592009-12-22 14:23:30 +00001736/// getTypeSizeInChars - Return the size of the specified type, in characters.
1737/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001738CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001739 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001740}
Jay Foad39c79802011-01-12 09:06:06 +00001741CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001742 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001743}
1744
Ken Dycka6046ab2010-01-26 17:25:18 +00001745/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001746/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001747CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001748 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001749}
Jay Foad39c79802011-01-12 09:06:06 +00001750CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001751 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001752}
1753
Chris Lattnera3402cd2009-01-27 18:08:34 +00001754/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1755/// type for the current target in bits. This can be different than the ABI
1756/// alignment in cases where it is beneficial for performance to overalign
1757/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001758unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +00001759 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +00001760
Robert Lyttoneaf6f362013-11-12 10:09:34 +00001761 if (Target->getTriple().getArch() == llvm::Triple::xcore)
1762 return ABIAlign; // Never overalign on XCore.
1763
Eli Friedman7ab09572009-05-25 21:27:19 +00001764 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +00001765 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001766 T = CT->getElementType().getTypePtr();
1767 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001768 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1769 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman7ab09572009-05-25 21:27:19 +00001770 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1771
Chris Lattnera3402cd2009-01-27 18:08:34 +00001772 return ABIAlign;
1773}
1774
Ulrich Weigandfa806422013-05-06 16:23:57 +00001775/// getAlignOfGlobalVar - Return the alignment in bits that should be given
1776/// to a global variable of the specified type.
1777unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1778 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1779}
1780
1781/// getAlignOfGlobalVarInChars - Return the alignment in characters that
1782/// should be given to a global variable of the specified type.
1783CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1784 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1785}
1786
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001787/// DeepCollectObjCIvars -
1788/// This routine first collects all declared, but not synthesized, ivars in
1789/// super class and then collects all ivars, including those synthesized for
1790/// current class. This routine is used for implementation of current class
1791/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001792///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001793void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1794 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001795 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001796 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1797 DeepCollectObjCIvars(SuperClass, false, Ivars);
1798 if (!leafClass) {
1799 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1800 E = OI->ivar_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001801 Ivars.push_back(*I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001802 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001803 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001804 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001805 Iv= Iv->getNextIvar())
1806 Ivars.push_back(Iv);
1807 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001808}
1809
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001810/// CollectInheritedProtocols - Collect all protocols in current class and
1811/// those inherited by it.
1812void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001813 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001814 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001815 // We can use protocol_iterator here instead of
1816 // all_referenced_protocol_iterator since we are walking all categories.
1817 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1818 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001819 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001820 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001821 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001822 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001823 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001824 CollectInheritedProtocols(*P, Protocols);
1825 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001826 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001827
1828 // Categories of this Interface.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001829 for (ObjCInterfaceDecl::visible_categories_iterator
1830 Cat = OI->visible_categories_begin(),
1831 CatEnd = OI->visible_categories_end();
1832 Cat != CatEnd; ++Cat) {
1833 CollectInheritedProtocols(*Cat, Protocols);
1834 }
1835
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001836 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1837 while (SD) {
1838 CollectInheritedProtocols(SD, Protocols);
1839 SD = SD->getSuperClass();
1840 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001841 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001842 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001843 PE = OC->protocol_end(); P != PE; ++P) {
1844 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001845 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001846 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1847 PE = Proto->protocol_end(); P != PE; ++P)
1848 CollectInheritedProtocols(*P, Protocols);
1849 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001850 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001851 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1852 PE = OP->protocol_end(); P != PE; ++P) {
1853 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001854 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001855 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1856 PE = Proto->protocol_end(); P != PE; ++P)
1857 CollectInheritedProtocols(*P, Protocols);
1858 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001859 }
1860}
1861
Jay Foad39c79802011-01-12 09:06:06 +00001862unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001863 unsigned count = 0;
1864 // Count ivars declared in class extension.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001865 for (ObjCInterfaceDecl::known_extensions_iterator
1866 Ext = OI->known_extensions_begin(),
1867 ExtEnd = OI->known_extensions_end();
1868 Ext != ExtEnd; ++Ext) {
1869 count += Ext->ivar_size();
1870 }
1871
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001872 // Count ivar defined in this class's implementation. This
1873 // includes synthesized ivars.
1874 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001875 count += ImplDecl->ivar_size();
1876
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001877 return count;
1878}
1879
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001880bool ASTContext::isSentinelNullExpr(const Expr *E) {
1881 if (!E)
1882 return false;
1883
1884 // nullptr_t is always treated as null.
1885 if (E->getType()->isNullPtrType()) return true;
1886
1887 if (E->getType()->isAnyPointerType() &&
1888 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1889 Expr::NPC_ValueDependentIsNull))
1890 return true;
1891
1892 // Unfortunately, __null has type 'int'.
1893 if (isa<GNUNullExpr>(E)) return true;
1894
1895 return false;
1896}
1897
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001898/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1899ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1900 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1901 I = ObjCImpls.find(D);
1902 if (I != ObjCImpls.end())
1903 return cast<ObjCImplementationDecl>(I->second);
1904 return 0;
1905}
1906/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1907ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1908 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1909 I = ObjCImpls.find(D);
1910 if (I != ObjCImpls.end())
1911 return cast<ObjCCategoryImplDecl>(I->second);
1912 return 0;
1913}
1914
1915/// \brief Set the implementation of ObjCInterfaceDecl.
1916void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1917 ObjCImplementationDecl *ImplD) {
1918 assert(IFaceD && ImplD && "Passed null params");
1919 ObjCImpls[IFaceD] = ImplD;
1920}
1921/// \brief Set the implementation of ObjCCategoryDecl.
1922void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1923 ObjCCategoryImplDecl *ImplD) {
1924 assert(CatD && ImplD && "Passed null params");
1925 ObjCImpls[CatD] = ImplD;
1926}
1927
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001928const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
1929 const NamedDecl *ND) const {
1930 if (const ObjCInterfaceDecl *ID =
1931 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001932 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001933 if (const ObjCCategoryDecl *CD =
1934 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001935 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001936 if (const ObjCImplDecl *IMD =
1937 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001938 return IMD->getClassInterface();
1939
1940 return 0;
1941}
1942
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001943/// \brief Get the copy initialization expression of VarDecl,or NULL if
1944/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001945Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001946 assert(VD && "Passed null params");
1947 assert(VD->hasAttr<BlocksAttr>() &&
1948 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001949 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001950 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001951 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1952}
1953
1954/// \brief Set the copy inialization expression of a block var decl.
1955void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1956 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001957 assert(VD->hasAttr<BlocksAttr>() &&
1958 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001959 BlockVarCopyInits[VD] = Init;
1960}
1961
John McCallbcd03502009-12-07 02:54:59 +00001962TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001963 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001964 if (!DataSize)
1965 DataSize = TypeLoc::getFullDataSizeForType(T);
1966 else
1967 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001968 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001969
John McCallbcd03502009-12-07 02:54:59 +00001970 TypeSourceInfo *TInfo =
1971 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1972 new (TInfo) TypeSourceInfo(T);
1973 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001974}
1975
John McCallbcd03502009-12-07 02:54:59 +00001976TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001977 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001978 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001979 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001980 return DI;
1981}
1982
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001983const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001984ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001985 return getObjCLayout(D, 0);
1986}
1987
1988const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001989ASTContext::getASTObjCImplementationLayout(
1990 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001991 return getObjCLayout(D->getClassInterface(), D);
1992}
1993
Chris Lattner983a8bb2007-07-13 22:13:22 +00001994//===----------------------------------------------------------------------===//
1995// Type creation/memoization methods
1996//===----------------------------------------------------------------------===//
1997
Jay Foad39c79802011-01-12 09:06:06 +00001998QualType
John McCall33ddac02011-01-19 10:06:00 +00001999ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2000 unsigned fastQuals = quals.getFastQualifiers();
2001 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002002
2003 // Check if we've already instantiated this type.
2004 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002005 ExtQuals::Profile(ID, baseType, quals);
2006 void *insertPos = 0;
2007 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2008 assert(eq->getQualifiers() == quals);
2009 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002010 }
2011
John McCall33ddac02011-01-19 10:06:00 +00002012 // If the base type is not canonical, make the appropriate canonical type.
2013 QualType canon;
2014 if (!baseType->isCanonicalUnqualified()) {
2015 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002016 canonSplit.Quals.addConsistentQualifiers(quals);
2017 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002018
2019 // Re-find the insert position.
2020 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2021 }
2022
2023 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2024 ExtQualNodes.InsertNode(eq, insertPos);
2025 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002026}
2027
Jay Foad39c79802011-01-12 09:06:06 +00002028QualType
2029ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002030 QualType CanT = getCanonicalType(T);
2031 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002032 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002033
John McCall8ccfcb52009-09-24 19:53:00 +00002034 // If we are composing extended qualifiers together, merge together
2035 // into one ExtQuals node.
2036 QualifierCollector Quals;
2037 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002038
John McCall8ccfcb52009-09-24 19:53:00 +00002039 // If this type already has an address space specified, it cannot get
2040 // another one.
2041 assert(!Quals.hasAddressSpace() &&
2042 "Type cannot be in multiple addr spaces!");
2043 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002044
John McCall8ccfcb52009-09-24 19:53:00 +00002045 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002046}
2047
Chris Lattnerd60183d2009-02-18 22:53:11 +00002048QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002049 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002050 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002051 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002052 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002053
John McCall53fa7142010-12-24 02:08:15 +00002054 if (const PointerType *ptr = T->getAs<PointerType>()) {
2055 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002056 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002057 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2058 return getPointerType(ResultType);
2059 }
2060 }
Mike Stump11289f42009-09-09 15:08:12 +00002061
John McCall8ccfcb52009-09-24 19:53:00 +00002062 // If we are composing extended qualifiers together, merge together
2063 // into one ExtQuals node.
2064 QualifierCollector Quals;
2065 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002066
John McCall8ccfcb52009-09-24 19:53:00 +00002067 // If this type already has an ObjCGC specified, it cannot get
2068 // another one.
2069 assert(!Quals.hasObjCGCAttr() &&
2070 "Type cannot have multiple ObjCGCs!");
2071 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002072
John McCall8ccfcb52009-09-24 19:53:00 +00002073 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002074}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002075
John McCall4f5019e2010-12-19 02:44:49 +00002076const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2077 FunctionType::ExtInfo Info) {
2078 if (T->getExtInfo() == Info)
2079 return T;
2080
2081 QualType Result;
2082 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
2083 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
2084 } else {
2085 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2086 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2087 EPI.ExtInfo = Info;
Reid Kleckner896b32f2013-06-10 20:51:09 +00002088 Result = getFunctionType(FPT->getResultType(), FPT->getArgTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002089 }
2090
2091 return cast<FunctionType>(Result.getTypePtr());
2092}
2093
Richard Smith2a7d4812013-05-04 07:00:32 +00002094void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2095 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002096 FD = FD->getMostRecentDecl();
2097 while (true) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002098 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2099 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2100 FD->setType(getFunctionType(ResultType, FPT->getArgTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002101 if (FunctionDecl *Next = FD->getPreviousDecl())
2102 FD = Next;
2103 else
2104 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002105 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002106 if (ASTMutationListener *L = getASTMutationListener())
2107 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002108}
2109
Chris Lattnerc6395932007-06-22 20:56:16 +00002110/// getComplexType - Return the uniqued reference to the type for a complex
2111/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002112QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002113 // Unique pointers, to guarantee there is only one pointer of a particular
2114 // structure.
2115 llvm::FoldingSetNodeID ID;
2116 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002117
Chris Lattnerc6395932007-06-22 20:56:16 +00002118 void *InsertPos = 0;
2119 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2120 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002121
Chris Lattnerc6395932007-06-22 20:56:16 +00002122 // If the pointee type isn't canonical, this won't be a canonical type either,
2123 // so fill in the canonical type field.
2124 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002125 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002126 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002127
Chris Lattnerc6395932007-06-22 20:56:16 +00002128 // Get the new insert position for the node we care about.
2129 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002130 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002131 }
John McCall90d1c2d2009-09-24 23:30:46 +00002132 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002133 Types.push_back(New);
2134 ComplexTypes.InsertNode(New, InsertPos);
2135 return QualType(New, 0);
2136}
2137
Chris Lattner970e54e2006-11-12 00:37:36 +00002138/// getPointerType - Return the uniqued reference to the type for a pointer to
2139/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002140QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002141 // Unique pointers, to guarantee there is only one pointer of a particular
2142 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002143 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002144 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002145
Chris Lattner67521df2007-01-27 01:29:36 +00002146 void *InsertPos = 0;
2147 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002148 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002149
Chris Lattner7ccecb92006-11-12 08:50:50 +00002150 // If the pointee type isn't canonical, this won't be a canonical type either,
2151 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002152 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002153 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002154 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002155
Bob Wilsonc8541f22013-03-15 17:12:43 +00002156 // Get the new insert position for the node we care about.
2157 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2158 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2159 }
John McCall90d1c2d2009-09-24 23:30:46 +00002160 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002161 Types.push_back(New);
2162 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002163 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002164}
2165
Reid Kleckner8a365022013-06-24 17:51:48 +00002166QualType ASTContext::getDecayedType(QualType T) const {
2167 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2168
2169 llvm::FoldingSetNodeID ID;
2170 DecayedType::Profile(ID, T);
2171 void *InsertPos = 0;
2172 if (DecayedType *DT = DecayedTypes.FindNodeOrInsertPos(ID, InsertPos))
2173 return QualType(DT, 0);
2174
2175 QualType Decayed;
2176
2177 // C99 6.7.5.3p7:
2178 // A declaration of a parameter as "array of type" shall be
2179 // adjusted to "qualified pointer to type", where the type
2180 // qualifiers (if any) are those specified within the [ and ] of
2181 // the array type derivation.
2182 if (T->isArrayType())
2183 Decayed = getArrayDecayedType(T);
2184
2185 // C99 6.7.5.3p8:
2186 // A declaration of a parameter as "function returning type"
2187 // shall be adjusted to "pointer to function returning type", as
2188 // in 6.3.2.1.
2189 if (T->isFunctionType())
2190 Decayed = getPointerType(T);
2191
2192 QualType Canonical = getCanonicalType(Decayed);
2193
2194 // Get the new insert position for the node we care about.
2195 DecayedType *NewIP = DecayedTypes.FindNodeOrInsertPos(ID, InsertPos);
2196 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2197
2198 DecayedType *New =
2199 new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2200 Types.push_back(New);
2201 DecayedTypes.InsertNode(New, InsertPos);
2202 return QualType(New, 0);
2203}
2204
Mike Stump11289f42009-09-09 15:08:12 +00002205/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002206/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002207QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002208 assert(T->isFunctionType() && "block of function types only");
2209 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002210 // structure.
2211 llvm::FoldingSetNodeID ID;
2212 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002213
Steve Naroffec33ed92008-08-27 16:04:49 +00002214 void *InsertPos = 0;
2215 if (BlockPointerType *PT =
2216 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2217 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002218
2219 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002220 // type either so fill in the canonical type field.
2221 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002222 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002223 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002224
Steve Naroffec33ed92008-08-27 16:04:49 +00002225 // Get the new insert position for the node we care about.
2226 BlockPointerType *NewIP =
2227 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002228 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002229 }
John McCall90d1c2d2009-09-24 23:30:46 +00002230 BlockPointerType *New
2231 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002232 Types.push_back(New);
2233 BlockPointerTypes.InsertNode(New, InsertPos);
2234 return QualType(New, 0);
2235}
2236
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002237/// getLValueReferenceType - Return the uniqued reference to the type for an
2238/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002239QualType
2240ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002241 assert(getCanonicalType(T) != OverloadTy &&
2242 "Unresolved overloaded function type");
2243
Bill Wendling3708c182007-05-27 10:15:43 +00002244 // Unique pointers, to guarantee there is only one pointer of a particular
2245 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002246 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002247 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002248
2249 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002250 if (LValueReferenceType *RT =
2251 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002252 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002253
John McCallfc93cf92009-10-22 22:37:11 +00002254 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2255
Bill Wendling3708c182007-05-27 10:15:43 +00002256 // If the referencee type isn't canonical, this won't be a canonical type
2257 // either, so fill in the canonical type field.
2258 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002259 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2260 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2261 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002262
Bill Wendling3708c182007-05-27 10:15:43 +00002263 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002264 LValueReferenceType *NewIP =
2265 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002266 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002267 }
2268
John McCall90d1c2d2009-09-24 23:30:46 +00002269 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002270 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2271 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002272 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002273 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002274
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002275 return QualType(New, 0);
2276}
2277
2278/// getRValueReferenceType - Return the uniqued reference to the type for an
2279/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002280QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002281 // Unique pointers, to guarantee there is only one pointer of a particular
2282 // structure.
2283 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002284 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002285
2286 void *InsertPos = 0;
2287 if (RValueReferenceType *RT =
2288 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2289 return QualType(RT, 0);
2290
John McCallfc93cf92009-10-22 22:37:11 +00002291 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2292
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002293 // If the referencee type isn't canonical, this won't be a canonical type
2294 // either, so fill in the canonical type field.
2295 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002296 if (InnerRef || !T.isCanonical()) {
2297 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2298 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002299
2300 // Get the new insert position for the node we care about.
2301 RValueReferenceType *NewIP =
2302 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002303 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002304 }
2305
John McCall90d1c2d2009-09-24 23:30:46 +00002306 RValueReferenceType *New
2307 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002308 Types.push_back(New);
2309 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002310 return QualType(New, 0);
2311}
2312
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002313/// getMemberPointerType - Return the uniqued reference to the type for a
2314/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002315QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002316 // Unique pointers, to guarantee there is only one pointer of a particular
2317 // structure.
2318 llvm::FoldingSetNodeID ID;
2319 MemberPointerType::Profile(ID, T, Cls);
2320
2321 void *InsertPos = 0;
2322 if (MemberPointerType *PT =
2323 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2324 return QualType(PT, 0);
2325
2326 // If the pointee or class type isn't canonical, this won't be a canonical
2327 // type either, so fill in the canonical type field.
2328 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002329 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002330 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2331
2332 // Get the new insert position for the node we care about.
2333 MemberPointerType *NewIP =
2334 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002335 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002336 }
John McCall90d1c2d2009-09-24 23:30:46 +00002337 MemberPointerType *New
2338 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002339 Types.push_back(New);
2340 MemberPointerTypes.InsertNode(New, InsertPos);
2341 return QualType(New, 0);
2342}
2343
Mike Stump11289f42009-09-09 15:08:12 +00002344/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002345/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002346QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002347 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002348 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002349 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002350 assert((EltTy->isDependentType() ||
2351 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002352 "Constant array of VLAs is illegal!");
2353
Chris Lattnere2df3f92009-05-13 04:12:56 +00002354 // Convert the array size into a canonical width matching the pointer size for
2355 // the target.
2356 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002357 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002358 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002359
Chris Lattner23b7eb62007-06-15 23:05:46 +00002360 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002361 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002362
Chris Lattner36f8e652007-01-27 08:31:04 +00002363 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002364 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002365 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002366 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002367
John McCall33ddac02011-01-19 10:06:00 +00002368 // If the element type isn't canonical or has qualifiers, this won't
2369 // be a canonical type either, so fill in the canonical type field.
2370 QualType Canon;
2371 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2372 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002373 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002374 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002375 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002376
Chris Lattner36f8e652007-01-27 08:31:04 +00002377 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002378 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002379 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002380 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002381 }
Mike Stump11289f42009-09-09 15:08:12 +00002382
John McCall90d1c2d2009-09-24 23:30:46 +00002383 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002384 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002385 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002386 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002387 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002388}
2389
John McCall06549462011-01-18 08:40:38 +00002390/// getVariableArrayDecayedType - Turns the given type, which may be
2391/// variably-modified, into the corresponding type with all the known
2392/// sizes replaced with [*].
2393QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2394 // Vastly most common case.
2395 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002396
John McCall06549462011-01-18 08:40:38 +00002397 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002398
John McCall06549462011-01-18 08:40:38 +00002399 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002400 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002401 switch (ty->getTypeClass()) {
2402#define TYPE(Class, Base)
2403#define ABSTRACT_TYPE(Class, Base)
2404#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2405#include "clang/AST/TypeNodes.def"
2406 llvm_unreachable("didn't desugar past all non-canonical types?");
2407
2408 // These types should never be variably-modified.
2409 case Type::Builtin:
2410 case Type::Complex:
2411 case Type::Vector:
2412 case Type::ExtVector:
2413 case Type::DependentSizedExtVector:
2414 case Type::ObjCObject:
2415 case Type::ObjCInterface:
2416 case Type::ObjCObjectPointer:
2417 case Type::Record:
2418 case Type::Enum:
2419 case Type::UnresolvedUsing:
2420 case Type::TypeOfExpr:
2421 case Type::TypeOf:
2422 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002423 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002424 case Type::DependentName:
2425 case Type::InjectedClassName:
2426 case Type::TemplateSpecialization:
2427 case Type::DependentTemplateSpecialization:
2428 case Type::TemplateTypeParm:
2429 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002430 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002431 case Type::PackExpansion:
2432 llvm_unreachable("type should never be variably-modified");
2433
2434 // These types can be variably-modified but should never need to
2435 // further decay.
2436 case Type::FunctionNoProto:
2437 case Type::FunctionProto:
2438 case Type::BlockPointer:
2439 case Type::MemberPointer:
2440 return type;
2441
2442 // These types can be variably-modified. All these modifications
2443 // preserve structure except as noted by comments.
2444 // TODO: if we ever care about optimizing VLAs, there are no-op
2445 // optimizations available here.
2446 case Type::Pointer:
2447 result = getPointerType(getVariableArrayDecayedType(
2448 cast<PointerType>(ty)->getPointeeType()));
2449 break;
2450
2451 case Type::LValueReference: {
2452 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2453 result = getLValueReferenceType(
2454 getVariableArrayDecayedType(lv->getPointeeType()),
2455 lv->isSpelledAsLValue());
2456 break;
2457 }
2458
2459 case Type::RValueReference: {
2460 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2461 result = getRValueReferenceType(
2462 getVariableArrayDecayedType(lv->getPointeeType()));
2463 break;
2464 }
2465
Eli Friedman0dfb8892011-10-06 23:00:33 +00002466 case Type::Atomic: {
2467 const AtomicType *at = cast<AtomicType>(ty);
2468 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2469 break;
2470 }
2471
John McCall06549462011-01-18 08:40:38 +00002472 case Type::ConstantArray: {
2473 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2474 result = getConstantArrayType(
2475 getVariableArrayDecayedType(cat->getElementType()),
2476 cat->getSize(),
2477 cat->getSizeModifier(),
2478 cat->getIndexTypeCVRQualifiers());
2479 break;
2480 }
2481
2482 case Type::DependentSizedArray: {
2483 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2484 result = getDependentSizedArrayType(
2485 getVariableArrayDecayedType(dat->getElementType()),
2486 dat->getSizeExpr(),
2487 dat->getSizeModifier(),
2488 dat->getIndexTypeCVRQualifiers(),
2489 dat->getBracketsRange());
2490 break;
2491 }
2492
2493 // Turn incomplete types into [*] types.
2494 case Type::IncompleteArray: {
2495 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2496 result = getVariableArrayType(
2497 getVariableArrayDecayedType(iat->getElementType()),
2498 /*size*/ 0,
2499 ArrayType::Normal,
2500 iat->getIndexTypeCVRQualifiers(),
2501 SourceRange());
2502 break;
2503 }
2504
2505 // Turn VLA types into [*] types.
2506 case Type::VariableArray: {
2507 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2508 result = getVariableArrayType(
2509 getVariableArrayDecayedType(vat->getElementType()),
2510 /*size*/ 0,
2511 ArrayType::Star,
2512 vat->getIndexTypeCVRQualifiers(),
2513 vat->getBracketsRange());
2514 break;
2515 }
2516 }
2517
2518 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002519 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002520}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002521
Steve Naroffcadebd02007-08-30 18:14:25 +00002522/// getVariableArrayType - Returns a non-unique reference to the type for a
2523/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002524QualType ASTContext::getVariableArrayType(QualType EltTy,
2525 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002526 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002527 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002528 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002529 // Since we don't unique expressions, it isn't possible to unique VLA's
2530 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002531 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002532
John McCall33ddac02011-01-19 10:06:00 +00002533 // Be sure to pull qualifiers off the element type.
2534 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2535 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002536 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002537 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002538 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002539 }
2540
John McCall90d1c2d2009-09-24 23:30:46 +00002541 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002542 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002543
2544 VariableArrayTypes.push_back(New);
2545 Types.push_back(New);
2546 return QualType(New, 0);
2547}
2548
Douglas Gregor4619e432008-12-05 23:32:09 +00002549/// getDependentSizedArrayType - Returns a non-unique reference to
2550/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002551/// type.
John McCall33ddac02011-01-19 10:06:00 +00002552QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2553 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002554 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002555 unsigned elementTypeQuals,
2556 SourceRange brackets) const {
2557 assert((!numElements || numElements->isTypeDependent() ||
2558 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002559 "Size must be type- or value-dependent!");
2560
John McCall33ddac02011-01-19 10:06:00 +00002561 // Dependently-sized array types that do not have a specified number
2562 // of elements will have their sizes deduced from a dependent
2563 // initializer. We do no canonicalization here at all, which is okay
2564 // because they can't be used in most locations.
2565 if (!numElements) {
2566 DependentSizedArrayType *newType
2567 = new (*this, TypeAlignment)
2568 DependentSizedArrayType(*this, elementType, QualType(),
2569 numElements, ASM, elementTypeQuals,
2570 brackets);
2571 Types.push_back(newType);
2572 return QualType(newType, 0);
2573 }
2574
2575 // Otherwise, we actually build a new type every time, but we
2576 // also build a canonical type.
2577
2578 SplitQualType canonElementType = getCanonicalType(elementType).split();
2579
2580 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002581 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002582 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002583 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002584 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002585
John McCall33ddac02011-01-19 10:06:00 +00002586 // Look for an existing type with these properties.
2587 DependentSizedArrayType *canonTy =
2588 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002589
John McCall33ddac02011-01-19 10:06:00 +00002590 // If we don't have one, build one.
2591 if (!canonTy) {
2592 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002593 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002594 QualType(), numElements, ASM, elementTypeQuals,
2595 brackets);
2596 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2597 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002598 }
2599
John McCall33ddac02011-01-19 10:06:00 +00002600 // Apply qualifiers from the element type to the array.
2601 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002602 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002603
John McCall33ddac02011-01-19 10:06:00 +00002604 // If we didn't need extra canonicalization for the element type,
2605 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00002606 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00002607 return canon;
2608
2609 // Otherwise, we need to build a type which follows the spelling
2610 // of the element type.
2611 DependentSizedArrayType *sugaredType
2612 = new (*this, TypeAlignment)
2613 DependentSizedArrayType(*this, elementType, canon, numElements,
2614 ASM, elementTypeQuals, brackets);
2615 Types.push_back(sugaredType);
2616 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002617}
2618
John McCall33ddac02011-01-19 10:06:00 +00002619QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002620 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002621 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002622 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002623 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002624
John McCall33ddac02011-01-19 10:06:00 +00002625 void *insertPos = 0;
2626 if (IncompleteArrayType *iat =
2627 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2628 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002629
2630 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002631 // either, so fill in the canonical type field. We also have to pull
2632 // qualifiers off the element type.
2633 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002634
John McCall33ddac02011-01-19 10:06:00 +00002635 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2636 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002637 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002638 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002639 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002640
2641 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002642 IncompleteArrayType *existing =
2643 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2644 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002645 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002646
John McCall33ddac02011-01-19 10:06:00 +00002647 IncompleteArrayType *newType = new (*this, TypeAlignment)
2648 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002649
John McCall33ddac02011-01-19 10:06:00 +00002650 IncompleteArrayTypes.InsertNode(newType, insertPos);
2651 Types.push_back(newType);
2652 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002653}
2654
Steve Naroff91fcddb2007-07-18 18:00:27 +00002655/// getVectorType - Return the unique reference to a vector type of
2656/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002657QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002658 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002659 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002660
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002661 // Check if we've already instantiated a vector of this type.
2662 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002663 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002664
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002665 void *InsertPos = 0;
2666 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2667 return QualType(VTP, 0);
2668
2669 // If the element type isn't canonical, this won't be a canonical type either,
2670 // so fill in the canonical type field.
2671 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002672 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002673 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002674
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002675 // Get the new insert position for the node we care about.
2676 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002677 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002678 }
John McCall90d1c2d2009-09-24 23:30:46 +00002679 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002680 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002681 VectorTypes.InsertNode(New, InsertPos);
2682 Types.push_back(New);
2683 return QualType(New, 0);
2684}
2685
Nate Begemance4d7fc2008-04-18 23:10:10 +00002686/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002687/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002688QualType
2689ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002690 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002691
Steve Naroff91fcddb2007-07-18 18:00:27 +00002692 // Check if we've already instantiated a vector of this type.
2693 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002694 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002695 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002696 void *InsertPos = 0;
2697 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2698 return QualType(VTP, 0);
2699
2700 // If the element type isn't canonical, this won't be a canonical type either,
2701 // so fill in the canonical type field.
2702 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002703 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002704 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002705
Steve Naroff91fcddb2007-07-18 18:00:27 +00002706 // Get the new insert position for the node we care about.
2707 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002708 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002709 }
John McCall90d1c2d2009-09-24 23:30:46 +00002710 ExtVectorType *New = new (*this, TypeAlignment)
2711 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002712 VectorTypes.InsertNode(New, InsertPos);
2713 Types.push_back(New);
2714 return QualType(New, 0);
2715}
2716
Jay Foad39c79802011-01-12 09:06:06 +00002717QualType
2718ASTContext::getDependentSizedExtVectorType(QualType vecType,
2719 Expr *SizeExpr,
2720 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002721 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002722 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002723 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002724
Douglas Gregor352169a2009-07-31 03:54:25 +00002725 void *InsertPos = 0;
2726 DependentSizedExtVectorType *Canon
2727 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2728 DependentSizedExtVectorType *New;
2729 if (Canon) {
2730 // We already have a canonical version of this array type; use it as
2731 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002732 New = new (*this, TypeAlignment)
2733 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2734 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002735 } else {
2736 QualType CanonVecTy = getCanonicalType(vecType);
2737 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002738 New = new (*this, TypeAlignment)
2739 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2740 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002741
2742 DependentSizedExtVectorType *CanonCheck
2743 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2744 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2745 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002746 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2747 } else {
2748 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2749 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002750 New = new (*this, TypeAlignment)
2751 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002752 }
2753 }
Mike Stump11289f42009-09-09 15:08:12 +00002754
Douglas Gregor758a8692009-06-17 21:51:59 +00002755 Types.push_back(New);
2756 return QualType(New, 0);
2757}
2758
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002759/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002760///
Jay Foad39c79802011-01-12 09:06:06 +00002761QualType
2762ASTContext::getFunctionNoProtoType(QualType ResultTy,
2763 const FunctionType::ExtInfo &Info) const {
Reid Kleckner78af0702013-08-27 23:08:25 +00002764 const CallingConv CallConv = Info.getCC();
2765
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002766 // Unique functions, to guarantee there is only one function of a particular
2767 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002768 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002769 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002770
Chris Lattner47955de2007-01-27 08:37:20 +00002771 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002772 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002773 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002774 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002775
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002776 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002777 if (!ResultTy.isCanonical()) {
2778 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00002779
Chris Lattner47955de2007-01-27 08:37:20 +00002780 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002781 FunctionNoProtoType *NewIP =
2782 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002783 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002784 }
Mike Stump11289f42009-09-09 15:08:12 +00002785
Roman Divacky65b88cd2011-03-01 17:40:53 +00002786 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002787 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002788 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002789 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002790 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002791 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002792}
2793
Douglas Gregorcd780372013-01-17 23:36:45 +00002794/// \brief Determine whether \p T is canonical as the result type of a function.
2795static bool isCanonicalResultType(QualType T) {
2796 return T.isCanonical() &&
2797 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2798 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2799}
2800
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002801/// getFunctionType - Return a normal function type with a typed argument
2802/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00002803QualType
Jordan Rose5c382722013-03-08 21:51:21 +00002804ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad39c79802011-01-12 09:06:06 +00002805 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rose5c382722013-03-08 21:51:21 +00002806 size_t NumArgs = ArgArray.size();
2807
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002808 // Unique functions, to guarantee there is only one function of a particular
2809 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002810 llvm::FoldingSetNodeID ID;
Jordan Rose5c382722013-03-08 21:51:21 +00002811 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
2812 *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002813
2814 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002815 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002816 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002817 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002818
2819 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002820 bool isCanonical =
Douglas Gregorcd780372013-01-17 23:36:45 +00002821 EPI.ExceptionSpecType == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smith5e580292012-02-10 09:58:53 +00002822 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002823 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002824 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002825 isCanonical = false;
2826
2827 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002828 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002829 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002830 if (!isCanonical) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002831 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002832 CanonicalArgs.reserve(NumArgs);
2833 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002834 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002835
John McCalldb40c7f2010-12-14 08:05:40 +00002836 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002837 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002838 CanonicalEPI.ExceptionSpecType = EST_None;
2839 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002840
Douglas Gregorcd780372013-01-17 23:36:45 +00002841 // Result types do not have ARC lifetime qualifiers.
2842 QualType CanResultTy = getCanonicalType(ResultTy);
2843 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2844 Qualifiers Qs = CanResultTy.getQualifiers();
2845 Qs.removeObjCLifetime();
2846 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2847 }
2848
Jordan Rose5c382722013-03-08 21:51:21 +00002849 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002850
Chris Lattnerfd4de792007-01-27 01:15:32 +00002851 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002852 FunctionProtoType *NewIP =
2853 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002854 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002855 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002856
John McCall31168b02011-06-15 23:02:42 +00002857 // FunctionProtoType objects are allocated with extra bytes after
2858 // them for three variable size arrays at the end:
2859 // - parameter types
2860 // - exception types
2861 // - consumed-arguments flags
2862 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00002863 // expression, or information used to resolve the exception
2864 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00002865 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002866 NumArgs * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002867 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002868 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002869 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002870 Size += sizeof(Expr*);
Richard Smithf623c962012-04-17 00:58:00 +00002871 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00002872 Size += 2 * sizeof(FunctionDecl*);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002873 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2874 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002875 }
John McCall31168b02011-06-15 23:02:42 +00002876 if (EPI.ConsumedArguments)
2877 Size += NumArgs * sizeof(bool);
2878
John McCalldb40c7f2010-12-14 08:05:40 +00002879 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002880 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00002881 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002882 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002883 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002884 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002885}
Chris Lattneref51c202006-11-10 07:17:23 +00002886
John McCalle78aac42010-03-10 03:28:59 +00002887#ifndef NDEBUG
2888static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2889 if (!isa<CXXRecordDecl>(D)) return false;
2890 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2891 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2892 return true;
2893 if (RD->getDescribedClassTemplate() &&
2894 !isa<ClassTemplateSpecializationDecl>(RD))
2895 return true;
2896 return false;
2897}
2898#endif
2899
2900/// getInjectedClassNameType - Return the unique reference to the
2901/// injected class name type for the specified templated declaration.
2902QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002903 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002904 assert(NeedsInjectedClassNameType(Decl));
2905 if (Decl->TypeForDecl) {
2906 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00002907 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00002908 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2909 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2910 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2911 } else {
John McCall424cec92011-01-19 06:33:43 +00002912 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002913 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002914 Decl->TypeForDecl = newType;
2915 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002916 }
2917 return QualType(Decl->TypeForDecl, 0);
2918}
2919
Douglas Gregor83a586e2008-04-13 21:07:44 +00002920/// getTypeDeclType - Return the unique reference to the type for the
2921/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002922QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002923 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002924 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002925
Richard Smithdda56e42011-04-15 14:24:37 +00002926 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002927 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002928
John McCall96f0b5f2010-03-10 06:48:02 +00002929 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2930 "Template type parameter types are always available.");
2931
John McCall81e38502010-02-16 03:57:14 +00002932 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00002933 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00002934 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002935 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002936 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00002937 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002938 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002939 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002940 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002941 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2942 Decl->TypeForDecl = newType;
2943 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002944 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002945 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002946
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002947 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002948}
2949
Chris Lattner32d920b2007-01-26 02:01:53 +00002950/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002951/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002952QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002953ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2954 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002955 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002956
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002957 if (Canonical.isNull())
2958 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002959 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002960 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002961 Decl->TypeForDecl = newType;
2962 Types.push_back(newType);
2963 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002964}
2965
Jay Foad39c79802011-01-12 09:06:06 +00002966QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002967 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2968
Douglas Gregorec9fd132012-01-14 16:38:05 +00002969 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002970 if (PrevDecl->TypeForDecl)
2971 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2972
John McCall424cec92011-01-19 06:33:43 +00002973 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2974 Decl->TypeForDecl = newType;
2975 Types.push_back(newType);
2976 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002977}
2978
Jay Foad39c79802011-01-12 09:06:06 +00002979QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002980 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2981
Douglas Gregorec9fd132012-01-14 16:38:05 +00002982 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002983 if (PrevDecl->TypeForDecl)
2984 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2985
John McCall424cec92011-01-19 06:33:43 +00002986 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2987 Decl->TypeForDecl = newType;
2988 Types.push_back(newType);
2989 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002990}
2991
John McCall81904512011-01-06 01:58:22 +00002992QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2993 QualType modifiedType,
2994 QualType equivalentType) {
2995 llvm::FoldingSetNodeID id;
2996 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2997
2998 void *insertPos = 0;
2999 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3000 if (type) return QualType(type, 0);
3001
3002 QualType canon = getCanonicalType(equivalentType);
3003 type = new (*this, TypeAlignment)
3004 AttributedType(canon, attrKind, modifiedType, equivalentType);
3005
3006 Types.push_back(type);
3007 AttributedTypes.InsertNode(type, insertPos);
3008
3009 return QualType(type, 0);
3010}
3011
3012
John McCallcebee162009-10-18 09:09:24 +00003013/// \brief Retrieve a substitution-result type.
3014QualType
3015ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003016 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003017 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003018 && "replacement types must always be canonical");
3019
3020 llvm::FoldingSetNodeID ID;
3021 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
3022 void *InsertPos = 0;
3023 SubstTemplateTypeParmType *SubstParm
3024 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3025
3026 if (!SubstParm) {
3027 SubstParm = new (*this, TypeAlignment)
3028 SubstTemplateTypeParmType(Parm, Replacement);
3029 Types.push_back(SubstParm);
3030 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3031 }
3032
3033 return QualType(SubstParm, 0);
3034}
3035
Douglas Gregorada4b792011-01-14 02:55:32 +00003036/// \brief Retrieve a
3037QualType ASTContext::getSubstTemplateTypeParmPackType(
3038 const TemplateTypeParmType *Parm,
3039 const TemplateArgument &ArgPack) {
3040#ifndef NDEBUG
3041 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
3042 PEnd = ArgPack.pack_end();
3043 P != PEnd; ++P) {
3044 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3045 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
3046 }
3047#endif
3048
3049 llvm::FoldingSetNodeID ID;
3050 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
3051 void *InsertPos = 0;
3052 if (SubstTemplateTypeParmPackType *SubstParm
3053 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3054 return QualType(SubstParm, 0);
3055
3056 QualType Canon;
3057 if (!Parm->isCanonicalUnqualified()) {
3058 Canon = getCanonicalType(QualType(Parm, 0));
3059 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3060 ArgPack);
3061 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3062 }
3063
3064 SubstTemplateTypeParmPackType *SubstParm
3065 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3066 ArgPack);
3067 Types.push_back(SubstParm);
3068 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3069 return QualType(SubstParm, 0);
3070}
3071
Douglas Gregoreff93e02009-02-05 23:33:38 +00003072/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003073/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003074/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003075QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003076 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003077 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003078 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003079 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003080 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003081 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003082 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3083
3084 if (TypeParm)
3085 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003086
Chandler Carruth08836322011-05-01 00:51:33 +00003087 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003088 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003089 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003090
3091 TemplateTypeParmType *TypeCheck
3092 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3093 assert(!TypeCheck && "Template type parameter canonical type broken");
3094 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003095 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003096 TypeParm = new (*this, TypeAlignment)
3097 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003098
3099 Types.push_back(TypeParm);
3100 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3101
3102 return QualType(TypeParm, 0);
3103}
3104
John McCalle78aac42010-03-10 03:28:59 +00003105TypeSourceInfo *
3106ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3107 SourceLocation NameLoc,
3108 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003109 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003110 assert(!Name.getAsDependentTemplateName() &&
3111 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003112 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003113
3114 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003115 TemplateSpecializationTypeLoc TL =
3116 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003117 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003118 TL.setTemplateNameLoc(NameLoc);
3119 TL.setLAngleLoc(Args.getLAngleLoc());
3120 TL.setRAngleLoc(Args.getRAngleLoc());
3121 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3122 TL.setArgLocInfo(i, Args[i].getLocInfo());
3123 return DI;
3124}
3125
Mike Stump11289f42009-09-09 15:08:12 +00003126QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003127ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003128 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003129 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003130 assert(!Template.getAsDependentTemplateName() &&
3131 "No dependent template names here!");
3132
John McCall6b51f282009-11-23 01:53:49 +00003133 unsigned NumArgs = Args.size();
3134
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003135 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00003136 ArgVec.reserve(NumArgs);
3137 for (unsigned i = 0; i != NumArgs; ++i)
3138 ArgVec.push_back(Args[i].getArgument());
3139
John McCall2408e322010-04-27 00:57:59 +00003140 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003141 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003142}
3143
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003144#ifndef NDEBUG
3145static bool hasAnyPackExpansions(const TemplateArgument *Args,
3146 unsigned NumArgs) {
3147 for (unsigned I = 0; I != NumArgs; ++I)
3148 if (Args[I].isPackExpansion())
3149 return true;
3150
3151 return true;
3152}
3153#endif
3154
John McCall0ad16662009-10-29 08:12:44 +00003155QualType
3156ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00003157 const TemplateArgument *Args,
3158 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003159 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003160 assert(!Template.getAsDependentTemplateName() &&
3161 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003162 // Look through qualified template names.
3163 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3164 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003165
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003166 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003167 Template.getAsTemplateDecl() &&
3168 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003169 QualType CanonType;
3170 if (!Underlying.isNull())
3171 CanonType = getCanonicalType(Underlying);
3172 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003173 // We can get here with an alias template when the specialization contains
3174 // a pack expansion that does not match up with a parameter pack.
3175 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3176 "Caller must compute aliased type");
3177 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003178 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3179 NumArgs);
3180 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003181
Douglas Gregora8e02e72009-07-28 23:00:59 +00003182 // Allocate the (non-canonical) template specialization type, but don't
3183 // try to unique it: these types typically have location information that
3184 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003185 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3186 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003187 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003188 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003189 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003190 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3191 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003192
Douglas Gregor8bf42052009-02-09 18:46:07 +00003193 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003194 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003195}
3196
Mike Stump11289f42009-09-09 15:08:12 +00003197QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003198ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3199 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00003200 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003201 assert(!Template.getAsDependentTemplateName() &&
3202 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003203
Douglas Gregore29139c2011-03-03 17:04:51 +00003204 // Look through qualified template names.
3205 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3206 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003207
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003208 // Build the canonical template specialization type.
3209 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003210 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003211 CanonArgs.reserve(NumArgs);
3212 for (unsigned I = 0; I != NumArgs; ++I)
3213 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3214
3215 // Determine whether this canonical template specialization type already
3216 // exists.
3217 llvm::FoldingSetNodeID ID;
3218 TemplateSpecializationType::Profile(ID, CanonTemplate,
3219 CanonArgs.data(), NumArgs, *this);
3220
3221 void *InsertPos = 0;
3222 TemplateSpecializationType *Spec
3223 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3224
3225 if (!Spec) {
3226 // Allocate a new canonical template specialization type.
3227 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3228 sizeof(TemplateArgument) * NumArgs),
3229 TypeAlignment);
3230 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3231 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003232 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003233 Types.push_back(Spec);
3234 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3235 }
3236
3237 assert(Spec->isDependentType() &&
3238 "Non-dependent template-id type must have a canonical type");
3239 return QualType(Spec, 0);
3240}
3241
3242QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003243ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3244 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003245 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003246 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003247 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003248
3249 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003250 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003251 if (T)
3252 return QualType(T, 0);
3253
Douglas Gregorc42075a2010-02-04 18:10:26 +00003254 QualType Canon = NamedType;
3255 if (!Canon.isCanonical()) {
3256 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003257 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3258 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003259 (void)CheckT;
3260 }
3261
Abramo Bagnara6150c882010-05-11 21:36:43 +00003262 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003263 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003264 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003265 return QualType(T, 0);
3266}
3267
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003268QualType
Jay Foad39c79802011-01-12 09:06:06 +00003269ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003270 llvm::FoldingSetNodeID ID;
3271 ParenType::Profile(ID, InnerType);
3272
3273 void *InsertPos = 0;
3274 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3275 if (T)
3276 return QualType(T, 0);
3277
3278 QualType Canon = InnerType;
3279 if (!Canon.isCanonical()) {
3280 Canon = getCanonicalType(InnerType);
3281 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3282 assert(!CheckT && "Paren canonical type broken");
3283 (void)CheckT;
3284 }
3285
3286 T = new (*this) ParenType(InnerType, Canon);
3287 Types.push_back(T);
3288 ParenTypes.InsertNode(T, InsertPos);
3289 return QualType(T, 0);
3290}
3291
Douglas Gregor02085352010-03-31 20:19:30 +00003292QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3293 NestedNameSpecifier *NNS,
3294 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003295 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003296 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
3297
3298 if (Canon.isNull()) {
3299 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00003300 ElaboratedTypeKeyword CanonKeyword = Keyword;
3301 if (Keyword == ETK_None)
3302 CanonKeyword = ETK_Typename;
3303
3304 if (CanonNNS != NNS || CanonKeyword != Keyword)
3305 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003306 }
3307
3308 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003309 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003310
3311 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003312 DependentNameType *T
3313 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003314 if (T)
3315 return QualType(T, 0);
3316
Douglas Gregor02085352010-03-31 20:19:30 +00003317 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003318 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003319 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003320 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003321}
3322
Mike Stump11289f42009-09-09 15:08:12 +00003323QualType
John McCallc392f372010-06-11 00:33:02 +00003324ASTContext::getDependentTemplateSpecializationType(
3325 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003326 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003327 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003328 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003329 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003330 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003331 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3332 ArgCopy.push_back(Args[I].getArgument());
3333 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3334 ArgCopy.size(),
3335 ArgCopy.data());
3336}
3337
3338QualType
3339ASTContext::getDependentTemplateSpecializationType(
3340 ElaboratedTypeKeyword Keyword,
3341 NestedNameSpecifier *NNS,
3342 const IdentifierInfo *Name,
3343 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00003344 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003345 assert((!NNS || NNS->isDependent()) &&
3346 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003347
Douglas Gregorc42075a2010-02-04 18:10:26 +00003348 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003349 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3350 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003351
3352 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00003353 DependentTemplateSpecializationType *T
3354 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003355 if (T)
3356 return QualType(T, 0);
3357
John McCallc392f372010-06-11 00:33:02 +00003358 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003359
John McCallc392f372010-06-11 00:33:02 +00003360 ElaboratedTypeKeyword CanonKeyword = Keyword;
3361 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3362
3363 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003364 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003365 for (unsigned I = 0; I != NumArgs; ++I) {
3366 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3367 if (!CanonArgs[I].structurallyEquals(Args[I]))
3368 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003369 }
3370
John McCallc392f372010-06-11 00:33:02 +00003371 QualType Canon;
3372 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3373 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3374 Name, NumArgs,
3375 CanonArgs.data());
3376
3377 // Find the insert position again.
3378 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3379 }
3380
3381 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3382 sizeof(TemplateArgument) * NumArgs),
3383 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003384 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00003385 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003386 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003387 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003388 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003389}
3390
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003391QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00003392 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003393 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003394 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003395
3396 assert(Pattern->containsUnexpandedParameterPack() &&
3397 "Pack expansions must expand one or more parameter packs");
3398 void *InsertPos = 0;
3399 PackExpansionType *T
3400 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3401 if (T)
3402 return QualType(T, 0);
3403
3404 QualType Canon;
3405 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003406 Canon = getCanonicalType(Pattern);
3407 // The canonical type might not contain an unexpanded parameter pack, if it
3408 // contains an alias template specialization which ignores one of its
3409 // parameters.
3410 if (Canon->containsUnexpandedParameterPack()) {
3411 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003412
Richard Smith68eea502012-07-16 00:20:35 +00003413 // Find the insert position again, in case we inserted an element into
3414 // PackExpansionTypes and invalidated our insert position.
3415 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3416 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003417 }
3418
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003419 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003420 Types.push_back(T);
3421 PackExpansionTypes.InsertNode(T, InsertPos);
3422 return QualType(T, 0);
3423}
3424
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003425/// CmpProtocolNames - Comparison predicate for sorting protocols
3426/// alphabetically.
3427static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3428 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00003429 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003430}
3431
John McCall8b07ec22010-05-15 11:32:37 +00003432static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00003433 unsigned NumProtocols) {
3434 if (NumProtocols == 0) return true;
3435
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003436 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3437 return false;
3438
John McCallfc93cf92009-10-22 22:37:11 +00003439 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003440 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3441 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003442 return false;
3443 return true;
3444}
3445
3446static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003447 unsigned &NumProtocols) {
3448 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00003449
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003450 // Sort protocols, keyed by name.
3451 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3452
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003453 // Canonicalize.
3454 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3455 Protocols[I] = Protocols[I]->getCanonicalDecl();
3456
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003457 // Remove duplicates.
3458 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3459 NumProtocols = ProtocolsEnd-Protocols;
3460}
3461
John McCall8b07ec22010-05-15 11:32:37 +00003462QualType ASTContext::getObjCObjectType(QualType BaseType,
3463 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003464 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00003465 // If the base type is an interface and there aren't any protocols
3466 // to add, then the interface type will do just fine.
3467 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3468 return BaseType;
3469
3470 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003471 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00003472 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00003473 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00003474 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3475 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003476
John McCall8b07ec22010-05-15 11:32:37 +00003477 // Build the canonical type, which has the canonical base type and
3478 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00003479 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00003480 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3481 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3482 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003483 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003484 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003485 unsigned UniqueCount = NumProtocols;
3486
John McCallfc93cf92009-10-22 22:37:11 +00003487 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00003488 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3489 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00003490 } else {
John McCall8b07ec22010-05-15 11:32:37 +00003491 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3492 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003493 }
3494
3495 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003496 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3497 }
3498
3499 unsigned Size = sizeof(ObjCObjectTypeImpl);
3500 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3501 void *Mem = Allocate(Size, TypeAlignment);
3502 ObjCObjectTypeImpl *T =
3503 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3504
3505 Types.push_back(T);
3506 ObjCObjectTypes.InsertNode(T, InsertPos);
3507 return QualType(T, 0);
3508}
3509
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003510/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
3511/// protocol list adopt all protocols in QT's qualified-id protocol
3512/// list.
3513bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
3514 ObjCInterfaceDecl *IC) {
3515 if (!QT->isObjCQualifiedIdType())
3516 return false;
3517
3518 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
3519 // If both the right and left sides have qualifiers.
3520 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3521 E = OPT->qual_end(); I != E; ++I) {
3522 ObjCProtocolDecl *Proto = *I;
3523 if (!IC->ClassImplementsProtocol(Proto, false))
3524 return false;
3525 }
3526 return true;
3527 }
3528 return false;
3529}
3530
3531/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
3532/// QT's qualified-id protocol list adopt all protocols in IDecl's list
3533/// of protocols.
3534bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
3535 ObjCInterfaceDecl *IDecl) {
3536 if (!QT->isObjCQualifiedIdType())
3537 return false;
3538 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
3539 if (!OPT)
3540 return false;
3541 if (!IDecl->hasDefinition())
3542 return false;
3543 ObjCInterfaceDecl::protocol_iterator PI = IDecl->protocol_begin(),
3544 E = IDecl->protocol_end();
3545 if (PI == E)
3546 return (IDecl->getSuperClass()
3547 ? QIdProtocolsAdoptObjCObjectProtocols(QT, IDecl->getSuperClass())
3548 : false);
3549
3550 for (; PI != E; ++PI) {
3551 // If both the right and left sides have qualifiers.
3552 bool Adopts = false;
3553 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3554 E = OPT->qual_end(); I != E; ++I) {
3555 ObjCProtocolDecl *Proto = *I;
3556 // return 'true' if '*PI' is in the inheritance hierarchy of Proto
3557 if ((Adopts = ProtocolCompatibleWithProtocol(*PI, Proto)))
3558 break;
3559 }
3560 if (!Adopts)
3561 return (IDecl->getSuperClass()
3562 ? QIdProtocolsAdoptObjCObjectProtocols(QT, IDecl->getSuperClass())
3563 : false);
3564 }
3565 return true;
3566}
3567
John McCall8b07ec22010-05-15 11:32:37 +00003568/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3569/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003570QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003571 llvm::FoldingSetNodeID ID;
3572 ObjCObjectPointerType::Profile(ID, ObjectT);
3573
3574 void *InsertPos = 0;
3575 if (ObjCObjectPointerType *QT =
3576 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3577 return QualType(QT, 0);
3578
3579 // Find the canonical object type.
3580 QualType Canonical;
3581 if (!ObjectT.isCanonical()) {
3582 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3583
3584 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003585 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3586 }
3587
Douglas Gregorf85bee62010-02-08 22:59:26 +00003588 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003589 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3590 ObjCObjectPointerType *QType =
3591 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003592
Steve Narofffb4330f2009-06-17 22:40:22 +00003593 Types.push_back(QType);
3594 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003595 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003596}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003597
Douglas Gregor1c283312010-08-11 12:19:30 +00003598/// getObjCInterfaceType - Return the unique reference to the type for the
3599/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003600QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3601 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003602 if (Decl->TypeForDecl)
3603 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003604
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003605 if (PrevDecl) {
3606 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3607 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3608 return QualType(PrevDecl->TypeForDecl, 0);
3609 }
3610
Douglas Gregor7671e532011-12-16 16:34:57 +00003611 // Prefer the definition, if there is one.
3612 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3613 Decl = Def;
3614
Douglas Gregor1c283312010-08-11 12:19:30 +00003615 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3616 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3617 Decl->TypeForDecl = T;
3618 Types.push_back(T);
3619 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003620}
3621
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003622/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3623/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003624/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003625/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003626/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003627QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003628 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003629 if (tofExpr->isTypeDependent()) {
3630 llvm::FoldingSetNodeID ID;
3631 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003632
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003633 void *InsertPos = 0;
3634 DependentTypeOfExprType *Canon
3635 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3636 if (Canon) {
3637 // We already have a "canonical" version of an identical, dependent
3638 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003639 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003640 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003641 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003642 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003643 Canon
3644 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003645 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3646 toe = Canon;
3647 }
3648 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003649 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003650 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003651 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003652 Types.push_back(toe);
3653 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003654}
3655
Steve Naroffa773cd52007-08-01 18:02:17 +00003656/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3657/// TypeOfType AST's. The only motivation to unique these nodes would be
3658/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003659/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003660/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003661QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003662 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003663 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003664 Types.push_back(tot);
3665 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003666}
3667
Anders Carlssonad6bd352009-06-24 21:24:56 +00003668
Anders Carlsson81df7b82009-06-24 19:06:50 +00003669/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3670/// DecltypeType AST's. The only motivation to unique these nodes would be
3671/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003672/// an issue. This doesn't effect the type checker, since it operates
David Blaikie876657b2011-11-06 22:28:03 +00003673/// on canonical types (which are always unique).
Douglas Gregor81495f32012-02-12 18:42:33 +00003674QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003675 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003676
3677 // C++0x [temp.type]p2:
3678 // If an expression e involves a template parameter, decltype(e) denotes a
3679 // unique dependent type. Two such decltype-specifiers refer to the same
3680 // type only if their expressions are equivalent (14.5.6.1).
3681 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003682 llvm::FoldingSetNodeID ID;
3683 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003684
Douglas Gregora21f6c32009-07-30 23:36:40 +00003685 void *InsertPos = 0;
3686 DependentDecltypeType *Canon
3687 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3688 if (Canon) {
3689 // We already have a "canonical" version of an equivalent, dependent
3690 // decltype type. Use that as our canonical type.
Richard Smithef8bf432012-08-13 20:08:14 +00003691 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
Douglas Gregora21f6c32009-07-30 23:36:40 +00003692 QualType((DecltypeType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003693 } else {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003694 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003695 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003696 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3697 dt = Canon;
3698 }
3699 } else {
Douglas Gregor81495f32012-02-12 18:42:33 +00003700 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3701 getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003702 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003703 Types.push_back(dt);
3704 return QualType(dt, 0);
3705}
3706
Alexis Hunte852b102011-05-24 22:41:36 +00003707/// getUnaryTransformationType - We don't unique these, since the memory
3708/// savings are minimal and these are rare.
3709QualType ASTContext::getUnaryTransformType(QualType BaseType,
3710 QualType UnderlyingType,
3711 UnaryTransformType::UTTKind Kind)
3712 const {
3713 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003714 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3715 Kind,
3716 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003717 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003718 Types.push_back(Ty);
3719 return QualType(Ty, 0);
3720}
3721
Richard Smith2a7d4812013-05-04 07:00:32 +00003722/// getAutoType - Return the uniqued reference to the 'auto' type which has been
3723/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3724/// canonical deduced-but-dependent 'auto' type.
3725QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003726 bool IsDependent) const {
3727 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00003728 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003729
Richard Smith2a7d4812013-05-04 07:00:32 +00003730 // Look in the folding set for an existing type.
Richard Smithb2bc2e62011-02-21 20:05:19 +00003731 void *InsertPos = 0;
Richard Smith2a7d4812013-05-04 07:00:32 +00003732 llvm::FoldingSetNodeID ID;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003733 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00003734 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3735 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003736
Richard Smith74aeef52013-04-26 16:15:35 +00003737 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smith27d807c2013-04-30 13:56:41 +00003738 IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003739 IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003740 Types.push_back(AT);
3741 if (InsertPos)
3742 AutoTypes.InsertNode(AT, InsertPos);
3743 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003744}
3745
Eli Friedman0dfb8892011-10-06 23:00:33 +00003746/// getAtomicType - Return the uniqued reference to the atomic type for
3747/// the given value type.
3748QualType ASTContext::getAtomicType(QualType T) const {
3749 // Unique pointers, to guarantee there is only one pointer of a particular
3750 // structure.
3751 llvm::FoldingSetNodeID ID;
3752 AtomicType::Profile(ID, T);
3753
3754 void *InsertPos = 0;
3755 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3756 return QualType(AT, 0);
3757
3758 // If the atomic value type isn't canonical, this won't be a canonical type
3759 // either, so fill in the canonical type field.
3760 QualType Canonical;
3761 if (!T.isCanonical()) {
3762 Canonical = getAtomicType(getCanonicalType(T));
3763
3764 // Get the new insert position for the node we care about.
3765 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3766 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3767 }
3768 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3769 Types.push_back(New);
3770 AtomicTypes.InsertNode(New, InsertPos);
3771 return QualType(New, 0);
3772}
3773
Richard Smith02e85f32011-04-14 22:09:26 +00003774/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3775QualType ASTContext::getAutoDeductType() const {
3776 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00003777 AutoDeductTy = QualType(
3778 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003779 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00003780 0);
Richard Smith02e85f32011-04-14 22:09:26 +00003781 return AutoDeductTy;
3782}
3783
3784/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3785QualType ASTContext::getAutoRRefDeductType() const {
3786 if (AutoRRefDeductTy.isNull())
3787 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3788 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3789 return AutoRRefDeductTy;
3790}
3791
Chris Lattnerfb072462007-01-23 05:45:31 +00003792/// getTagDeclType - Return the unique reference to the type for the
3793/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003794QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003795 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003796 // FIXME: What is the design on getTagDeclType when it requires casting
3797 // away const? mutable?
3798 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003799}
3800
Mike Stump11289f42009-09-09 15:08:12 +00003801/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3802/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3803/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003804CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003805 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003806}
Chris Lattnerfb072462007-01-23 05:45:31 +00003807
Hans Wennborg27541db2011-10-27 08:29:09 +00003808/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3809CanQualType ASTContext::getIntMaxType() const {
3810 return getFromTargetType(Target->getIntMaxType());
3811}
3812
3813/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3814CanQualType ASTContext::getUIntMaxType() const {
3815 return getFromTargetType(Target->getUIntMaxType());
3816}
3817
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003818/// getSignedWCharType - Return the type of "signed wchar_t".
3819/// Used when in C++, as a GCC extension.
3820QualType ASTContext::getSignedWCharType() const {
3821 // FIXME: derive from "Target" ?
3822 return WCharTy;
3823}
3824
3825/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3826/// Used when in C++, as a GCC extension.
3827QualType ASTContext::getUnsignedWCharType() const {
3828 // FIXME: derive from "Target" ?
3829 return UnsignedIntTy;
3830}
3831
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00003832QualType ASTContext::getIntPtrType() const {
3833 return getFromTargetType(Target->getIntPtrType());
3834}
3835
3836QualType ASTContext::getUIntPtrType() const {
3837 return getCorrespondingUnsignedType(getIntPtrType());
3838}
3839
Hans Wennborg27541db2011-10-27 08:29:09 +00003840/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003841/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3842QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003843 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003844}
3845
Eli Friedman4e91899e2012-11-27 02:58:24 +00003846/// \brief Return the unique type for "pid_t" defined in
3847/// <sys/types.h>. We need this to compute the correct type for vfork().
3848QualType ASTContext::getProcessIDType() const {
3849 return getFromTargetType(Target->getProcessIDType());
3850}
3851
Chris Lattnera21ad802008-04-02 05:18:44 +00003852//===----------------------------------------------------------------------===//
3853// Type Operators
3854//===----------------------------------------------------------------------===//
3855
Jay Foad39c79802011-01-12 09:06:06 +00003856CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003857 // Push qualifiers into arrays, and then discard any remaining
3858 // qualifiers.
3859 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003860 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003861 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003862 QualType Result;
3863 if (isa<ArrayType>(Ty)) {
3864 Result = getArrayDecayedType(QualType(Ty,0));
3865 } else if (isa<FunctionType>(Ty)) {
3866 Result = getPointerType(QualType(Ty, 0));
3867 } else {
3868 Result = QualType(Ty, 0);
3869 }
3870
3871 return CanQualType::CreateUnsafe(Result);
3872}
3873
John McCall6c9dd522011-01-18 07:41:22 +00003874QualType ASTContext::getUnqualifiedArrayType(QualType type,
3875 Qualifiers &quals) {
3876 SplitQualType splitType = type.getSplitUnqualifiedType();
3877
3878 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3879 // the unqualified desugared type and then drops it on the floor.
3880 // We then have to strip that sugar back off with
3881 // getUnqualifiedDesugaredType(), which is silly.
3882 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003883 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003884
3885 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003886 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003887 quals = splitType.Quals;
3888 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003889 }
3890
John McCall6c9dd522011-01-18 07:41:22 +00003891 // Otherwise, recurse on the array's element type.
3892 QualType elementType = AT->getElementType();
3893 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3894
3895 // If that didn't change the element type, AT has no qualifiers, so we
3896 // can just use the results in splitType.
3897 if (elementType == unqualElementType) {
3898 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00003899 quals = splitType.Quals;
3900 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00003901 }
3902
3903 // Otherwise, add in the qualifiers from the outermost type, then
3904 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00003905 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003906
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003907 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003908 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003909 CAT->getSizeModifier(), 0);
3910 }
3911
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003912 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003913 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003914 }
3915
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003916 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003917 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003918 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003919 VAT->getSizeModifier(),
3920 VAT->getIndexTypeCVRQualifiers(),
3921 VAT->getBracketsRange());
3922 }
3923
3924 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003925 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003926 DSAT->getSizeModifier(), 0,
3927 SourceRange());
3928}
3929
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003930/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3931/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3932/// they point to and return true. If T1 and T2 aren't pointer types
3933/// or pointer-to-member types, or if they are not similar at this
3934/// level, returns false and leaves T1 and T2 unchanged. Top-level
3935/// qualifiers on T1 and T2 are ignored. This function will typically
3936/// be called in a loop that successively "unwraps" pointer and
3937/// pointer-to-member types to compare them at each level.
3938bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3939 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3940 *T2PtrType = T2->getAs<PointerType>();
3941 if (T1PtrType && T2PtrType) {
3942 T1 = T1PtrType->getPointeeType();
3943 T2 = T2PtrType->getPointeeType();
3944 return true;
3945 }
3946
3947 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3948 *T2MPType = T2->getAs<MemberPointerType>();
3949 if (T1MPType && T2MPType &&
3950 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3951 QualType(T2MPType->getClass(), 0))) {
3952 T1 = T1MPType->getPointeeType();
3953 T2 = T2MPType->getPointeeType();
3954 return true;
3955 }
3956
David Blaikiebbafb8a2012-03-11 07:00:24 +00003957 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003958 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3959 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3960 if (T1OPType && T2OPType) {
3961 T1 = T1OPType->getPointeeType();
3962 T2 = T2OPType->getPointeeType();
3963 return true;
3964 }
3965 }
3966
3967 // FIXME: Block pointers, too?
3968
3969 return false;
3970}
3971
Jay Foad39c79802011-01-12 09:06:06 +00003972DeclarationNameInfo
3973ASTContext::getNameForTemplate(TemplateName Name,
3974 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003975 switch (Name.getKind()) {
3976 case TemplateName::QualifiedTemplate:
3977 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003978 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00003979 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3980 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003981
John McCalld9dfe3a2011-06-30 08:33:18 +00003982 case TemplateName::OverloadedTemplate: {
3983 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3984 // DNInfo work in progress: CHECKME: what about DNLoc?
3985 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3986 }
3987
3988 case TemplateName::DependentTemplate: {
3989 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003990 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00003991 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003992 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3993 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00003994 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003995 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3996 // DNInfo work in progress: FIXME: source locations?
3997 DeclarationNameLoc DNLoc;
3998 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3999 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4000 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00004001 }
4002 }
4003
John McCalld9dfe3a2011-06-30 08:33:18 +00004004 case TemplateName::SubstTemplateTemplateParm: {
4005 SubstTemplateTemplateParmStorage *subst
4006 = Name.getAsSubstTemplateTemplateParm();
4007 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4008 NameLoc);
4009 }
4010
4011 case TemplateName::SubstTemplateTemplateParmPack: {
4012 SubstTemplateTemplateParmPackStorage *subst
4013 = Name.getAsSubstTemplateTemplateParmPack();
4014 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4015 NameLoc);
4016 }
4017 }
4018
4019 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00004020}
4021
Jay Foad39c79802011-01-12 09:06:06 +00004022TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004023 switch (Name.getKind()) {
4024 case TemplateName::QualifiedTemplate:
4025 case TemplateName::Template: {
4026 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004027 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00004028 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004029 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4030
4031 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004032 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004033 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00004034
John McCalld9dfe3a2011-06-30 08:33:18 +00004035 case TemplateName::OverloadedTemplate:
4036 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00004037
John McCalld9dfe3a2011-06-30 08:33:18 +00004038 case TemplateName::DependentTemplate: {
4039 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4040 assert(DTN && "Non-dependent template names must refer to template decls.");
4041 return DTN->CanonicalTemplateName;
4042 }
4043
4044 case TemplateName::SubstTemplateTemplateParm: {
4045 SubstTemplateTemplateParmStorage *subst
4046 = Name.getAsSubstTemplateTemplateParm();
4047 return getCanonicalTemplateName(subst->getReplacement());
4048 }
4049
4050 case TemplateName::SubstTemplateTemplateParmPack: {
4051 SubstTemplateTemplateParmPackStorage *subst
4052 = Name.getAsSubstTemplateTemplateParmPack();
4053 TemplateTemplateParmDecl *canonParameter
4054 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4055 TemplateArgument canonArgPack
4056 = getCanonicalTemplateArgument(subst->getArgumentPack());
4057 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4058 }
4059 }
4060
4061 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00004062}
4063
Douglas Gregoradee3e32009-11-11 23:06:43 +00004064bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4065 X = getCanonicalTemplateName(X);
4066 Y = getCanonicalTemplateName(Y);
4067 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4068}
4069
Mike Stump11289f42009-09-09 15:08:12 +00004070TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00004071ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00004072 switch (Arg.getKind()) {
4073 case TemplateArgument::Null:
4074 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004075
Douglas Gregora8e02e72009-07-28 23:00:59 +00004076 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00004077 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004078
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004079 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00004080 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
4081 return TemplateArgument(D, Arg.isDeclForReferenceParam());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004082 }
Mike Stump11289f42009-09-09 15:08:12 +00004083
Eli Friedmanb826a002012-09-26 02:36:12 +00004084 case TemplateArgument::NullPtr:
4085 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4086 /*isNullPtr*/true);
4087
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004088 case TemplateArgument::Template:
4089 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004090
4091 case TemplateArgument::TemplateExpansion:
4092 return TemplateArgument(getCanonicalTemplateName(
4093 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00004094 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004095
Douglas Gregora8e02e72009-07-28 23:00:59 +00004096 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004097 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00004098
Douglas Gregora8e02e72009-07-28 23:00:59 +00004099 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00004100 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00004101
Douglas Gregora8e02e72009-07-28 23:00:59 +00004102 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00004103 if (Arg.pack_size() == 0)
4104 return Arg;
4105
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004106 TemplateArgument *CanonArgs
4107 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00004108 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004109 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00004110 AEnd = Arg.pack_end();
4111 A != AEnd; (void)++A, ++Idx)
4112 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00004113
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004114 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00004115 }
4116 }
4117
4118 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00004119 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00004120}
4121
Douglas Gregor333489b2009-03-27 23:10:48 +00004122NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00004123ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00004124 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00004125 return 0;
4126
4127 switch (NNS->getKind()) {
4128 case NestedNameSpecifier::Identifier:
4129 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00004130 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00004131 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4132 NNS->getAsIdentifier());
4133
4134 case NestedNameSpecifier::Namespace:
4135 // A namespace is canonical; build a nested-name-specifier with
4136 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004137 return NestedNameSpecifier::Create(*this, 0,
4138 NNS->getAsNamespace()->getOriginalNamespace());
4139
4140 case NestedNameSpecifier::NamespaceAlias:
4141 // A namespace is canonical; build a nested-name-specifier with
4142 // this namespace and no prefix.
4143 return NestedNameSpecifier::Create(*this, 0,
4144 NNS->getAsNamespaceAlias()->getNamespace()
4145 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00004146
4147 case NestedNameSpecifier::TypeSpec:
4148 case NestedNameSpecifier::TypeSpecWithTemplate: {
4149 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004150
4151 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4152 // break it apart into its prefix and identifier, then reconsititute those
4153 // as the canonical nested-name-specifier. This is required to canonicalize
4154 // a dependent nested-name-specifier involving typedefs of dependent-name
4155 // types, e.g.,
4156 // typedef typename T::type T1;
4157 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00004158 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4159 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00004160 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004161
Eli Friedman5358a0a2012-03-03 04:09:56 +00004162 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4163 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4164 // first place?
John McCall33ddac02011-01-19 10:06:00 +00004165 return NestedNameSpecifier::Create(*this, 0, false,
4166 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00004167 }
4168
4169 case NestedNameSpecifier::Global:
4170 // The global specifier is canonical and unique.
4171 return NNS;
4172 }
4173
David Blaikie8a40f702012-01-17 06:56:22 +00004174 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00004175}
4176
Chris Lattner7adf0762008-08-04 07:31:14 +00004177
Jay Foad39c79802011-01-12 09:06:06 +00004178const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004179 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004180 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00004181 // Handle the common positive case fast.
4182 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4183 return AT;
4184 }
Mike Stump11289f42009-09-09 15:08:12 +00004185
John McCall8ccfcb52009-09-24 19:53:00 +00004186 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00004187 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00004188 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004189
John McCall8ccfcb52009-09-24 19:53:00 +00004190 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00004191 // implements C99 6.7.3p8: "If the specification of an array type includes
4192 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00004193
Chris Lattner7adf0762008-08-04 07:31:14 +00004194 // If we get here, we either have type qualifiers on the type, or we have
4195 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00004196 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00004197
John McCall33ddac02011-01-19 10:06:00 +00004198 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004199 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00004200
Chris Lattner7adf0762008-08-04 07:31:14 +00004201 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00004202 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall33ddac02011-01-19 10:06:00 +00004203 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00004204 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00004205
Chris Lattner7adf0762008-08-04 07:31:14 +00004206 // Otherwise, we have an array and we have qualifiers on it. Push the
4207 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00004208 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00004209
Chris Lattner7adf0762008-08-04 07:31:14 +00004210 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4211 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4212 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004213 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00004214 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4215 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4216 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004217 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00004218
Mike Stump11289f42009-09-09 15:08:12 +00004219 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00004220 = dyn_cast<DependentSizedArrayType>(ATy))
4221 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00004222 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004223 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00004224 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004225 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004226 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00004227
Chris Lattner7adf0762008-08-04 07:31:14 +00004228 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00004229 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004230 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00004231 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004232 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004233 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00004234}
4235
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004236QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00004237 if (T->isArrayType() || T->isFunctionType())
4238 return getDecayedType(T);
4239 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00004240}
4241
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004242QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004243 T = getVariableArrayDecayedType(T);
4244 T = getAdjustedParameterType(T);
4245 return T.getUnqualifiedType();
4246}
4247
Chris Lattnera21ad802008-04-02 05:18:44 +00004248/// getArrayDecayedType - Return the properly qualified result of decaying the
4249/// specified array type to a pointer. This operation is non-trivial when
4250/// handling typedefs etc. The canonical type of "T" must be an array type,
4251/// this returns a pointer to a properly qualified element of the array.
4252///
4253/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004254QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004255 // Get the element type with 'getAsArrayType' so that we don't lose any
4256 // typedefs in the element type of the array. This also handles propagation
4257 // of type qualifiers from the array type into the element type if present
4258 // (C99 6.7.3p8).
4259 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4260 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004261
Chris Lattner7adf0762008-08-04 07:31:14 +00004262 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004263
4264 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00004265 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00004266}
4267
John McCall33ddac02011-01-19 10:06:00 +00004268QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4269 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00004270}
4271
John McCall33ddac02011-01-19 10:06:00 +00004272QualType ASTContext::getBaseElementType(QualType type) const {
4273 Qualifiers qs;
4274 while (true) {
4275 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004276 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00004277 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00004278
John McCall33ddac02011-01-19 10:06:00 +00004279 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00004280 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00004281 }
Mike Stump11289f42009-09-09 15:08:12 +00004282
John McCall33ddac02011-01-19 10:06:00 +00004283 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00004284}
4285
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004286/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00004287uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004288ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4289 uint64_t ElementCount = 1;
4290 do {
4291 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00004292 CA = dyn_cast_or_null<ConstantArrayType>(
4293 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004294 } while (CA);
4295 return ElementCount;
4296}
4297
Steve Naroff0af91202007-04-27 21:51:21 +00004298/// getFloatingRank - Return a relative rank for floating point types.
4299/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00004300static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00004301 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00004302 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00004303
John McCall9dd450b2009-09-21 23:43:11 +00004304 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4305 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004306 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004307 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00004308 case BuiltinType::Float: return FloatRank;
4309 case BuiltinType::Double: return DoubleRank;
4310 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00004311 }
4312}
4313
Mike Stump11289f42009-09-09 15:08:12 +00004314/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4315/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00004316/// 'typeDomain' is a real floating point or complex type.
4317/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004318QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4319 QualType Domain) const {
4320 FloatingRank EltRank = getFloatingRank(Size);
4321 if (Domain->isComplexType()) {
4322 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004323 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00004324 case FloatRank: return FloatComplexTy;
4325 case DoubleRank: return DoubleComplexTy;
4326 case LongDoubleRank: return LongDoubleComplexTy;
4327 }
Steve Naroff0af91202007-04-27 21:51:21 +00004328 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004329
4330 assert(Domain->isRealFloatingType() && "Unknown domain!");
4331 switch (EltRank) {
Joey Goulydd7f4562013-01-23 11:56:20 +00004332 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004333 case FloatRank: return FloatTy;
4334 case DoubleRank: return DoubleTy;
4335 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00004336 }
David Blaikief47fa302012-01-17 02:30:50 +00004337 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00004338}
4339
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004340/// getFloatingTypeOrder - Compare the rank of the two specified floating
4341/// point types, ignoring the domain of the type (i.e. 'double' ==
4342/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004343/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004344int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00004345 FloatingRank LHSR = getFloatingRank(LHS);
4346 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004347
Chris Lattnerb90739d2008-04-06 23:38:49 +00004348 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004349 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00004350 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004351 return 1;
4352 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00004353}
4354
Chris Lattner76a00cf2008-04-06 22:59:24 +00004355/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4356/// routine will assert if passed a built-in type that isn't an integer or enum,
4357/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00004358unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00004359 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004360
Chris Lattner76a00cf2008-04-06 22:59:24 +00004361 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004362 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004363 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004364 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004365 case BuiltinType::Char_S:
4366 case BuiltinType::Char_U:
4367 case BuiltinType::SChar:
4368 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004369 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004370 case BuiltinType::Short:
4371 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004372 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004373 case BuiltinType::Int:
4374 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004375 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004376 case BuiltinType::Long:
4377 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004378 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004379 case BuiltinType::LongLong:
4380 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004381 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00004382 case BuiltinType::Int128:
4383 case BuiltinType::UInt128:
4384 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00004385 }
4386}
4387
Eli Friedman629ffb92009-08-20 04:21:42 +00004388/// \brief Whether this is a promotable bitfield reference according
4389/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4390///
4391/// \returns the type this bit-field will promote to, or NULL if no
4392/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004393QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004394 if (E->isTypeDependent() || E->isValueDependent())
4395 return QualType();
4396
John McCalld25db7e2013-05-06 21:39:12 +00004397 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00004398 if (!Field)
4399 return QualType();
4400
4401 QualType FT = Field->getType();
4402
Richard Smithcaf33902011-10-10 18:28:20 +00004403 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004404 uint64_t IntSize = getTypeSize(IntTy);
4405 // GCC extension compatibility: if the bit-field size is less than or equal
4406 // to the size of int, it gets promoted no matter what its type is.
4407 // For instance, unsigned long bf : 4 gets promoted to signed int.
4408 if (BitWidth < IntSize)
4409 return IntTy;
4410
4411 if (BitWidth == IntSize)
4412 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4413
4414 // Types bigger than int are not subject to promotions, and therefore act
4415 // like the base type.
4416 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4417 // is ridiculous.
4418 return QualType();
4419}
4420
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004421/// getPromotedIntegerType - Returns the type that Promotable will
4422/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4423/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004424QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004425 assert(!Promotable.isNull());
4426 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004427 if (const EnumType *ET = Promotable->getAs<EnumType>())
4428 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004429
4430 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4431 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4432 // (3.9.1) can be converted to a prvalue of the first of the following
4433 // types that can represent all the values of its underlying type:
4434 // int, unsigned int, long int, unsigned long int, long long int, or
4435 // unsigned long long int [...]
4436 // FIXME: Is there some better way to compute this?
4437 if (BT->getKind() == BuiltinType::WChar_S ||
4438 BT->getKind() == BuiltinType::WChar_U ||
4439 BT->getKind() == BuiltinType::Char16 ||
4440 BT->getKind() == BuiltinType::Char32) {
4441 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4442 uint64_t FromSize = getTypeSize(BT);
4443 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4444 LongLongTy, UnsignedLongLongTy };
4445 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4446 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4447 if (FromSize < ToSize ||
4448 (FromSize == ToSize &&
4449 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4450 return PromoteTypes[Idx];
4451 }
4452 llvm_unreachable("char type should fit into long long");
4453 }
4454 }
4455
4456 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004457 if (Promotable->isSignedIntegerType())
4458 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00004459 uint64_t PromotableSize = getIntWidth(Promotable);
4460 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004461 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4462 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4463}
4464
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004465/// \brief Recurses in pointer/array types until it finds an objc retainable
4466/// type and returns its ownership.
4467Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4468 while (!T.isNull()) {
4469 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4470 return T.getObjCLifetime();
4471 if (T->isArrayType())
4472 T = getBaseElementType(T);
4473 else if (const PointerType *PT = T->getAs<PointerType>())
4474 T = PT->getPointeeType();
4475 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004476 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004477 else
4478 break;
4479 }
4480
4481 return Qualifiers::OCL_None;
4482}
4483
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004484static const Type *getIntegerTypeForEnum(const EnumType *ET) {
4485 // Incomplete enum types are not treated as integer types.
4486 // FIXME: In C++, enum types are never integer types.
4487 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
4488 return ET->getDecl()->getIntegerType().getTypePtr();
4489 return NULL;
4490}
4491
Mike Stump11289f42009-09-09 15:08:12 +00004492/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004493/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004494/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004495int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004496 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4497 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004498
4499 // Unwrap enums to their underlying type.
4500 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
4501 LHSC = getIntegerTypeForEnum(ET);
4502 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
4503 RHSC = getIntegerTypeForEnum(ET);
4504
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004505 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004506
Chris Lattner76a00cf2008-04-06 22:59:24 +00004507 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4508 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004509
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004510 unsigned LHSRank = getIntegerRank(LHSC);
4511 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004512
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004513 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4514 if (LHSRank == RHSRank) return 0;
4515 return LHSRank > RHSRank ? 1 : -1;
4516 }
Mike Stump11289f42009-09-09 15:08:12 +00004517
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004518 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4519 if (LHSUnsigned) {
4520 // If the unsigned [LHS] type is larger, return it.
4521 if (LHSRank >= RHSRank)
4522 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004523
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004524 // If the signed type can represent all values of the unsigned type, it
4525 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004526 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004527 return -1;
4528 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004529
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004530 // If the unsigned [RHS] type is larger, return it.
4531 if (RHSRank >= LHSRank)
4532 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004533
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004534 // If the signed type can represent all values of the unsigned type, it
4535 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004536 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004537 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004538}
Anders Carlsson98f07902007-08-17 05:31:46 +00004539
Anders Carlsson6d417272009-11-14 21:45:58 +00004540static RecordDecl *
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004541CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
4542 DeclContext *DC, IdentifierInfo *Id) {
4543 SourceLocation Loc;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004544 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004545 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00004546 else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004547 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00004548}
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004549
Mike Stump11289f42009-09-09 15:08:12 +00004550// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00004551QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004552 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00004553 CFConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004554 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004555 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00004556 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004557
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004558 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00004559
Anders Carlsson98f07902007-08-17 05:31:46 +00004560 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004561 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004562 // int flags;
4563 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00004564 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004565 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00004566 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004567 FieldTypes[3] = LongTy;
4568
Anders Carlsson98f07902007-08-17 05:31:46 +00004569 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004570 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00004571 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004572 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00004573 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00004574 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00004575 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004576 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004577 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004578 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004579 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004580 }
4581
Douglas Gregord5058122010-02-11 01:19:42 +00004582 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00004583 }
Mike Stump11289f42009-09-09 15:08:12 +00004584
Anders Carlsson98f07902007-08-17 05:31:46 +00004585 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00004586}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004587
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004588QualType ASTContext::getObjCSuperType() const {
4589 if (ObjCSuperType.isNull()) {
4590 RecordDecl *ObjCSuperTypeDecl =
4591 CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get("objc_super"));
4592 TUDecl->addDecl(ObjCSuperTypeDecl);
4593 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4594 }
4595 return ObjCSuperType;
4596}
4597
Douglas Gregor512b0772009-04-23 22:29:11 +00004598void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004599 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00004600 assert(Rec && "Invalid CFConstantStringType");
4601 CFConstantStringTypeDecl = Rec->getDecl();
4602}
4603
Jay Foad39c79802011-01-12 09:06:06 +00004604QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004605 if (BlockDescriptorType)
4606 return getTagDeclType(BlockDescriptorType);
4607
4608 RecordDecl *T;
4609 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004610 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004611 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00004612 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004613
4614 QualType FieldTypes[] = {
4615 UnsignedLongTy,
4616 UnsignedLongTy,
4617 };
4618
Craig Topperd6d31ac2013-07-15 08:24:27 +00004619 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00004620 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004621 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004622 };
4623
4624 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004625 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00004626 SourceLocation(),
4627 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004628 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00004629 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004630 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004631 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004632 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00004633 T->addDecl(Field);
4634 }
4635
Douglas Gregord5058122010-02-11 01:19:42 +00004636 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004637
4638 BlockDescriptorType = T;
4639
4640 return getTagDeclType(BlockDescriptorType);
4641}
4642
Jay Foad39c79802011-01-12 09:06:06 +00004643QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004644 if (BlockDescriptorExtendedType)
4645 return getTagDeclType(BlockDescriptorExtendedType);
4646
4647 RecordDecl *T;
4648 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004649 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00004650 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00004651 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004652
4653 QualType FieldTypes[] = {
4654 UnsignedLongTy,
4655 UnsignedLongTy,
4656 getPointerType(VoidPtrTy),
4657 getPointerType(VoidPtrTy)
4658 };
4659
Craig Topperd6d31ac2013-07-15 08:24:27 +00004660 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004661 "reserved",
4662 "Size",
4663 "CopyFuncPtr",
4664 "DestroyFuncPtr"
4665 };
4666
4667 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004668 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004669 SourceLocation(),
4670 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00004671 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004672 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004673 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004674 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004675 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004676 T->addDecl(Field);
4677 }
4678
Douglas Gregord5058122010-02-11 01:19:42 +00004679 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004680
4681 BlockDescriptorExtendedType = T;
4682
4683 return getTagDeclType(BlockDescriptorExtendedType);
4684}
4685
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004686/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4687/// requires copy/dispose. Note that this must match the logic
4688/// in buildByrefHelpers.
4689bool ASTContext::BlockRequiresCopying(QualType Ty,
4690 const VarDecl *D) {
4691 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4692 const Expr *copyExpr = getBlockVarCopyInits(D);
4693 if (!copyExpr && record->hasTrivialDestructor()) return false;
4694
Mike Stump94967902009-10-21 18:16:27 +00004695 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004696 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004697
4698 if (!Ty->isObjCRetainableType()) return false;
4699
4700 Qualifiers qs = Ty.getQualifiers();
4701
4702 // If we have lifetime, that dominates.
4703 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4704 assert(getLangOpts().ObjCAutoRefCount);
4705
4706 switch (lifetime) {
4707 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4708
4709 // These are just bits as far as the runtime is concerned.
4710 case Qualifiers::OCL_ExplicitNone:
4711 case Qualifiers::OCL_Autoreleasing:
4712 return false;
4713
4714 // Tell the runtime that this is ARC __weak, called by the
4715 // byref routines.
4716 case Qualifiers::OCL_Weak:
4717 // ARC __strong __block variables need to be retained.
4718 case Qualifiers::OCL_Strong:
4719 return true;
4720 }
4721 llvm_unreachable("fell out of lifetime switch!");
4722 }
4723 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4724 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00004725}
4726
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004727bool ASTContext::getByrefLifetime(QualType Ty,
4728 Qualifiers::ObjCLifetime &LifeTime,
4729 bool &HasByrefExtendedLayout) const {
4730
4731 if (!getLangOpts().ObjC1 ||
4732 getLangOpts().getGC() != LangOptions::NonGC)
4733 return false;
4734
4735 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00004736 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004737 HasByrefExtendedLayout = true;
4738 LifeTime = Qualifiers::OCL_None;
4739 }
4740 else if (getLangOpts().ObjCAutoRefCount)
4741 LifeTime = Ty.getObjCLifetime();
4742 // MRR.
4743 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4744 LifeTime = Qualifiers::OCL_ExplicitNone;
4745 else
4746 LifeTime = Qualifiers::OCL_None;
4747 return true;
4748}
4749
Douglas Gregorbab8a962011-09-08 01:46:34 +00004750TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4751 if (!ObjCInstanceTypeDecl)
4752 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4753 getTranslationUnitDecl(),
4754 SourceLocation(),
4755 SourceLocation(),
4756 &Idents.get("instancetype"),
4757 getTrivialTypeSourceInfo(getObjCIdType()));
4758 return ObjCInstanceTypeDecl;
4759}
4760
Anders Carlsson18acd442007-10-29 06:33:42 +00004761// This returns true if a type has been typedefed to BOOL:
4762// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004763static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004764 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004765 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4766 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004767
Anders Carlssond8499822007-10-29 05:01:08 +00004768 return false;
4769}
4770
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004771/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004772/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004773CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004774 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4775 return CharUnits::Zero();
4776
Ken Dyck40775002010-01-11 17:06:35 +00004777 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004778
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004779 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004780 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004781 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004782 // Treat arrays as pointers, since that's how they're passed in.
4783 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004784 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004785 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004786}
4787
4788static inline
4789std::string charUnitsToString(const CharUnits &CU) {
4790 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004791}
4792
John McCall351762c2011-02-07 10:33:21 +00004793/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004794/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004795std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4796 std::string S;
4797
David Chisnall950a9512009-11-17 19:33:30 +00004798 const BlockDecl *Decl = Expr->getBlockDecl();
4799 QualType BlockTy =
4800 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4801 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004802 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004803 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None,
4804 BlockTy->getAs<FunctionType>()->getResultType(),
4805 S, true /*Extended*/);
4806 else
4807 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(),
4808 S);
David Chisnall950a9512009-11-17 19:33:30 +00004809 // Compute size of all parameters.
4810 // Start with computing size of a pointer in number of bytes.
4811 // FIXME: There might(should) be a better way of doing this computation!
4812 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004813 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4814 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00004815 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00004816 E = Decl->param_end(); PI != E; ++PI) {
4817 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004818 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00004819 if (sz.isZero())
4820 continue;
Ken Dyck40775002010-01-11 17:06:35 +00004821 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004822 ParmOffset += sz;
4823 }
4824 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004825 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004826 // Block pointer and offset.
4827 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004828
4829 // Argument types.
4830 ParmOffset = PtrSize;
4831 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4832 Decl->param_end(); PI != E; ++PI) {
4833 ParmVarDecl *PVDecl = *PI;
4834 QualType PType = PVDecl->getOriginalType();
4835 if (const ArrayType *AT =
4836 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4837 // Use array's original type only if it has known number of
4838 // elements.
4839 if (!isa<ConstantArrayType>(AT))
4840 PType = PVDecl->getType();
4841 } else if (PType->isFunctionType())
4842 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004843 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004844 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4845 S, true /*Extended*/);
4846 else
4847 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004848 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004849 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004850 }
John McCall351762c2011-02-07 10:33:21 +00004851
4852 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004853}
4854
Douglas Gregora9d84932011-05-27 01:19:52 +00004855bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004856 std::string& S) {
4857 // Encode result type.
4858 getObjCEncodingForType(Decl->getResultType(), S);
4859 CharUnits ParmOffset;
4860 // Compute size of all parameters.
4861 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4862 E = Decl->param_end(); PI != E; ++PI) {
4863 QualType PType = (*PI)->getType();
4864 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004865 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004866 continue;
4867
David Chisnall50e4eba2010-12-30 14:05:53 +00004868 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004869 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004870 ParmOffset += sz;
4871 }
4872 S += charUnitsToString(ParmOffset);
4873 ParmOffset = CharUnits::Zero();
4874
4875 // Argument types.
4876 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4877 E = Decl->param_end(); PI != E; ++PI) {
4878 ParmVarDecl *PVDecl = *PI;
4879 QualType PType = PVDecl->getOriginalType();
4880 if (const ArrayType *AT =
4881 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4882 // Use array's original type only if it has known number of
4883 // elements.
4884 if (!isa<ConstantArrayType>(AT))
4885 PType = PVDecl->getType();
4886 } else if (PType->isFunctionType())
4887 PType = PVDecl->getType();
4888 getObjCEncodingForType(PType, S);
4889 S += charUnitsToString(ParmOffset);
4890 ParmOffset += getObjCEncodingTypeSize(PType);
4891 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004892
4893 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004894}
4895
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004896/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4897/// method parameter or return type. If Extended, include class names and
4898/// block object types.
4899void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4900 QualType T, std::string& S,
4901 bool Extended) const {
4902 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4903 getObjCEncodingForTypeQualifier(QT, S);
4904 // Encode parameter type.
4905 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4906 true /*OutermostType*/,
4907 false /*EncodingProperty*/,
4908 false /*StructField*/,
4909 Extended /*EncodeBlockParameters*/,
4910 Extended /*EncodeClassNames*/);
4911}
4912
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004913/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004914/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004915bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004916 std::string& S,
4917 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004918 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004919 // Encode return type.
4920 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4921 Decl->getResultType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004922 // Compute size of all parameters.
4923 // Start with computing size of a pointer in number of bytes.
4924 // FIXME: There might(should) be a better way of doing this computation!
4925 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004926 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004927 // The first two arguments (self and _cmd) are pointers; account for
4928 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004929 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004930 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004931 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004932 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004933 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004934 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004935 continue;
4936
Ken Dyck40775002010-01-11 17:06:35 +00004937 assert (sz.isPositive() &&
4938 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004939 ParmOffset += sz;
4940 }
Ken Dyck40775002010-01-11 17:06:35 +00004941 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004942 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004943 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004944
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004945 // Argument types.
4946 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004947 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004948 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004949 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004950 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004951 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004952 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4953 // Use array's original type only if it has known number of
4954 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004955 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004956 PType = PVDecl->getType();
4957 } else if (PType->isFunctionType())
4958 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004959 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4960 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00004961 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004962 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004963 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004964
4965 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004966}
4967
Daniel Dunbar4932b362008-08-28 04:38:10 +00004968/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004969/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004970/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4971/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004972/// Property attributes are stored as a comma-delimited C string. The simple
4973/// attributes readonly and bycopy are encoded as single characters. The
4974/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4975/// encoded as single characters, followed by an identifier. Property types
4976/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004977/// these attributes are defined by the following enumeration:
4978/// @code
4979/// enum PropertyAttributes {
4980/// kPropertyReadOnly = 'R', // property is read-only.
4981/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4982/// kPropertyByref = '&', // property is a reference to the value last assigned
4983/// kPropertyDynamic = 'D', // property is dynamic
4984/// kPropertyGetter = 'G', // followed by getter selector name
4985/// kPropertySetter = 'S', // followed by setter selector name
4986/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00004987/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004988/// kPropertyWeak = 'W' // 'weak' property
4989/// kPropertyStrong = 'P' // property GC'able
4990/// kPropertyNonAtomic = 'N' // property non-atomic
4991/// };
4992/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00004993void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00004994 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00004995 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004996 // Collect information from the property implementation decl(s).
4997 bool Dynamic = false;
4998 ObjCPropertyImplDecl *SynthesizePID = 0;
4999
5000 // FIXME: Duplicated code due to poor abstraction.
5001 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00005002 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00005003 dyn_cast<ObjCCategoryImplDecl>(Container)) {
5004 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005005 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00005006 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00005007 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005008 if (PID->getPropertyDecl() == PD) {
5009 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
5010 Dynamic = true;
5011 } else {
5012 SynthesizePID = PID;
5013 }
5014 }
5015 }
5016 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00005017 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00005018 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005019 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00005020 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00005021 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005022 if (PID->getPropertyDecl() == PD) {
5023 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
5024 Dynamic = true;
5025 } else {
5026 SynthesizePID = PID;
5027 }
5028 }
Mike Stump11289f42009-09-09 15:08:12 +00005029 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00005030 }
5031 }
5032
5033 // FIXME: This is not very efficient.
5034 S = "T";
5035
5036 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005037 // GCC has some special rules regarding encoding of properties which
5038 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00005039 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005040 true /* outermost type */,
5041 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00005042
5043 if (PD->isReadOnly()) {
5044 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00005045 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5046 S += ",C";
5047 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5048 S += ",&";
Daniel Dunbar4932b362008-08-28 04:38:10 +00005049 } else {
5050 switch (PD->getSetterKind()) {
5051 case ObjCPropertyDecl::Assign: break;
5052 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00005053 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00005054 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005055 }
5056 }
5057
5058 // It really isn't clear at all what this means, since properties
5059 // are "dynamic by default".
5060 if (Dynamic)
5061 S += ",D";
5062
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005063 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5064 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00005065
Daniel Dunbar4932b362008-08-28 04:38:10 +00005066 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5067 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00005068 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005069 }
5070
5071 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5072 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00005073 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005074 }
5075
5076 if (SynthesizePID) {
5077 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5078 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00005079 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005080 }
5081
5082 // FIXME: OBJCGC: weak & strong
5083}
5084
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005085/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00005086/// Another legacy compatibility encoding: 32-bit longs are encoded as
5087/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005088/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5089///
5090void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00005091 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00005092 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00005093 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005094 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00005095 else
Jay Foad39c79802011-01-12 09:06:06 +00005096 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005097 PointeeTy = IntTy;
5098 }
5099 }
5100}
5101
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005102void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00005103 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005104 // We follow the behavior of gcc, expanding structures which are
5105 // directly pointed to, and expanding embedded structures. Note that
5106 // these rules are sufficient to prevent recursive encoding of the
5107 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00005108 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00005109 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005110}
5111
John McCall393a78d2012-12-20 02:45:14 +00005112static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5113 BuiltinType::Kind kind) {
5114 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005115 case BuiltinType::Void: return 'v';
5116 case BuiltinType::Bool: return 'B';
5117 case BuiltinType::Char_U:
5118 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00005119 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00005120 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00005121 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00005122 case BuiltinType::UInt: return 'I';
5123 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00005124 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005125 case BuiltinType::UInt128: return 'T';
5126 case BuiltinType::ULongLong: return 'Q';
5127 case BuiltinType::Char_S:
5128 case BuiltinType::SChar: return 'c';
5129 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00005130 case BuiltinType::WChar_S:
5131 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00005132 case BuiltinType::Int: return 'i';
5133 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00005134 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005135 case BuiltinType::LongLong: return 'q';
5136 case BuiltinType::Int128: return 't';
5137 case BuiltinType::Float: return 'f';
5138 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00005139 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00005140 case BuiltinType::NullPtr: return '*'; // like char*
5141
5142 case BuiltinType::Half:
5143 // FIXME: potentially need @encodes for these!
5144 return ' ';
5145
5146 case BuiltinType::ObjCId:
5147 case BuiltinType::ObjCClass:
5148 case BuiltinType::ObjCSel:
5149 llvm_unreachable("@encoding ObjC primitive type");
5150
5151 // OpenCL and placeholder types don't need @encodings.
5152 case BuiltinType::OCLImage1d:
5153 case BuiltinType::OCLImage1dArray:
5154 case BuiltinType::OCLImage1dBuffer:
5155 case BuiltinType::OCLImage2d:
5156 case BuiltinType::OCLImage2dArray:
5157 case BuiltinType::OCLImage3d:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005158 case BuiltinType::OCLEvent:
Guy Benyei61054192013-02-07 10:55:47 +00005159 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00005160 case BuiltinType::Dependent:
5161#define BUILTIN_TYPE(KIND, ID)
5162#define PLACEHOLDER_TYPE(KIND, ID) \
5163 case BuiltinType::KIND:
5164#include "clang/AST/BuiltinTypes.def"
5165 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00005166 }
David Blaikie5a6a0202013-01-09 17:48:41 +00005167 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00005168}
5169
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005170static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5171 EnumDecl *Enum = ET->getDecl();
5172
5173 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5174 if (!Enum->isFixed())
5175 return 'i';
5176
5177 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00005178 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5179 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005180}
5181
Jay Foad39c79802011-01-12 09:06:06 +00005182static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00005183 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00005184 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005185 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00005186 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5187 // The GNU runtime requires more information; bitfields are encoded as b,
5188 // then the offset (in bits) of the first element, then the type of the
5189 // bitfield, then the size in bits. For example, in this structure:
5190 //
5191 // struct
5192 // {
5193 // int integer;
5194 // int flags:2;
5195 // };
5196 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5197 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5198 // information is not especially sensible, but we're stuck with it for
5199 // compatibility with GCC, although providing it breaks anything that
5200 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00005201 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005202 const RecordDecl *RD = FD->getParent();
5203 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00005204 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005205 if (const EnumType *ET = T->getAs<EnumType>())
5206 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00005207 else {
5208 const BuiltinType *BT = T->castAs<BuiltinType>();
5209 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5210 }
David Chisnallb190a2c2010-06-04 01:10:52 +00005211 }
Richard Smithcaf33902011-10-10 18:28:20 +00005212 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005213}
5214
Daniel Dunbar07d07852009-10-18 21:17:35 +00005215// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005216void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5217 bool ExpandPointedToStructures,
5218 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00005219 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005220 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005221 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005222 bool StructField,
5223 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005224 bool EncodeClassNames,
5225 bool EncodePointerToObjCTypedef) const {
John McCall393a78d2012-12-20 02:45:14 +00005226 CanQualType CT = getCanonicalType(T);
5227 switch (CT->getTypeClass()) {
5228 case Type::Builtin:
5229 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00005230 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00005231 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00005232 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5233 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5234 else
5235 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00005236 return;
Mike Stump11289f42009-09-09 15:08:12 +00005237
John McCall393a78d2012-12-20 02:45:14 +00005238 case Type::Complex: {
5239 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00005240 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00005241 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00005242 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005243 return;
5244 }
John McCall393a78d2012-12-20 02:45:14 +00005245
5246 case Type::Atomic: {
5247 const AtomicType *AT = T->castAs<AtomicType>();
5248 S += 'A';
5249 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, 0,
5250 false, false);
5251 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00005252 }
John McCall393a78d2012-12-20 02:45:14 +00005253
5254 // encoding for pointer or reference types.
5255 case Type::Pointer:
5256 case Type::LValueReference:
5257 case Type::RValueReference: {
5258 QualType PointeeTy;
5259 if (isa<PointerType>(CT)) {
5260 const PointerType *PT = T->castAs<PointerType>();
5261 if (PT->isObjCSelType()) {
5262 S += ':';
5263 return;
5264 }
5265 PointeeTy = PT->getPointeeType();
5266 } else {
5267 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5268 }
5269
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005270 bool isReadOnly = false;
5271 // For historical/compatibility reasons, the read-only qualifier of the
5272 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5273 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00005274 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00005275 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005276 if (OutermostType && T.isConstQualified()) {
5277 isReadOnly = true;
5278 S += 'r';
5279 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00005280 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005281 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005282 while (P->getAs<PointerType>())
5283 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005284 if (P.isConstQualified()) {
5285 isReadOnly = true;
5286 S += 'r';
5287 }
5288 }
5289 if (isReadOnly) {
5290 // Another legacy compatibility encoding. Some ObjC qualifier and type
5291 // combinations need to be rearranged.
5292 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005293 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00005294 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005295 }
Mike Stump11289f42009-09-09 15:08:12 +00005296
Anders Carlssond8499822007-10-29 05:01:08 +00005297 if (PointeeTy->isCharType()) {
5298 // char pointer types should be encoded as '*' unless it is a
5299 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00005300 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00005301 S += '*';
5302 return;
5303 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005304 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00005305 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5306 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5307 S += '#';
5308 return;
5309 }
5310 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5311 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5312 S += '@';
5313 return;
5314 }
5315 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00005316 }
Anders Carlssond8499822007-10-29 05:01:08 +00005317 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005318 getLegacyIntegralTypeEncoding(PointeeTy);
5319
Mike Stump11289f42009-09-09 15:08:12 +00005320 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005321 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005322 return;
5323 }
John McCall393a78d2012-12-20 02:45:14 +00005324
5325 case Type::ConstantArray:
5326 case Type::IncompleteArray:
5327 case Type::VariableArray: {
5328 const ArrayType *AT = cast<ArrayType>(CT);
5329
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005330 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005331 // Incomplete arrays are encoded as a pointer to the array element.
5332 S += '^';
5333
Mike Stump11289f42009-09-09 15:08:12 +00005334 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005335 false, ExpandStructures, FD);
5336 } else {
5337 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00005338
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00005339 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5340 S += llvm::utostr(CAT->getSize().getZExtValue());
5341 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005342 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005343 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5344 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00005345 S += '0';
5346 }
Mike Stump11289f42009-09-09 15:08:12 +00005347
5348 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005349 false, ExpandStructures, FD);
5350 S += ']';
5351 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005352 return;
5353 }
Mike Stump11289f42009-09-09 15:08:12 +00005354
John McCall393a78d2012-12-20 02:45:14 +00005355 case Type::FunctionNoProto:
5356 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00005357 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005358 return;
Mike Stump11289f42009-09-09 15:08:12 +00005359
John McCall393a78d2012-12-20 02:45:14 +00005360 case Type::Record: {
5361 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005362 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00005363 // Anonymous structures print as '?'
5364 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5365 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005366 if (ClassTemplateSpecializationDecl *Spec
5367 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5368 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00005369 llvm::raw_string_ostream OS(S);
5370 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005371 TemplateArgs.data(),
5372 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00005373 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005374 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00005375 } else {
5376 S += '?';
5377 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00005378 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005379 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005380 if (!RDecl->isUnion()) {
5381 getObjCEncodingForStructureImpl(RDecl, S, FD);
5382 } else {
5383 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5384 FieldEnd = RDecl->field_end();
5385 Field != FieldEnd; ++Field) {
5386 if (FD) {
5387 S += '"';
5388 S += Field->getNameAsString();
5389 S += '"';
5390 }
Mike Stump11289f42009-09-09 15:08:12 +00005391
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005392 // Special case bit-fields.
5393 if (Field->isBitField()) {
5394 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie40ed2972012-06-06 20:45:41 +00005395 *Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005396 } else {
5397 QualType qt = Field->getType();
5398 getLegacyIntegralTypeEncoding(qt);
5399 getObjCEncodingForTypeImpl(qt, S, false, true,
5400 FD, /*OutermostType*/false,
5401 /*EncodingProperty*/false,
5402 /*StructField*/true);
5403 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005404 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005405 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00005406 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005407 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005408 return;
5409 }
Mike Stump11289f42009-09-09 15:08:12 +00005410
John McCall393a78d2012-12-20 02:45:14 +00005411 case Type::BlockPointer: {
5412 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00005413 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005414 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00005415 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005416
5417 S += '<';
5418 // Block return type
5419 getObjCEncodingForTypeImpl(FT->getResultType(), S,
5420 ExpandPointedToStructures, ExpandStructures,
5421 FD,
5422 false /* OutermostType */,
5423 EncodingProperty,
5424 false /* StructField */,
5425 EncodeBlockParameters,
5426 EncodeClassNames);
5427 // Block self
5428 S += "@?";
5429 // Block parameters
5430 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
5431 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
5432 E = FPT->arg_type_end(); I && (I != E); ++I) {
5433 getObjCEncodingForTypeImpl(*I, S,
5434 ExpandPointedToStructures,
5435 ExpandStructures,
5436 FD,
5437 false /* OutermostType */,
5438 EncodingProperty,
5439 false /* StructField */,
5440 EncodeBlockParameters,
5441 EncodeClassNames);
5442 }
5443 }
5444 S += '>';
5445 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005446 return;
5447 }
Mike Stump11289f42009-09-09 15:08:12 +00005448
John McCall393a78d2012-12-20 02:45:14 +00005449 case Type::ObjCObject:
5450 case Type::ObjCInterface: {
5451 // Ignore protocol qualifiers when mangling at this level.
5452 T = T->castAs<ObjCObjectType>()->getBaseType();
John McCall8b07ec22010-05-15 11:32:37 +00005453
John McCall393a78d2012-12-20 02:45:14 +00005454 // The assumption seems to be that this assert will succeed
5455 // because nested levels will have filtered out 'id' and 'Class'.
5456 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005457 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00005458 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005459 S += '{';
5460 const IdentifierInfo *II = OI->getIdentifier();
5461 S += II->getName();
5462 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005463 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005464 DeepCollectObjCIvars(OI, true, Ivars);
5465 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005466 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005467 if (Field->isBitField())
5468 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005469 else
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005470 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5471 false, false, false, false, false,
5472 EncodePointerToObjCTypedef);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005473 }
5474 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005475 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005476 }
Mike Stump11289f42009-09-09 15:08:12 +00005477
John McCall393a78d2012-12-20 02:45:14 +00005478 case Type::ObjCObjectPointer: {
5479 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005480 if (OPT->isObjCIdType()) {
5481 S += '@';
5482 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005483 }
Mike Stump11289f42009-09-09 15:08:12 +00005484
Steve Narofff0c86112009-10-28 22:03:49 +00005485 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5486 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5487 // Since this is a binary compatibility issue, need to consult with runtime
5488 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005489 S += '#';
5490 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005491 }
Mike Stump11289f42009-09-09 15:08:12 +00005492
Chris Lattnere7cabb92009-07-13 00:10:46 +00005493 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005494 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005495 ExpandPointedToStructures,
5496 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005497 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005498 // Note that we do extended encoding of protocol qualifer list
5499 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005500 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00005501 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5502 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005503 S += '<';
5504 S += (*I)->getNameAsString();
5505 S += '>';
5506 }
5507 S += '"';
5508 }
5509 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005510 }
Mike Stump11289f42009-09-09 15:08:12 +00005511
Chris Lattnere7cabb92009-07-13 00:10:46 +00005512 QualType PointeeTy = OPT->getPointeeType();
5513 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005514 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5515 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005516 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005517 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005518 // {...};
5519 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005520 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00005521 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005522 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5523 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5524 DeepCollectObjCIvars(OI, true, Ivars);
5525 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5526 if (cast<FieldDecl>(Ivars[i]) == FD) {
5527 S += '{';
5528 S += OI->getIdentifier()->getName();
5529 S += '}';
5530 return;
5531 }
5532 }
5533 }
Mike Stump11289f42009-09-09 15:08:12 +00005534 getObjCEncodingForTypeImpl(PointeeTy, S,
5535 false, ExpandPointedToStructures,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005536 NULL,
5537 false, false, false, false, false,
5538 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005539 return;
5540 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005541
5542 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005543 if (OPT->getInterfaceDecl() &&
5544 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005545 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00005546 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00005547 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5548 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005549 S += '<';
5550 S += (*I)->getNameAsString();
5551 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005552 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005553 S += '"';
5554 }
5555 return;
5556 }
Mike Stump11289f42009-09-09 15:08:12 +00005557
John McCalla9e6e8d2010-05-17 23:56:34 +00005558 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00005559 // FIXME: we shoul do better than that. 'M' is available.
5560 case Type::MemberPointer:
John McCalla9e6e8d2010-05-17 23:56:34 +00005561 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005562
John McCall393a78d2012-12-20 02:45:14 +00005563 case Type::Vector:
5564 case Type::ExtVector:
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005565 // This matches gcc's encoding, even though technically it is
5566 // insufficient.
5567 // FIXME. We should do a better job than gcc.
5568 return;
John McCall393a78d2012-12-20 02:45:14 +00005569
Richard Smith27d807c2013-04-30 13:56:41 +00005570 case Type::Auto:
5571 // We could see an undeduced auto type here during error recovery.
5572 // Just ignore it.
5573 return;
5574
John McCall393a78d2012-12-20 02:45:14 +00005575#define ABSTRACT_TYPE(KIND, BASE)
5576#define TYPE(KIND, BASE)
5577#define DEPENDENT_TYPE(KIND, BASE) \
5578 case Type::KIND:
5579#define NON_CANONICAL_TYPE(KIND, BASE) \
5580 case Type::KIND:
5581#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5582 case Type::KIND:
5583#include "clang/AST/TypeNodes.def"
5584 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005585 }
John McCall393a78d2012-12-20 02:45:14 +00005586 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00005587}
5588
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005589void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5590 std::string &S,
5591 const FieldDecl *FD,
5592 bool includeVBases) const {
5593 assert(RDecl && "Expected non-null RecordDecl");
5594 assert(!RDecl->isUnion() && "Should not be called for unions");
5595 if (!RDecl->getDefinition())
5596 return;
5597
5598 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5599 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5600 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5601
5602 if (CXXRec) {
5603 for (CXXRecordDecl::base_class_iterator
5604 BI = CXXRec->bases_begin(),
5605 BE = CXXRec->bases_end(); BI != BE; ++BI) {
5606 if (!BI->isVirtual()) {
5607 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005608 if (base->isEmpty())
5609 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005610 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005611 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5612 std::make_pair(offs, base));
5613 }
5614 }
5615 }
5616
5617 unsigned i = 0;
5618 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5619 FieldEnd = RDecl->field_end();
5620 Field != FieldEnd; ++Field, ++i) {
5621 uint64_t offs = layout.getFieldOffset(i);
5622 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie40ed2972012-06-06 20:45:41 +00005623 std::make_pair(offs, *Field));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005624 }
5625
5626 if (CXXRec && includeVBases) {
5627 for (CXXRecordDecl::base_class_iterator
5628 BI = CXXRec->vbases_begin(),
5629 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
5630 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005631 if (base->isEmpty())
5632 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005633 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00005634 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
5635 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00005636 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5637 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005638 }
5639 }
5640
5641 CharUnits size;
5642 if (CXXRec) {
5643 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5644 } else {
5645 size = layout.getSize();
5646 }
5647
5648 uint64_t CurOffs = 0;
5649 std::multimap<uint64_t, NamedDecl *>::iterator
5650 CurLayObj = FieldOrBaseOffsets.begin();
5651
Douglas Gregorf5d6c742012-04-27 22:30:01 +00005652 if (CXXRec && CXXRec->isDynamicClass() &&
5653 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005654 if (FD) {
5655 S += "\"_vptr$";
5656 std::string recname = CXXRec->getNameAsString();
5657 if (recname.empty()) recname = "?";
5658 S += recname;
5659 S += '"';
5660 }
5661 S += "^^?";
5662 CurOffs += getTypeSize(VoidPtrTy);
5663 }
5664
5665 if (!RDecl->hasFlexibleArrayMember()) {
5666 // Mark the end of the structure.
5667 uint64_t offs = toBits(size);
5668 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5669 std::make_pair(offs, (NamedDecl*)0));
5670 }
5671
5672 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5673 assert(CurOffs <= CurLayObj->first);
5674
5675 if (CurOffs < CurLayObj->first) {
5676 uint64_t padding = CurLayObj->first - CurOffs;
5677 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5678 // packing/alignment of members is different that normal, in which case
5679 // the encoding will be out-of-sync with the real layout.
5680 // If the runtime switches to just consider the size of types without
5681 // taking into account alignment, we could make padding explicit in the
5682 // encoding (e.g. using arrays of chars). The encoding strings would be
5683 // longer then though.
5684 CurOffs += padding;
5685 }
5686
5687 NamedDecl *dcl = CurLayObj->second;
5688 if (dcl == 0)
5689 break; // reached end of structure.
5690
5691 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5692 // We expand the bases without their virtual bases since those are going
5693 // in the initial structure. Note that this differs from gcc which
5694 // expands virtual bases each time one is encountered in the hierarchy,
5695 // making the encoding type bigger than it really is.
5696 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005697 assert(!base->isEmpty());
5698 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005699 } else {
5700 FieldDecl *field = cast<FieldDecl>(dcl);
5701 if (FD) {
5702 S += '"';
5703 S += field->getNameAsString();
5704 S += '"';
5705 }
5706
5707 if (field->isBitField()) {
5708 EncodeBitField(this, S, field->getType(), field);
Richard Smithcaf33902011-10-10 18:28:20 +00005709 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005710 } else {
5711 QualType qt = field->getType();
5712 getLegacyIntegralTypeEncoding(qt);
5713 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5714 /*OutermostType*/false,
5715 /*EncodingProperty*/false,
5716 /*StructField*/true);
5717 CurOffs += getTypeSize(field->getType());
5718 }
5719 }
5720 }
5721}
5722
Mike Stump11289f42009-09-09 15:08:12 +00005723void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005724 std::string& S) const {
5725 if (QT & Decl::OBJC_TQ_In)
5726 S += 'n';
5727 if (QT & Decl::OBJC_TQ_Inout)
5728 S += 'N';
5729 if (QT & Decl::OBJC_TQ_Out)
5730 S += 'o';
5731 if (QT & Decl::OBJC_TQ_Bycopy)
5732 S += 'O';
5733 if (QT & Decl::OBJC_TQ_Byref)
5734 S += 'R';
5735 if (QT & Decl::OBJC_TQ_Oneway)
5736 S += 'V';
5737}
5738
Douglas Gregor3ea72692011-08-12 05:46:01 +00005739TypedefDecl *ASTContext::getObjCIdDecl() const {
5740 if (!ObjCIdDecl) {
5741 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5742 T = getObjCObjectPointerType(T);
5743 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
5744 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5745 getTranslationUnitDecl(),
5746 SourceLocation(), SourceLocation(),
5747 &Idents.get("id"), IdInfo);
5748 }
5749
5750 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00005751}
5752
Douglas Gregor52e02802011-08-12 06:17:30 +00005753TypedefDecl *ASTContext::getObjCSelDecl() const {
5754 if (!ObjCSelDecl) {
5755 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5756 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5757 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5758 getTranslationUnitDecl(),
5759 SourceLocation(), SourceLocation(),
5760 &Idents.get("SEL"), SelInfo);
5761 }
5762 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00005763}
5764
Douglas Gregor0a586182011-08-12 05:59:41 +00005765TypedefDecl *ASTContext::getObjCClassDecl() const {
5766 if (!ObjCClassDecl) {
5767 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5768 T = getObjCObjectPointerType(T);
5769 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5770 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5771 getTranslationUnitDecl(),
5772 SourceLocation(), SourceLocation(),
5773 &Idents.get("Class"), ClassInfo);
5774 }
5775
5776 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00005777}
5778
Douglas Gregord53ae832012-01-17 18:09:05 +00005779ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5780 if (!ObjCProtocolClassDecl) {
5781 ObjCProtocolClassDecl
5782 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5783 SourceLocation(),
5784 &Idents.get("Protocol"),
5785 /*PrevDecl=*/0,
5786 SourceLocation(), true);
5787 }
5788
5789 return ObjCProtocolClassDecl;
5790}
5791
Meador Inge5d3fb222012-06-16 03:34:49 +00005792//===----------------------------------------------------------------------===//
5793// __builtin_va_list Construction Functions
5794//===----------------------------------------------------------------------===//
5795
5796static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5797 // typedef char* __builtin_va_list;
5798 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5799 TypeSourceInfo *TInfo
5800 = Context->getTrivialTypeSourceInfo(CharPtrType);
5801
5802 TypedefDecl *VaListTypeDecl
5803 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5804 Context->getTranslationUnitDecl(),
5805 SourceLocation(), SourceLocation(),
5806 &Context->Idents.get("__builtin_va_list"),
5807 TInfo);
5808 return VaListTypeDecl;
5809}
5810
5811static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5812 // typedef void* __builtin_va_list;
5813 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5814 TypeSourceInfo *TInfo
5815 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5816
5817 TypedefDecl *VaListTypeDecl
5818 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5819 Context->getTranslationUnitDecl(),
5820 SourceLocation(), SourceLocation(),
5821 &Context->Idents.get("__builtin_va_list"),
5822 TInfo);
5823 return VaListTypeDecl;
5824}
5825
Tim Northover9bb857a2013-01-31 12:13:10 +00005826static TypedefDecl *
5827CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
5828 RecordDecl *VaListTagDecl;
5829 if (Context->getLangOpts().CPlusPlus) {
5830 // namespace std { struct __va_list {
5831 NamespaceDecl *NS;
5832 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5833 Context->getTranslationUnitDecl(),
5834 /*Inline*/false, SourceLocation(),
5835 SourceLocation(), &Context->Idents.get("std"),
5836 /*PrevDecl*/0);
5837
5838 VaListTagDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5839 Context->getTranslationUnitDecl(),
5840 SourceLocation(), SourceLocation(),
5841 &Context->Idents.get("__va_list"));
5842 VaListTagDecl->setDeclContext(NS);
5843 } else {
5844 // struct __va_list
5845 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5846 Context->getTranslationUnitDecl(),
5847 &Context->Idents.get("__va_list"));
5848 }
5849
5850 VaListTagDecl->startDefinition();
5851
5852 const size_t NumFields = 5;
5853 QualType FieldTypes[NumFields];
5854 const char *FieldNames[NumFields];
5855
5856 // void *__stack;
5857 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
5858 FieldNames[0] = "__stack";
5859
5860 // void *__gr_top;
5861 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
5862 FieldNames[1] = "__gr_top";
5863
5864 // void *__vr_top;
5865 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5866 FieldNames[2] = "__vr_top";
5867
5868 // int __gr_offs;
5869 FieldTypes[3] = Context->IntTy;
5870 FieldNames[3] = "__gr_offs";
5871
5872 // int __vr_offs;
5873 FieldTypes[4] = Context->IntTy;
5874 FieldNames[4] = "__vr_offs";
5875
5876 // Create fields
5877 for (unsigned i = 0; i < NumFields; ++i) {
5878 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5879 VaListTagDecl,
5880 SourceLocation(),
5881 SourceLocation(),
5882 &Context->Idents.get(FieldNames[i]),
5883 FieldTypes[i], /*TInfo=*/0,
5884 /*BitWidth=*/0,
5885 /*Mutable=*/false,
5886 ICIS_NoInit);
5887 Field->setAccess(AS_public);
5888 VaListTagDecl->addDecl(Field);
5889 }
5890 VaListTagDecl->completeDefinition();
5891 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5892 Context->VaListTagTy = VaListTagType;
5893
5894 // } __builtin_va_list;
5895 TypedefDecl *VaListTypedefDecl
5896 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5897 Context->getTranslationUnitDecl(),
5898 SourceLocation(), SourceLocation(),
5899 &Context->Idents.get("__builtin_va_list"),
5900 Context->getTrivialTypeSourceInfo(VaListTagType));
5901
5902 return VaListTypedefDecl;
5903}
5904
Meador Inge5d3fb222012-06-16 03:34:49 +00005905static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5906 // typedef struct __va_list_tag {
5907 RecordDecl *VaListTagDecl;
5908
5909 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5910 Context->getTranslationUnitDecl(),
5911 &Context->Idents.get("__va_list_tag"));
5912 VaListTagDecl->startDefinition();
5913
5914 const size_t NumFields = 5;
5915 QualType FieldTypes[NumFields];
5916 const char *FieldNames[NumFields];
5917
5918 // unsigned char gpr;
5919 FieldTypes[0] = Context->UnsignedCharTy;
5920 FieldNames[0] = "gpr";
5921
5922 // unsigned char fpr;
5923 FieldTypes[1] = Context->UnsignedCharTy;
5924 FieldNames[1] = "fpr";
5925
5926 // unsigned short reserved;
5927 FieldTypes[2] = Context->UnsignedShortTy;
5928 FieldNames[2] = "reserved";
5929
5930 // void* overflow_arg_area;
5931 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5932 FieldNames[3] = "overflow_arg_area";
5933
5934 // void* reg_save_area;
5935 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5936 FieldNames[4] = "reg_save_area";
5937
5938 // Create fields
5939 for (unsigned i = 0; i < NumFields; ++i) {
5940 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5941 SourceLocation(),
5942 SourceLocation(),
5943 &Context->Idents.get(FieldNames[i]),
5944 FieldTypes[i], /*TInfo=*/0,
5945 /*BitWidth=*/0,
5946 /*Mutable=*/false,
5947 ICIS_NoInit);
5948 Field->setAccess(AS_public);
5949 VaListTagDecl->addDecl(Field);
5950 }
5951 VaListTagDecl->completeDefinition();
5952 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005953 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005954
5955 // } __va_list_tag;
5956 TypedefDecl *VaListTagTypedefDecl
5957 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5958 Context->getTranslationUnitDecl(),
5959 SourceLocation(), SourceLocation(),
5960 &Context->Idents.get("__va_list_tag"),
5961 Context->getTrivialTypeSourceInfo(VaListTagType));
5962 QualType VaListTagTypedefType =
5963 Context->getTypedefType(VaListTagTypedefDecl);
5964
5965 // typedef __va_list_tag __builtin_va_list[1];
5966 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5967 QualType VaListTagArrayType
5968 = Context->getConstantArrayType(VaListTagTypedefType,
5969 Size, ArrayType::Normal, 0);
5970 TypeSourceInfo *TInfo
5971 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5972 TypedefDecl *VaListTypedefDecl
5973 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5974 Context->getTranslationUnitDecl(),
5975 SourceLocation(), SourceLocation(),
5976 &Context->Idents.get("__builtin_va_list"),
5977 TInfo);
5978
5979 return VaListTypedefDecl;
5980}
5981
5982static TypedefDecl *
5983CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5984 // typedef struct __va_list_tag {
5985 RecordDecl *VaListTagDecl;
5986 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5987 Context->getTranslationUnitDecl(),
5988 &Context->Idents.get("__va_list_tag"));
5989 VaListTagDecl->startDefinition();
5990
5991 const size_t NumFields = 4;
5992 QualType FieldTypes[NumFields];
5993 const char *FieldNames[NumFields];
5994
5995 // unsigned gp_offset;
5996 FieldTypes[0] = Context->UnsignedIntTy;
5997 FieldNames[0] = "gp_offset";
5998
5999 // unsigned fp_offset;
6000 FieldTypes[1] = Context->UnsignedIntTy;
6001 FieldNames[1] = "fp_offset";
6002
6003 // void* overflow_arg_area;
6004 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6005 FieldNames[2] = "overflow_arg_area";
6006
6007 // void* reg_save_area;
6008 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6009 FieldNames[3] = "reg_save_area";
6010
6011 // Create fields
6012 for (unsigned i = 0; i < NumFields; ++i) {
6013 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6014 VaListTagDecl,
6015 SourceLocation(),
6016 SourceLocation(),
6017 &Context->Idents.get(FieldNames[i]),
6018 FieldTypes[i], /*TInfo=*/0,
6019 /*BitWidth=*/0,
6020 /*Mutable=*/false,
6021 ICIS_NoInit);
6022 Field->setAccess(AS_public);
6023 VaListTagDecl->addDecl(Field);
6024 }
6025 VaListTagDecl->completeDefinition();
6026 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00006027 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00006028
6029 // } __va_list_tag;
6030 TypedefDecl *VaListTagTypedefDecl
6031 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6032 Context->getTranslationUnitDecl(),
6033 SourceLocation(), SourceLocation(),
6034 &Context->Idents.get("__va_list_tag"),
6035 Context->getTrivialTypeSourceInfo(VaListTagType));
6036 QualType VaListTagTypedefType =
6037 Context->getTypedefType(VaListTagTypedefDecl);
6038
6039 // typedef __va_list_tag __builtin_va_list[1];
6040 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6041 QualType VaListTagArrayType
6042 = Context->getConstantArrayType(VaListTagTypedefType,
6043 Size, ArrayType::Normal,0);
6044 TypeSourceInfo *TInfo
6045 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
6046 TypedefDecl *VaListTypedefDecl
6047 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6048 Context->getTranslationUnitDecl(),
6049 SourceLocation(), SourceLocation(),
6050 &Context->Idents.get("__builtin_va_list"),
6051 TInfo);
6052
6053 return VaListTypedefDecl;
6054}
6055
6056static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
6057 // typedef int __builtin_va_list[4];
6058 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
6059 QualType IntArrayType
6060 = Context->getConstantArrayType(Context->IntTy,
6061 Size, ArrayType::Normal, 0);
6062 TypedefDecl *VaListTypedefDecl
6063 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6064 Context->getTranslationUnitDecl(),
6065 SourceLocation(), SourceLocation(),
6066 &Context->Idents.get("__builtin_va_list"),
6067 Context->getTrivialTypeSourceInfo(IntArrayType));
6068
6069 return VaListTypedefDecl;
6070}
6071
Logan Chien57086ce2012-10-10 06:56:20 +00006072static TypedefDecl *
6073CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
6074 RecordDecl *VaListDecl;
6075 if (Context->getLangOpts().CPlusPlus) {
6076 // namespace std { struct __va_list {
6077 NamespaceDecl *NS;
6078 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6079 Context->getTranslationUnitDecl(),
6080 /*Inline*/false, SourceLocation(),
6081 SourceLocation(), &Context->Idents.get("std"),
6082 /*PrevDecl*/0);
6083
6084 VaListDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
6085 Context->getTranslationUnitDecl(),
6086 SourceLocation(), SourceLocation(),
6087 &Context->Idents.get("__va_list"));
6088
6089 VaListDecl->setDeclContext(NS);
6090
6091 } else {
6092 // struct __va_list {
6093 VaListDecl = CreateRecordDecl(*Context, TTK_Struct,
6094 Context->getTranslationUnitDecl(),
6095 &Context->Idents.get("__va_list"));
6096 }
6097
6098 VaListDecl->startDefinition();
6099
6100 // void * __ap;
6101 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6102 VaListDecl,
6103 SourceLocation(),
6104 SourceLocation(),
6105 &Context->Idents.get("__ap"),
6106 Context->getPointerType(Context->VoidTy),
6107 /*TInfo=*/0,
6108 /*BitWidth=*/0,
6109 /*Mutable=*/false,
6110 ICIS_NoInit);
6111 Field->setAccess(AS_public);
6112 VaListDecl->addDecl(Field);
6113
6114 // };
6115 VaListDecl->completeDefinition();
6116
6117 // typedef struct __va_list __builtin_va_list;
6118 TypeSourceInfo *TInfo
6119 = Context->getTrivialTypeSourceInfo(Context->getRecordType(VaListDecl));
6120
6121 TypedefDecl *VaListTypeDecl
6122 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6123 Context->getTranslationUnitDecl(),
6124 SourceLocation(), SourceLocation(),
6125 &Context->Idents.get("__builtin_va_list"),
6126 TInfo);
6127
6128 return VaListTypeDecl;
6129}
6130
Ulrich Weigand47445072013-05-06 16:26:41 +00006131static TypedefDecl *
6132CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
6133 // typedef struct __va_list_tag {
6134 RecordDecl *VaListTagDecl;
6135 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
6136 Context->getTranslationUnitDecl(),
6137 &Context->Idents.get("__va_list_tag"));
6138 VaListTagDecl->startDefinition();
6139
6140 const size_t NumFields = 4;
6141 QualType FieldTypes[NumFields];
6142 const char *FieldNames[NumFields];
6143
6144 // long __gpr;
6145 FieldTypes[0] = Context->LongTy;
6146 FieldNames[0] = "__gpr";
6147
6148 // long __fpr;
6149 FieldTypes[1] = Context->LongTy;
6150 FieldNames[1] = "__fpr";
6151
6152 // void *__overflow_arg_area;
6153 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6154 FieldNames[2] = "__overflow_arg_area";
6155
6156 // void *__reg_save_area;
6157 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6158 FieldNames[3] = "__reg_save_area";
6159
6160 // Create fields
6161 for (unsigned i = 0; i < NumFields; ++i) {
6162 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6163 VaListTagDecl,
6164 SourceLocation(),
6165 SourceLocation(),
6166 &Context->Idents.get(FieldNames[i]),
6167 FieldTypes[i], /*TInfo=*/0,
6168 /*BitWidth=*/0,
6169 /*Mutable=*/false,
6170 ICIS_NoInit);
6171 Field->setAccess(AS_public);
6172 VaListTagDecl->addDecl(Field);
6173 }
6174 VaListTagDecl->completeDefinition();
6175 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6176 Context->VaListTagTy = VaListTagType;
6177
6178 // } __va_list_tag;
6179 TypedefDecl *VaListTagTypedefDecl
6180 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6181 Context->getTranslationUnitDecl(),
6182 SourceLocation(), SourceLocation(),
6183 &Context->Idents.get("__va_list_tag"),
6184 Context->getTrivialTypeSourceInfo(VaListTagType));
6185 QualType VaListTagTypedefType =
6186 Context->getTypedefType(VaListTagTypedefDecl);
6187
6188 // typedef __va_list_tag __builtin_va_list[1];
6189 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6190 QualType VaListTagArrayType
6191 = Context->getConstantArrayType(VaListTagTypedefType,
6192 Size, ArrayType::Normal,0);
6193 TypeSourceInfo *TInfo
6194 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
6195 TypedefDecl *VaListTypedefDecl
6196 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
6197 Context->getTranslationUnitDecl(),
6198 SourceLocation(), SourceLocation(),
6199 &Context->Idents.get("__builtin_va_list"),
6200 TInfo);
6201
6202 return VaListTypedefDecl;
6203}
6204
Meador Inge5d3fb222012-06-16 03:34:49 +00006205static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6206 TargetInfo::BuiltinVaListKind Kind) {
6207 switch (Kind) {
6208 case TargetInfo::CharPtrBuiltinVaList:
6209 return CreateCharPtrBuiltinVaListDecl(Context);
6210 case TargetInfo::VoidPtrBuiltinVaList:
6211 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00006212 case TargetInfo::AArch64ABIBuiltinVaList:
6213 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006214 case TargetInfo::PowerABIBuiltinVaList:
6215 return CreatePowerABIBuiltinVaListDecl(Context);
6216 case TargetInfo::X86_64ABIBuiltinVaList:
6217 return CreateX86_64ABIBuiltinVaListDecl(Context);
6218 case TargetInfo::PNaClABIBuiltinVaList:
6219 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00006220 case TargetInfo::AAPCSABIBuiltinVaList:
6221 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00006222 case TargetInfo::SystemZBuiltinVaList:
6223 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006224 }
6225
6226 llvm_unreachable("Unhandled __builtin_va_list type kind");
6227}
6228
6229TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
6230 if (!BuiltinVaListDecl)
6231 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
6232
6233 return BuiltinVaListDecl;
6234}
6235
Meador Ingecfb60902012-07-01 15:57:25 +00006236QualType ASTContext::getVaListTagType() const {
6237 // Force the creation of VaListTagTy by building the __builtin_va_list
6238 // declaration.
6239 if (VaListTagTy.isNull())
6240 (void) getBuiltinVaListDecl();
6241
6242 return VaListTagTy;
6243}
6244
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006245void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00006246 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00006247 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00006248
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006249 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00006250}
6251
John McCalld28ae272009-12-02 08:04:21 +00006252/// \brief Retrieve the template name that corresponds to a non-empty
6253/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00006254TemplateName
6255ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6256 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00006257 unsigned size = End - Begin;
6258 assert(size > 1 && "set is not overloaded!");
6259
6260 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6261 size * sizeof(FunctionTemplateDecl*));
6262 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6263
6264 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00006265 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00006266 NamedDecl *D = *I;
6267 assert(isa<FunctionTemplateDecl>(D) ||
6268 (isa<UsingShadowDecl>(D) &&
6269 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6270 *Storage++ = D;
6271 }
6272
6273 return TemplateName(OT);
6274}
6275
Douglas Gregordc572a32009-03-30 22:58:21 +00006276/// \brief Retrieve the template name that represents a qualified
6277/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00006278TemplateName
6279ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6280 bool TemplateKeyword,
6281 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00006282 assert(NNS && "Missing nested-name-specifier in qualified template name");
6283
Douglas Gregorc42075a2010-02-04 18:10:26 +00006284 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00006285 llvm::FoldingSetNodeID ID;
6286 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6287
6288 void *InsertPos = 0;
6289 QualifiedTemplateName *QTN =
6290 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6291 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00006292 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6293 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00006294 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6295 }
6296
6297 return TemplateName(QTN);
6298}
6299
6300/// \brief Retrieve the template name that represents a dependent
6301/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00006302TemplateName
6303ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6304 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00006305 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00006306 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00006307
6308 llvm::FoldingSetNodeID ID;
6309 DependentTemplateName::Profile(ID, NNS, Name);
6310
6311 void *InsertPos = 0;
6312 DependentTemplateName *QTN =
6313 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6314
6315 if (QTN)
6316 return TemplateName(QTN);
6317
6318 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6319 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006320 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6321 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00006322 } else {
6323 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00006324 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6325 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006326 DependentTemplateName *CheckQTN =
6327 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6328 assert(!CheckQTN && "Dependent type name canonicalization broken");
6329 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00006330 }
6331
6332 DependentTemplateNames.InsertNode(QTN, InsertPos);
6333 return TemplateName(QTN);
6334}
6335
Douglas Gregor71395fa2009-11-04 00:56:37 +00006336/// \brief Retrieve the template name that represents a dependent
6337/// template name such as \c MetaFun::template operator+.
6338TemplateName
6339ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00006340 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00006341 assert((!NNS || NNS->isDependent()) &&
6342 "Nested name specifier must be dependent");
6343
6344 llvm::FoldingSetNodeID ID;
6345 DependentTemplateName::Profile(ID, NNS, Operator);
6346
6347 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00006348 DependentTemplateName *QTN
6349 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006350
6351 if (QTN)
6352 return TemplateName(QTN);
6353
6354 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6355 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006356 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6357 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006358 } else {
6359 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00006360 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6361 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006362
6363 DependentTemplateName *CheckQTN
6364 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6365 assert(!CheckQTN && "Dependent template name canonicalization broken");
6366 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00006367 }
6368
6369 DependentTemplateNames.InsertNode(QTN, InsertPos);
6370 return TemplateName(QTN);
6371}
6372
Douglas Gregor5590be02011-01-15 06:45:20 +00006373TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00006374ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6375 TemplateName replacement) const {
6376 llvm::FoldingSetNodeID ID;
6377 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
6378
6379 void *insertPos = 0;
6380 SubstTemplateTemplateParmStorage *subst
6381 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6382
6383 if (!subst) {
6384 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6385 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6386 }
6387
6388 return TemplateName(subst);
6389}
6390
6391TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00006392ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6393 const TemplateArgument &ArgPack) const {
6394 ASTContext &Self = const_cast<ASTContext &>(*this);
6395 llvm::FoldingSetNodeID ID;
6396 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
6397
6398 void *InsertPos = 0;
6399 SubstTemplateTemplateParmPackStorage *Subst
6400 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6401
6402 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00006403 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00006404 ArgPack.pack_size(),
6405 ArgPack.pack_begin());
6406 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6407 }
6408
6409 return TemplateName(Subst);
6410}
6411
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006412/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00006413/// TargetInfo, produce the corresponding type. The unsigned @p Type
6414/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00006415CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006416 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00006417 case TargetInfo::NoInt: return CanQualType();
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00006418 case TargetInfo::SignedChar: return SignedCharTy;
6419 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006420 case TargetInfo::SignedShort: return ShortTy;
6421 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6422 case TargetInfo::SignedInt: return IntTy;
6423 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6424 case TargetInfo::SignedLong: return LongTy;
6425 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6426 case TargetInfo::SignedLongLong: return LongLongTy;
6427 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6428 }
6429
David Blaikie83d382b2011-09-23 05:06:16 +00006430 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006431}
Ted Kremenek77c51b22008-07-24 23:58:27 +00006432
6433//===----------------------------------------------------------------------===//
6434// Type Predicates.
6435//===----------------------------------------------------------------------===//
6436
Fariborz Jahanian96207692009-02-18 21:49:28 +00006437/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6438/// garbage collection attribute.
6439///
John McCall553d45a2011-01-12 00:34:59 +00006440Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006441 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00006442 return Qualifiers::GCNone;
6443
David Blaikiebbafb8a2012-03-11 07:00:24 +00006444 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00006445 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6446
6447 // Default behaviour under objective-C's gc is for ObjC pointers
6448 // (or pointers to them) be treated as though they were declared
6449 // as __strong.
6450 if (GCAttrs == Qualifiers::GCNone) {
6451 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6452 return Qualifiers::Strong;
6453 else if (Ty->isPointerType())
6454 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6455 } else {
6456 // It's not valid to set GC attributes on anything that isn't a
6457 // pointer.
6458#ifndef NDEBUG
6459 QualType CT = Ty->getCanonicalTypeInternal();
6460 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6461 CT = AT->getElementType();
6462 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6463#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00006464 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00006465 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00006466}
6467
Chris Lattner49af6a42008-04-07 06:51:04 +00006468//===----------------------------------------------------------------------===//
6469// Type Compatibility Testing
6470//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00006471
Mike Stump11289f42009-09-09 15:08:12 +00006472/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006473/// compatible.
6474static bool areCompatVectorTypes(const VectorType *LHS,
6475 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00006476 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00006477 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00006478 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00006479}
6480
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006481bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6482 QualType SecondVec) {
6483 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6484 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6485
6486 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6487 return true;
6488
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006489 // Treat Neon vector types and most AltiVec vector types as if they are the
6490 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006491 const VectorType *First = FirstVec->getAs<VectorType>();
6492 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006493 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006494 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006495 First->getVectorKind() != VectorType::AltiVecPixel &&
6496 First->getVectorKind() != VectorType::AltiVecBool &&
6497 Second->getVectorKind() != VectorType::AltiVecPixel &&
6498 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006499 return true;
6500
6501 return false;
6502}
6503
Steve Naroff8e6aee52009-07-23 01:01:38 +00006504//===----------------------------------------------------------------------===//
6505// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6506//===----------------------------------------------------------------------===//
6507
6508/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6509/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00006510bool
6511ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6512 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00006513 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006514 return true;
6515 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
6516 E = rProto->protocol_end(); PI != E; ++PI)
6517 if (ProtocolCompatibleWithProtocol(lProto, *PI))
6518 return true;
6519 return false;
6520}
6521
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006522/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6523/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006524bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6525 QualType rhs) {
6526 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6527 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6528 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6529
6530 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6531 E = lhsQID->qual_end(); I != E; ++I) {
6532 bool match = false;
6533 ObjCProtocolDecl *lhsProto = *I;
6534 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6535 E = rhsOPT->qual_end(); J != E; ++J) {
6536 ObjCProtocolDecl *rhsProto = *J;
6537 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6538 match = true;
6539 break;
6540 }
6541 }
6542 if (!match)
6543 return false;
6544 }
6545 return true;
6546}
6547
Steve Naroff8e6aee52009-07-23 01:01:38 +00006548/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6549/// ObjCQualifiedIDType.
6550bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6551 bool compare) {
6552 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00006553 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006554 lhs->isObjCIdType() || lhs->isObjCClassType())
6555 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006556 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006557 rhs->isObjCIdType() || rhs->isObjCClassType())
6558 return true;
6559
6560 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00006561 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006562
Steve Naroff8e6aee52009-07-23 01:01:38 +00006563 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00006564
Steve Naroff8e6aee52009-07-23 01:01:38 +00006565 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00006566 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006567 // make sure we check the class hierarchy.
6568 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6569 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6570 E = lhsQID->qual_end(); I != E; ++I) {
6571 // when comparing an id<P> on lhs with a static type on rhs,
6572 // see if static class implements all of id's protocols, directly or
6573 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00006574 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006575 return false;
6576 }
6577 }
6578 // If there are no qualifiers and no interface, we have an 'id'.
6579 return true;
6580 }
Mike Stump11289f42009-09-09 15:08:12 +00006581 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006582 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6583 E = lhsQID->qual_end(); I != E; ++I) {
6584 ObjCProtocolDecl *lhsProto = *I;
6585 bool match = false;
6586
6587 // when comparing an id<P> on lhs with a static type on rhs,
6588 // see if static class implements all of id's protocols, directly or
6589 // through its super class and categories.
6590 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6591 E = rhsOPT->qual_end(); J != E; ++J) {
6592 ObjCProtocolDecl *rhsProto = *J;
6593 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6594 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6595 match = true;
6596 break;
6597 }
6598 }
Mike Stump11289f42009-09-09 15:08:12 +00006599 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006600 // make sure we check the class hierarchy.
6601 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6602 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6603 E = lhsQID->qual_end(); I != E; ++I) {
6604 // when comparing an id<P> on lhs with a static type on rhs,
6605 // see if static class implements all of id's protocols, directly or
6606 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00006607 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006608 match = true;
6609 break;
6610 }
6611 }
6612 }
6613 if (!match)
6614 return false;
6615 }
Mike Stump11289f42009-09-09 15:08:12 +00006616
Steve Naroff8e6aee52009-07-23 01:01:38 +00006617 return true;
6618 }
Mike Stump11289f42009-09-09 15:08:12 +00006619
Steve Naroff8e6aee52009-07-23 01:01:38 +00006620 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6621 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6622
Mike Stump11289f42009-09-09 15:08:12 +00006623 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00006624 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006625 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006626 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
6627 E = lhsOPT->qual_end(); I != E; ++I) {
6628 ObjCProtocolDecl *lhsProto = *I;
6629 bool match = false;
6630
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006631 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00006632 // see if static class implements all of id's protocols, directly or
6633 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006634 // First, lhs protocols in the qualifier list must be found, direct
6635 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006636 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6637 E = rhsQID->qual_end(); J != E; ++J) {
6638 ObjCProtocolDecl *rhsProto = *J;
6639 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6640 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6641 match = true;
6642 break;
6643 }
6644 }
6645 if (!match)
6646 return false;
6647 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006648
6649 // Static class's protocols, or its super class or category protocols
6650 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6651 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6652 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6653 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6654 // This is rather dubious but matches gcc's behavior. If lhs has
6655 // no type qualifier and its class has no static protocol(s)
6656 // assume that it is mismatch.
6657 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6658 return false;
6659 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6660 LHSInheritedProtocols.begin(),
6661 E = LHSInheritedProtocols.end(); I != E; ++I) {
6662 bool match = false;
6663 ObjCProtocolDecl *lhsProto = (*I);
6664 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6665 E = rhsQID->qual_end(); J != E; ++J) {
6666 ObjCProtocolDecl *rhsProto = *J;
6667 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6668 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6669 match = true;
6670 break;
6671 }
6672 }
6673 if (!match)
6674 return false;
6675 }
6676 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00006677 return true;
6678 }
6679 return false;
6680}
6681
Eli Friedman47f77112008-08-22 00:56:42 +00006682/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006683/// compatible for assignment from RHS to LHS. This handles validation of any
6684/// protocol qualifiers on the LHS or RHS.
6685///
Steve Naroff7cae42b2009-07-10 23:34:53 +00006686bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6687 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00006688 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6689 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6690
Steve Naroff1329fa02009-07-15 18:40:39 +00006691 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00006692 if (LHS->isObjCUnqualifiedIdOrClass() ||
6693 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00006694 return true;
6695
John McCall8b07ec22010-05-15 11:32:37 +00006696 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00006697 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6698 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00006699 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006700
6701 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6702 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6703 QualType(RHSOPT,0));
6704
John McCall8b07ec22010-05-15 11:32:37 +00006705 // If we have 2 user-defined types, fall into that path.
6706 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00006707 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006708
Steve Naroff8e6aee52009-07-23 01:01:38 +00006709 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006710}
6711
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006712/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00006713/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006714/// arguments in block literals. When passed as arguments, passing 'A*' where
6715/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6716/// not OK. For the return type, the opposite is not OK.
6717bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6718 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006719 const ObjCObjectPointerType *RHSOPT,
6720 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006721 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006722 return true;
6723
6724 if (LHSOPT->isObjCBuiltinType()) {
6725 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6726 }
6727
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006728 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006729 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6730 QualType(RHSOPT,0),
6731 false);
6732
6733 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6734 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6735 if (LHS && RHS) { // We have 2 user-defined types.
6736 if (LHS != RHS) {
6737 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006738 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006739 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006740 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006741 }
6742 else
6743 return true;
6744 }
6745 return false;
6746}
6747
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006748/// getIntersectionOfProtocols - This routine finds the intersection of set
6749/// of protocols inherited from two distinct objective-c pointer objects.
6750/// It is used to build composite qualifier list of the composite type of
6751/// the conditional expression involving two objective-c pointer objects.
6752static
6753void getIntersectionOfProtocols(ASTContext &Context,
6754 const ObjCObjectPointerType *LHSOPT,
6755 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006756 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006757
John McCall8b07ec22010-05-15 11:32:37 +00006758 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6759 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6760 assert(LHS->getInterface() && "LHS must have an interface base");
6761 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006762
6763 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6764 unsigned LHSNumProtocols = LHS->getNumProtocols();
6765 if (LHSNumProtocols > 0)
6766 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6767 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006768 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006769 Context.CollectInheritedProtocols(LHS->getInterface(),
6770 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006771 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6772 LHSInheritedProtocols.end());
6773 }
6774
6775 unsigned RHSNumProtocols = RHS->getNumProtocols();
6776 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00006777 ObjCProtocolDecl **RHSProtocols =
6778 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006779 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6780 if (InheritedProtocolSet.count(RHSProtocols[i]))
6781 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00006782 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006783 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006784 Context.CollectInheritedProtocols(RHS->getInterface(),
6785 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006786 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6787 RHSInheritedProtocols.begin(),
6788 E = RHSInheritedProtocols.end(); I != E; ++I)
6789 if (InheritedProtocolSet.count((*I)))
6790 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006791 }
6792}
6793
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006794/// areCommonBaseCompatible - Returns common base class of the two classes if
6795/// one found. Note that this is O'2 algorithm. But it will be called as the
6796/// last type comparison in a ?-exp of ObjC pointer types before a
6797/// warning is issued. So, its invokation is extremely rare.
6798QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00006799 const ObjCObjectPointerType *Lptr,
6800 const ObjCObjectPointerType *Rptr) {
6801 const ObjCObjectType *LHS = Lptr->getObjectType();
6802 const ObjCObjectType *RHS = Rptr->getObjectType();
6803 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6804 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00006805 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006806 return QualType();
6807
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006808 do {
John McCall8b07ec22010-05-15 11:32:37 +00006809 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006810 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006811 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00006812 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6813
6814 QualType Result = QualType(LHS, 0);
6815 if (!Protocols.empty())
6816 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6817 Result = getObjCObjectPointerType(Result);
6818 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006819 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006820 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006821
6822 return QualType();
6823}
6824
John McCall8b07ec22010-05-15 11:32:37 +00006825bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6826 const ObjCObjectType *RHS) {
6827 assert(LHS->getInterface() && "LHS is not an interface type");
6828 assert(RHS->getInterface() && "RHS is not an interface type");
6829
Chris Lattner49af6a42008-04-07 06:51:04 +00006830 // Verify that the base decls are compatible: the RHS must be a subclass of
6831 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00006832 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00006833 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006834
Chris Lattner49af6a42008-04-07 06:51:04 +00006835 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6836 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00006837 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00006838 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006839
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006840 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6841 // more detailed analysis is required.
6842 if (RHS->getNumProtocols() == 0) {
6843 // OK, if LHS is a superclass of RHS *and*
6844 // this superclass is assignment compatible with LHS.
6845 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006846 bool IsSuperClass =
6847 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6848 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006849 // OK if conversion of LHS to SuperClass results in narrowing of types
6850 // ; i.e., SuperClass may implement at least one of the protocols
6851 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6852 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6853 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006854 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006855 // If super class has no protocols, it is not a match.
6856 if (SuperClassInheritedProtocols.empty())
6857 return false;
6858
6859 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6860 LHSPE = LHS->qual_end();
6861 LHSPI != LHSPE; LHSPI++) {
6862 bool SuperImplementsProtocol = false;
6863 ObjCProtocolDecl *LHSProto = (*LHSPI);
6864
6865 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6866 SuperClassInheritedProtocols.begin(),
6867 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6868 ObjCProtocolDecl *SuperClassProto = (*I);
6869 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6870 SuperImplementsProtocol = true;
6871 break;
6872 }
6873 }
6874 if (!SuperImplementsProtocol)
6875 return false;
6876 }
6877 return true;
6878 }
6879 return false;
6880 }
Mike Stump11289f42009-09-09 15:08:12 +00006881
John McCall8b07ec22010-05-15 11:32:37 +00006882 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6883 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00006884 LHSPI != LHSPE; LHSPI++) {
6885 bool RHSImplementsProtocol = false;
6886
6887 // If the RHS doesn't implement the protocol on the left, the types
6888 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00006889 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6890 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00006891 RHSPI != RHSPE; RHSPI++) {
6892 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00006893 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00006894 break;
6895 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006896 }
6897 // FIXME: For better diagnostics, consider passing back the protocol name.
6898 if (!RHSImplementsProtocol)
6899 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00006900 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006901 // The RHS implements all protocols listed on the LHS.
6902 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00006903}
6904
Steve Naroffb7605152009-02-12 17:52:19 +00006905bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6906 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00006907 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6908 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006909
Steve Naroff7cae42b2009-07-10 23:34:53 +00006910 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00006911 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006912
6913 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6914 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00006915}
6916
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006917bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6918 return canAssignObjCInterfaces(
6919 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6920 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6921}
6922
Mike Stump11289f42009-09-09 15:08:12 +00006923/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00006924/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00006925/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00006926/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006927bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6928 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006929 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00006930 return hasSameType(LHS, RHS);
6931
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006932 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00006933}
6934
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006935bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00006936 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006937}
6938
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006939bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6940 return !mergeTypes(LHS, RHS, true).isNull();
6941}
6942
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006943/// mergeTransparentUnionType - if T is a transparent union type and a member
6944/// of T is compatible with SubType, return the merged type, else return
6945/// QualType()
6946QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6947 bool OfBlockPointer,
6948 bool Unqualified) {
6949 if (const RecordType *UT = T->getAsUnionType()) {
6950 RecordDecl *UD = UT->getDecl();
6951 if (UD->hasAttr<TransparentUnionAttr>()) {
6952 for (RecordDecl::field_iterator it = UD->field_begin(),
6953 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00006954 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006955 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6956 if (!MT.isNull())
6957 return MT;
6958 }
6959 }
6960 }
6961
6962 return QualType();
6963}
6964
6965/// mergeFunctionArgumentTypes - merge two types which appear as function
6966/// argument types
6967QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
6968 bool OfBlockPointer,
6969 bool Unqualified) {
6970 // GNU extension: two types are compatible if they appear as a function
6971 // argument, one of the types is a transparent union type and the other
6972 // type is compatible with a union member
6973 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6974 Unqualified);
6975 if (!lmerge.isNull())
6976 return lmerge;
6977
6978 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6979 Unqualified);
6980 if (!rmerge.isNull())
6981 return rmerge;
6982
6983 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6984}
6985
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006986QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006987 bool OfBlockPointer,
6988 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00006989 const FunctionType *lbase = lhs->getAs<FunctionType>();
6990 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006991 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6992 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00006993 bool allLTypes = true;
6994 bool allRTypes = true;
6995
6996 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006997 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00006998 if (OfBlockPointer) {
6999 QualType RHS = rbase->getResultType();
7000 QualType LHS = lbase->getResultType();
7001 bool UnqualifiedResult = Unqualified;
7002 if (!UnqualifiedResult)
7003 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007004 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00007005 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007006 else
John McCall8c6b56f2010-12-15 01:06:38 +00007007 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
7008 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007009 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007010
7011 if (Unqualified)
7012 retType = retType.getUnqualifiedType();
7013
7014 CanQualType LRetType = getCanonicalType(lbase->getResultType());
7015 CanQualType RRetType = getCanonicalType(rbase->getResultType());
7016 if (Unqualified) {
7017 LRetType = LRetType.getUnqualifiedType();
7018 RRetType = RRetType.getUnqualifiedType();
7019 }
7020
7021 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007022 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007023 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007024 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00007025
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00007026 // FIXME: double check this
7027 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
7028 // rbase->getRegParmAttr() != 0 &&
7029 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00007030 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
7031 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00007032
Douglas Gregor8c940862010-01-18 17:14:39 +00007033 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00007034 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Douglas Gregor8c940862010-01-18 17:14:39 +00007035 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00007036
John McCall8c6b56f2010-12-15 01:06:38 +00007037 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00007038 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
7039 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00007040 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
7041 return QualType();
7042
John McCall31168b02011-06-15 23:02:42 +00007043 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
7044 return QualType();
7045
John McCall8c6b56f2010-12-15 01:06:38 +00007046 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
7047 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00007048
Rafael Espindola8778c282012-11-29 16:09:03 +00007049 if (lbaseInfo.getNoReturn() != NoReturn)
7050 allLTypes = false;
7051 if (rbaseInfo.getNoReturn() != NoReturn)
7052 allRTypes = false;
7053
John McCall31168b02011-06-15 23:02:42 +00007054 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00007055
Eli Friedman47f77112008-08-22 00:56:42 +00007056 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007057 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
7058 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00007059 unsigned lproto_nargs = lproto->getNumArgs();
7060 unsigned rproto_nargs = rproto->getNumArgs();
7061
7062 // Compatible functions must have the same number of arguments
7063 if (lproto_nargs != rproto_nargs)
7064 return QualType();
7065
7066 // Variadic and non-variadic functions aren't compatible
7067 if (lproto->isVariadic() != rproto->isVariadic())
7068 return QualType();
7069
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00007070 if (lproto->getTypeQuals() != rproto->getTypeQuals())
7071 return QualType();
7072
Fariborz Jahanian97676972011-09-28 21:52:05 +00007073 if (LangOpts.ObjCAutoRefCount &&
7074 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
7075 return QualType();
7076
Eli Friedman47f77112008-08-22 00:56:42 +00007077 // Check argument compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007078 SmallVector<QualType, 10> types;
Eli Friedman47f77112008-08-22 00:56:42 +00007079 for (unsigned i = 0; i < lproto_nargs; i++) {
7080 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
7081 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007082 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
7083 OfBlockPointer,
7084 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007085 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007086
7087 if (Unqualified)
7088 argtype = argtype.getUnqualifiedType();
7089
Eli Friedman47f77112008-08-22 00:56:42 +00007090 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007091 if (Unqualified) {
7092 largtype = largtype.getUnqualifiedType();
7093 rargtype = rargtype.getUnqualifiedType();
7094 }
7095
Chris Lattner465fa322008-10-05 17:34:18 +00007096 if (getCanonicalType(argtype) != getCanonicalType(largtype))
7097 allLTypes = false;
7098 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
7099 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00007100 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00007101
Eli Friedman47f77112008-08-22 00:56:42 +00007102 if (allLTypes) return lhs;
7103 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007104
7105 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7106 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00007107 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007108 }
7109
7110 if (lproto) allRTypes = false;
7111 if (rproto) allLTypes = false;
7112
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007113 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00007114 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007115 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00007116 if (proto->isVariadic()) return QualType();
7117 // Check that the types are compatible with the types that
7118 // would result from default argument promotions (C99 6.7.5.3p15).
7119 // The only types actually affected are promotable integer
7120 // types and floats, which would be passed as a different
7121 // type depending on whether the prototype is visible.
7122 unsigned proto_nargs = proto->getNumArgs();
7123 for (unsigned i = 0; i < proto_nargs; ++i) {
7124 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00007125
Eli Friedman448ce402012-08-30 00:44:15 +00007126 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00007127 // to pass enum values.
Eli Friedman448ce402012-08-30 00:44:15 +00007128 if (const EnumType *Enum = argTy->getAs<EnumType>()) {
7129 argTy = Enum->getDecl()->getIntegerType();
7130 if (argTy.isNull())
7131 return QualType();
7132 }
Douglas Gregor2973d402010-02-03 19:27:29 +00007133
Eli Friedman47f77112008-08-22 00:56:42 +00007134 if (argTy->isPromotableIntegerType() ||
7135 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
7136 return QualType();
7137 }
7138
7139 if (allLTypes) return lhs;
7140 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007141
7142 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7143 EPI.ExtInfo = einfo;
Reid Kleckner896b32f2013-06-10 20:51:09 +00007144 return getFunctionType(retType, proto->getArgTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007145 }
7146
7147 if (allLTypes) return lhs;
7148 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00007149 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00007150}
7151
John McCall433c2e62013-03-21 00:10:07 +00007152/// Given that we have an enum type and a non-enum type, try to merge them.
7153static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7154 QualType other, bool isBlockReturnType) {
7155 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7156 // a signed integer type, or an unsigned integer type.
7157 // Compatibility is based on the underlying type, not the promotion
7158 // type.
7159 QualType underlyingType = ET->getDecl()->getIntegerType();
7160 if (underlyingType.isNull()) return QualType();
7161 if (Context.hasSameType(underlyingType, other))
7162 return other;
7163
7164 // In block return types, we're more permissive and accept any
7165 // integral type of the same size.
7166 if (isBlockReturnType && other->isIntegerType() &&
7167 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7168 return other;
7169
7170 return QualType();
7171}
7172
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007173QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007174 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007175 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00007176 // C++ [expr]: If an expression initially has the type "reference to T", the
7177 // type is adjusted to "T" prior to any further analysis, the expression
7178 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007179 // expression is an lvalue unless the reference is an rvalue reference and
7180 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00007181 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7182 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007183
7184 if (Unqualified) {
7185 LHS = LHS.getUnqualifiedType();
7186 RHS = RHS.getUnqualifiedType();
7187 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00007188
Eli Friedman47f77112008-08-22 00:56:42 +00007189 QualType LHSCan = getCanonicalType(LHS),
7190 RHSCan = getCanonicalType(RHS);
7191
7192 // If two types are identical, they are compatible.
7193 if (LHSCan == RHSCan)
7194 return LHS;
7195
John McCall8ccfcb52009-09-24 19:53:00 +00007196 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007197 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7198 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00007199 if (LQuals != RQuals) {
7200 // If any of these qualifiers are different, we have a type
7201 // mismatch.
7202 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00007203 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7204 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00007205 return QualType();
7206
7207 // Exactly one GC qualifier difference is allowed: __strong is
7208 // okay if the other type has no GC qualifier but is an Objective
7209 // C object pointer (i.e. implicitly strong by default). We fix
7210 // this by pretending that the unqualified type was actually
7211 // qualified __strong.
7212 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7213 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7214 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7215
7216 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7217 return QualType();
7218
7219 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7220 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7221 }
7222 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7223 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7224 }
Eli Friedman47f77112008-08-22 00:56:42 +00007225 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00007226 }
7227
7228 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00007229
Eli Friedmandcca6332009-06-01 01:22:52 +00007230 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7231 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00007232
Chris Lattnerfd652912008-01-14 05:45:46 +00007233 // We want to consider the two function types to be the same for these
7234 // comparisons, just force one to the other.
7235 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7236 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00007237
7238 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00007239 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7240 LHSClass = Type::ConstantArray;
7241 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7242 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00007243
John McCall8b07ec22010-05-15 11:32:37 +00007244 // ObjCInterfaces are just specialized ObjCObjects.
7245 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7246 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7247
Nate Begemance4d7fc2008-04-18 23:10:10 +00007248 // Canonicalize ExtVector -> Vector.
7249 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7250 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00007251
Chris Lattner95554662008-04-07 05:43:21 +00007252 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007253 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00007254 // Note that we only have special rules for turning block enum
7255 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00007256 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007257 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007258 }
John McCall9dd450b2009-09-21 23:43:11 +00007259 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007260 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007261 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007262 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00007263 if (OfBlockPointer && !BlockReturnType) {
7264 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7265 return LHS;
7266 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7267 return RHS;
7268 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007269
Eli Friedman47f77112008-08-22 00:56:42 +00007270 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00007271 }
Eli Friedman47f77112008-08-22 00:56:42 +00007272
Steve Naroffc6edcbd2008-01-09 22:43:08 +00007273 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007274 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007275#define TYPE(Class, Base)
7276#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00007277#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007278#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7279#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7280#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00007281 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007282
Richard Smith27d807c2013-04-30 13:56:41 +00007283 case Type::Auto:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007284 case Type::LValueReference:
7285 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007286 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00007287 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007288
John McCall8b07ec22010-05-15 11:32:37 +00007289 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007290 case Type::IncompleteArray:
7291 case Type::VariableArray:
7292 case Type::FunctionProto:
7293 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00007294 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007295
Chris Lattnerfd652912008-01-14 05:45:46 +00007296 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00007297 {
7298 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007299 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7300 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007301 if (Unqualified) {
7302 LHSPointee = LHSPointee.getUnqualifiedType();
7303 RHSPointee = RHSPointee.getUnqualifiedType();
7304 }
7305 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7306 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007307 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00007308 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007309 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00007310 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007311 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007312 return getPointerType(ResultType);
7313 }
Steve Naroff68e167d2008-12-10 17:49:55 +00007314 case Type::BlockPointer:
7315 {
7316 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007317 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7318 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007319 if (Unqualified) {
7320 LHSPointee = LHSPointee.getUnqualifiedType();
7321 RHSPointee = RHSPointee.getUnqualifiedType();
7322 }
7323 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7324 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00007325 if (ResultType.isNull()) return QualType();
7326 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7327 return LHS;
7328 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7329 return RHS;
7330 return getBlockPointerType(ResultType);
7331 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00007332 case Type::Atomic:
7333 {
7334 // Merge two pointer types, while trying to preserve typedef info
7335 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7336 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7337 if (Unqualified) {
7338 LHSValue = LHSValue.getUnqualifiedType();
7339 RHSValue = RHSValue.getUnqualifiedType();
7340 }
7341 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7342 Unqualified);
7343 if (ResultType.isNull()) return QualType();
7344 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7345 return LHS;
7346 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7347 return RHS;
7348 return getAtomicType(ResultType);
7349 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007350 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00007351 {
7352 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7353 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7354 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7355 return QualType();
7356
7357 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7358 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007359 if (Unqualified) {
7360 LHSElem = LHSElem.getUnqualifiedType();
7361 RHSElem = RHSElem.getUnqualifiedType();
7362 }
7363
7364 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007365 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00007366 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7367 return LHS;
7368 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7369 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00007370 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7371 ArrayType::ArraySizeModifier(), 0);
7372 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7373 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007374 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7375 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00007376 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7377 return LHS;
7378 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7379 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007380 if (LVAT) {
7381 // FIXME: This isn't correct! But tricky to implement because
7382 // the array's size has to be the size of LHS, but the type
7383 // has to be different.
7384 return LHS;
7385 }
7386 if (RVAT) {
7387 // FIXME: This isn't correct! But tricky to implement because
7388 // the array's size has to be the size of RHS, but the type
7389 // has to be different.
7390 return RHS;
7391 }
Eli Friedman3e62c212008-08-22 01:48:21 +00007392 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7393 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00007394 return getIncompleteArrayType(ResultType,
7395 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007396 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007397 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007398 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007399 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007400 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00007401 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00007402 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007403 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00007404 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00007405 case Type::Complex:
7406 // Distinct complex types are incompatible.
7407 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007408 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00007409 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00007410 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7411 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00007412 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00007413 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00007414 case Type::ObjCObject: {
7415 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00007416 // FIXME: This should be type compatibility, e.g. whether
7417 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00007418 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7419 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7420 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00007421 return LHS;
7422
Eli Friedman47f77112008-08-22 00:56:42 +00007423 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00007424 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007425 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007426 if (OfBlockPointer) {
7427 if (canAssignObjCInterfacesInBlockPointer(
7428 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007429 RHS->getAs<ObjCObjectPointerType>(),
7430 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00007431 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007432 return QualType();
7433 }
John McCall9dd450b2009-09-21 23:43:11 +00007434 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7435 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007436 return LHS;
7437
Steve Naroffc68cfcf2008-12-10 22:14:21 +00007438 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00007439 }
Steve Naroff32e44c02007-10-15 20:41:53 +00007440 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007441
David Blaikie8a40f702012-01-17 06:56:22 +00007442 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00007443}
Ted Kremenekfc581a92007-10-31 17:10:13 +00007444
Fariborz Jahanian97676972011-09-28 21:52:05 +00007445bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7446 const FunctionProtoType *FromFunctionType,
7447 const FunctionProtoType *ToFunctionType) {
7448 if (FromFunctionType->hasAnyConsumedArgs() !=
7449 ToFunctionType->hasAnyConsumedArgs())
7450 return false;
7451 FunctionProtoType::ExtProtoInfo FromEPI =
7452 FromFunctionType->getExtProtoInfo();
7453 FunctionProtoType::ExtProtoInfo ToEPI =
7454 ToFunctionType->getExtProtoInfo();
7455 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
7456 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
7457 ArgIdx != NumArgs; ++ArgIdx) {
7458 if (FromEPI.ConsumedArguments[ArgIdx] !=
7459 ToEPI.ConsumedArguments[ArgIdx])
7460 return false;
7461 }
7462 return true;
7463}
7464
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007465/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7466/// 'RHS' attributes and returns the merged version; including for function
7467/// return types.
7468QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7469 QualType LHSCan = getCanonicalType(LHS),
7470 RHSCan = getCanonicalType(RHS);
7471 // If two types are identical, they are compatible.
7472 if (LHSCan == RHSCan)
7473 return LHS;
7474 if (RHSCan->isFunctionType()) {
7475 if (!LHSCan->isFunctionType())
7476 return QualType();
7477 QualType OldReturnType =
7478 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
7479 QualType NewReturnType =
7480 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
7481 QualType ResReturnType =
7482 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7483 if (ResReturnType.isNull())
7484 return QualType();
7485 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7486 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7487 // In either case, use OldReturnType to build the new function type.
7488 const FunctionType *F = LHS->getAs<FunctionType>();
7489 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00007490 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7491 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00007492 QualType ResultType =
7493 getFunctionType(OldReturnType, FPT->getArgTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007494 return ResultType;
7495 }
7496 }
7497 return QualType();
7498 }
7499
7500 // If the qualifiers are different, the types can still be merged.
7501 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7502 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7503 if (LQuals != RQuals) {
7504 // If any of these qualifiers are different, we have a type mismatch.
7505 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7506 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7507 return QualType();
7508
7509 // Exactly one GC qualifier difference is allowed: __strong is
7510 // okay if the other type has no GC qualifier but is an Objective
7511 // C object pointer (i.e. implicitly strong by default). We fix
7512 // this by pretending that the unqualified type was actually
7513 // qualified __strong.
7514 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7515 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7516 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7517
7518 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7519 return QualType();
7520
7521 if (GC_L == Qualifiers::Strong)
7522 return LHS;
7523 if (GC_R == Qualifiers::Strong)
7524 return RHS;
7525 return QualType();
7526 }
7527
7528 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7529 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7530 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7531 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7532 if (ResQT == LHSBaseQT)
7533 return LHS;
7534 if (ResQT == RHSBaseQT)
7535 return RHS;
7536 }
7537 return QualType();
7538}
7539
Chris Lattner4ba0cef2008-04-07 07:01:58 +00007540//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007541// Integer Predicates
7542//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00007543
Jay Foad39c79802011-01-12 09:06:06 +00007544unsigned ASTContext::getIntWidth(QualType T) const {
Richard Smithe9521062013-10-15 04:56:17 +00007545 if (const EnumType *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00007546 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00007547 if (T->isBooleanType())
7548 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00007549 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007550 return (unsigned)getTypeSize(T);
7551}
7552
Abramo Bagnara13640492012-09-09 10:21:24 +00007553QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007554 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00007555
7556 // Turn <4 x signed int> -> <4 x unsigned int>
7557 if (const VectorType *VTy = T->getAs<VectorType>())
7558 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00007559 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00007560
7561 // For enums, we return the unsigned version of the base type.
7562 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007563 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00007564
7565 const BuiltinType *BTy = T->getAs<BuiltinType>();
7566 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007567 switch (BTy->getKind()) {
7568 case BuiltinType::Char_S:
7569 case BuiltinType::SChar:
7570 return UnsignedCharTy;
7571 case BuiltinType::Short:
7572 return UnsignedShortTy;
7573 case BuiltinType::Int:
7574 return UnsignedIntTy;
7575 case BuiltinType::Long:
7576 return UnsignedLongTy;
7577 case BuiltinType::LongLong:
7578 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00007579 case BuiltinType::Int128:
7580 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007581 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007582 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007583 }
7584}
7585
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00007586ASTMutationListener::~ASTMutationListener() { }
7587
Richard Smith1fa5d642013-05-11 05:45:24 +00007588void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7589 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00007590
7591//===----------------------------------------------------------------------===//
7592// Builtin Type Computation
7593//===----------------------------------------------------------------------===//
7594
7595/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00007596/// pointer over the consumed characters. This returns the resultant type. If
7597/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7598/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7599/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007600///
7601/// RequiresICE is filled in on return to indicate whether the value is required
7602/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00007603static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00007604 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007605 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00007606 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00007607 // Modifiers.
7608 int HowLong = 0;
7609 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007610 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00007611
Chris Lattnerdc226c22010-10-01 22:42:38 +00007612 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00007613 bool Done = false;
7614 while (!Done) {
7615 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00007616 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00007617 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007618 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00007619 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007620 case 'S':
7621 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7622 assert(!Signed && "Can't use 'S' modifier multiple times!");
7623 Signed = true;
7624 break;
7625 case 'U':
7626 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7627 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7628 Unsigned = true;
7629 break;
7630 case 'L':
7631 assert(HowLong <= 2 && "Can't have LLLL modifier");
7632 ++HowLong;
7633 break;
7634 }
7635 }
7636
7637 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00007638
Chris Lattnerecd79c62009-06-14 00:45:47 +00007639 // Read the base type.
7640 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00007641 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007642 case 'v':
7643 assert(HowLong == 0 && !Signed && !Unsigned &&
7644 "Bad modifiers used with 'v'!");
7645 Type = Context.VoidTy;
7646 break;
Jack Carter24bef982013-08-15 15:16:57 +00007647 case 'h':
7648 assert(HowLong == 0 && !Signed && !Unsigned &&
7649 "Bad modifiers used with 'f'!");
7650 Type = Context.HalfTy;
7651 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007652 case 'f':
7653 assert(HowLong == 0 && !Signed && !Unsigned &&
7654 "Bad modifiers used with 'f'!");
7655 Type = Context.FloatTy;
7656 break;
7657 case 'd':
7658 assert(HowLong < 2 && !Signed && !Unsigned &&
7659 "Bad modifiers used with 'd'!");
7660 if (HowLong)
7661 Type = Context.LongDoubleTy;
7662 else
7663 Type = Context.DoubleTy;
7664 break;
7665 case 's':
7666 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7667 if (Unsigned)
7668 Type = Context.UnsignedShortTy;
7669 else
7670 Type = Context.ShortTy;
7671 break;
7672 case 'i':
7673 if (HowLong == 3)
7674 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7675 else if (HowLong == 2)
7676 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7677 else if (HowLong == 1)
7678 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7679 else
7680 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7681 break;
7682 case 'c':
7683 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7684 if (Signed)
7685 Type = Context.SignedCharTy;
7686 else if (Unsigned)
7687 Type = Context.UnsignedCharTy;
7688 else
7689 Type = Context.CharTy;
7690 break;
7691 case 'b': // boolean
7692 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7693 Type = Context.BoolTy;
7694 break;
7695 case 'z': // size_t.
7696 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7697 Type = Context.getSizeType();
7698 break;
7699 case 'F':
7700 Type = Context.getCFConstantStringType();
7701 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00007702 case 'G':
7703 Type = Context.getObjCIdType();
7704 break;
7705 case 'H':
7706 Type = Context.getObjCSelType();
7707 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00007708 case 'M':
7709 Type = Context.getObjCSuperType();
7710 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007711 case 'a':
7712 Type = Context.getBuiltinVaListType();
7713 assert(!Type.isNull() && "builtin va list type not initialized!");
7714 break;
7715 case 'A':
7716 // This is a "reference" to a va_list; however, what exactly
7717 // this means depends on how va_list is defined. There are two
7718 // different kinds of va_list: ones passed by value, and ones
7719 // passed by reference. An example of a by-value va_list is
7720 // x86, where va_list is a char*. An example of by-ref va_list
7721 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7722 // we want this argument to be a char*&; for x86-64, we want
7723 // it to be a __va_list_tag*.
7724 Type = Context.getBuiltinVaListType();
7725 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007726 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00007727 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007728 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00007729 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007730 break;
7731 case 'V': {
7732 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007733 unsigned NumElements = strtoul(Str, &End, 10);
7734 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007735 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00007736
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007737 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7738 RequiresICE, false);
7739 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00007740
7741 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00007742 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00007743 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007744 break;
7745 }
Douglas Gregorfed66992012-06-07 18:08:25 +00007746 case 'E': {
7747 char *End;
7748
7749 unsigned NumElements = strtoul(Str, &End, 10);
7750 assert(End != Str && "Missing vector size");
7751
7752 Str = End;
7753
7754 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7755 false);
7756 Type = Context.getExtVectorType(ElementType, NumElements);
7757 break;
7758 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007759 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007760 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7761 false);
7762 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007763 Type = Context.getComplexType(ElementType);
7764 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00007765 }
7766 case 'Y' : {
7767 Type = Context.getPointerDiffType();
7768 break;
7769 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00007770 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00007771 Type = Context.getFILEType();
7772 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007773 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007774 return QualType();
7775 }
Mike Stump2adb4da2009-07-28 23:47:15 +00007776 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00007777 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00007778 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00007779 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00007780 else
7781 Type = Context.getjmp_bufType();
7782
Mike Stump2adb4da2009-07-28 23:47:15 +00007783 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007784 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00007785 return QualType();
7786 }
7787 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00007788 case 'K':
7789 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7790 Type = Context.getucontext_tType();
7791
7792 if (Type.isNull()) {
7793 Error = ASTContext::GE_Missing_ucontext;
7794 return QualType();
7795 }
7796 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00007797 case 'p':
7798 Type = Context.getProcessIDType();
7799 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00007800 }
Mike Stump11289f42009-09-09 15:08:12 +00007801
Chris Lattnerdc226c22010-10-01 22:42:38 +00007802 // If there are modifiers and if we're allowed to parse them, go for it.
7803 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007804 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00007805 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007806 default: Done = true; --Str; break;
7807 case '*':
7808 case '&': {
7809 // Both pointers and references can have their pointee types
7810 // qualified with an address space.
7811 char *End;
7812 unsigned AddrSpace = strtoul(Str, &End, 10);
7813 if (End != Str && AddrSpace != 0) {
7814 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7815 Str = End;
7816 }
7817 if (c == '*')
7818 Type = Context.getPointerType(Type);
7819 else
7820 Type = Context.getLValueReferenceType(Type);
7821 break;
7822 }
7823 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7824 case 'C':
7825 Type = Type.withConst();
7826 break;
7827 case 'D':
7828 Type = Context.getVolatileType(Type);
7829 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00007830 case 'R':
7831 Type = Type.withRestrict();
7832 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007833 }
7834 }
Chris Lattner84733392010-10-01 07:13:18 +00007835
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007836 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00007837 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00007838
Chris Lattnerecd79c62009-06-14 00:45:47 +00007839 return Type;
7840}
7841
7842/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00007843QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007844 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00007845 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007846 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00007847
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007848 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00007849
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007850 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007851 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007852 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7853 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007854 if (Error != GE_None)
7855 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007856
7857 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7858
Chris Lattnerecd79c62009-06-14 00:45:47 +00007859 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007860 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007861 if (Error != GE_None)
7862 return QualType();
7863
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007864 // If this argument is required to be an IntegerConstantExpression and the
7865 // caller cares, fill in the bitmask we return.
7866 if (RequiresICE && IntegerConstantArgs)
7867 *IntegerConstantArgs |= 1 << ArgTypes.size();
7868
Chris Lattnerecd79c62009-06-14 00:45:47 +00007869 // Do array -> pointer decay. The builtin should use the decayed type.
7870 if (Ty->isArrayType())
7871 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00007872
Chris Lattnerecd79c62009-06-14 00:45:47 +00007873 ArgTypes.push_back(Ty);
7874 }
7875
7876 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7877 "'.' should only occur at end of builtin type list!");
7878
Reid Kleckner78af0702013-08-27 23:08:25 +00007879 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00007880 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7881
7882 bool Variadic = (TypeStr[0] == '.');
7883
7884 // We really shouldn't be making a no-proto type here, especially in C++.
7885 if (ArgTypes.empty() && Variadic)
7886 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00007887
John McCalldb40c7f2010-12-14 08:05:40 +00007888 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00007889 EPI.ExtInfo = EI;
7890 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00007891
Jordan Rose5c382722013-03-08 21:51:21 +00007892 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007893}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00007894
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007895GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007896 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007897 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007898
Rafael Espindola3ae00052013-05-13 00:12:11 +00007899 GVALinkage External = GVA_StrongExternal;
7900 switch (FD->getTemplateSpecializationKind()) {
7901 case TSK_Undeclared:
7902 case TSK_ExplicitSpecialization:
7903 External = GVA_StrongExternal;
7904 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007905
Rafael Espindola3ae00052013-05-13 00:12:11 +00007906 case TSK_ExplicitInstantiationDefinition:
7907 return GVA_ExplicitTemplateInstantiation;
7908
7909 case TSK_ExplicitInstantiationDeclaration:
7910 case TSK_ImplicitInstantiation:
7911 External = GVA_TemplateInstantiation;
7912 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007913 }
7914
7915 if (!FD->isInlined())
7916 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00007917
7918 if ((!getLangOpts().CPlusPlus && !getLangOpts().MicrosoftMode) ||
7919 FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007920 // GNU or C99 inline semantics. Determine whether this symbol should be
7921 // externally visible.
7922 if (FD->isInlineDefinitionExternallyVisible())
7923 return External;
7924
7925 // C99 inline semantics, where the symbol is not externally visible.
7926 return GVA_C99Inline;
7927 }
7928
7929 // C++0x [temp.explicit]p9:
7930 // [ Note: The intent is that an inline function that is the subject of
7931 // an explicit instantiation declaration will still be implicitly
7932 // instantiated when used so that the body can be considered for
7933 // inlining, but that no out-of-line copy of the inline function would be
7934 // generated in the translation unit. -- end note ]
7935 if (FD->getTemplateSpecializationKind()
7936 == TSK_ExplicitInstantiationDeclaration)
7937 return GVA_C99Inline;
7938
7939 return GVA_CXXInline;
7940}
7941
7942GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007943 if (!VD->isExternallyVisible())
7944 return GVA_Internal;
7945
Richard Smith8809a0c2013-09-27 20:14:12 +00007946 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007947 case TSK_Undeclared:
7948 case TSK_ExplicitSpecialization:
7949 return GVA_StrongExternal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007950
Rafael Espindola3ae00052013-05-13 00:12:11 +00007951 case TSK_ExplicitInstantiationDeclaration:
7952 llvm_unreachable("Variable should not be instantiated");
7953 // Fall through to treat this like any other instantiation.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007954
Rafael Espindola3ae00052013-05-13 00:12:11 +00007955 case TSK_ExplicitInstantiationDefinition:
7956 return GVA_ExplicitTemplateInstantiation;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007957
Rafael Espindola3ae00052013-05-13 00:12:11 +00007958 case TSK_ImplicitInstantiation:
7959 return GVA_TemplateInstantiation;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007960 }
Rafael Espindola27699c82013-05-13 14:05:53 +00007961
7962 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007963}
7964
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00007965bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007966 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7967 if (!VD->isFileVarDecl())
7968 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00007969 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7970 // We never need to emit an uninstantiated function template.
7971 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
7972 return false;
7973 } else
7974 return false;
7975
7976 // If this is a member of a class template, we do not need to emit it.
7977 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007978 return false;
7979
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007980 // Weak references don't produce any output by themselves.
7981 if (D->hasAttr<WeakRefAttr>())
7982 return false;
7983
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007984 // Aliases and used decls are required.
7985 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7986 return true;
7987
7988 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7989 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00007990 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00007991 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007992
7993 // Constructors and destructors are required.
7994 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7995 return true;
7996
John McCall6bd2a892013-01-25 22:31:03 +00007997 // The key function for a class is required. This rule only comes
7998 // into play when inline functions can be key functions, though.
7999 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
8000 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8001 const CXXRecordDecl *RD = MD->getParent();
8002 if (MD->isOutOfLine() && RD->isDynamicClass()) {
8003 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
8004 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
8005 return true;
8006 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008007 }
8008 }
8009
8010 GVALinkage Linkage = GetGVALinkageForFunction(FD);
8011
8012 // static, static inline, always_inline, and extern inline functions can
8013 // always be deferred. Normal inline functions can be deferred in C99/C++.
8014 // Implicit template instantiations can also be deferred in C++.
8015 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev79de4d42012-02-02 06:06:34 +00008016 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008017 return false;
8018 return true;
8019 }
Douglas Gregor87d81242011-09-10 00:22:34 +00008020
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008021 const VarDecl *VD = cast<VarDecl>(D);
8022 assert(VD->isFileVarDecl() && "Expected file scoped var");
8023
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00008024 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
8025 return false;
8026
Richard Smitha0e5e542012-11-12 21:38:00 +00008027 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008028 GVALinkage L = GetGVALinkageForVariable(VD);
Richard Smitha0e5e542012-11-12 21:38:00 +00008029 if (L != GVA_Internal && L != GVA_TemplateInstantiation)
8030 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008031
Richard Smitha0e5e542012-11-12 21:38:00 +00008032 // Variables that have destruction with side-effects are required.
8033 if (VD->getType().isDestructedType())
8034 return true;
8035
8036 // Variables that have initialization with side-effects are required.
8037 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
8038 return true;
8039
8040 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008041}
Charles Davis53c59df2010-08-16 03:33:14 +00008042
Reid Kleckner78af0702013-08-27 23:08:25 +00008043CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
8044 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00008045 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00008046 if (IsCXXMethod)
8047 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00008048
Reid Kleckner78af0702013-08-27 23:08:25 +00008049 return (LangOpts.MRTD && !IsVariadic) ? CC_X86StdCall : CC_C;
Charles Davis99202b32010-11-09 18:04:24 +00008050}
8051
Jay Foad39c79802011-01-12 09:06:06 +00008052bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00008053 // Pass through to the C++ ABI object
8054 return ABI->isNearlyEmpty(RD);
8055}
8056
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008057MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00008058 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00008059 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00008060 case TargetCXXABI::GenericItanium:
8061 case TargetCXXABI::GenericARM:
8062 case TargetCXXABI::iOS:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008063 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00008064 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00008065 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008066 }
David Blaikie83d382b2011-09-23 05:06:16 +00008067 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00008068}
8069
Charles Davis53c59df2010-08-16 03:33:14 +00008070CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008071
8072size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00008073 return ASTRecordLayouts.getMemorySize() +
8074 llvm::capacity_in_bytes(ObjCLayouts) +
8075 llvm::capacity_in_bytes(KeyFunctions) +
8076 llvm::capacity_in_bytes(ObjCImpls) +
8077 llvm::capacity_in_bytes(BlockVarCopyInits) +
8078 llvm::capacity_in_bytes(DeclAttrs) +
8079 llvm::capacity_in_bytes(TemplateOrInstantiation) +
8080 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
8081 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
8082 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
8083 llvm::capacity_in_bytes(OverriddenMethods) +
8084 llvm::capacity_in_bytes(Types) +
8085 llvm::capacity_in_bytes(VariableArrayTypes) +
8086 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008087}
Ted Kremenek540017e2011-10-06 05:00:56 +00008088
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00008089/// getIntTypeForBitwidth -
8090/// sets integer QualTy according to specified details:
8091/// bitwidth, signed/unsigned.
8092/// Returns empty type if there is no appropriate target types.
8093QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
8094 unsigned Signed) const {
8095 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
8096 CanQualType QualTy = getFromTargetType(Ty);
8097 if (!QualTy && DestWidth == 128)
8098 return Signed ? Int128Ty : UnsignedInt128Ty;
8099 return QualTy;
8100}
8101
8102/// getRealTypeForBitwidth -
8103/// sets floating point QualTy according to specified bitwidth.
8104/// Returns empty type if there is no appropriate target types.
8105QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
8106 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
8107 switch (Ty) {
8108 case TargetInfo::Float:
8109 return FloatTy;
8110 case TargetInfo::Double:
8111 return DoubleTy;
8112 case TargetInfo::LongDouble:
8113 return LongDoubleTy;
8114 case TargetInfo::NoFloat:
8115 return QualType();
8116 }
8117
8118 llvm_unreachable("Unhandled TargetInfo::RealType value");
8119}
8120
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008121void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
8122 if (Number > 1)
8123 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00008124}
8125
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008126unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
8127 llvm::DenseMap<const NamedDecl *, unsigned>::const_iterator I =
8128 MangleNumbers.find(ND);
8129 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00008130}
8131
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008132MangleNumberingContext &
8133ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00008134 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
8135 MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
8136 if (!MCtx)
8137 MCtx = createMangleNumberingContext();
8138 return *MCtx;
8139}
8140
8141MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
8142 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00008143}
8144
Ted Kremenek540017e2011-10-06 05:00:56 +00008145void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8146 ParamIndices[D] = index;
8147}
8148
8149unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8150 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8151 assert(I != ParamIndices.end() &&
8152 "ParmIndices lacks entry set by ParmVarDecl");
8153 return I->second;
8154}
Fariborz Jahanian615de762013-05-28 17:37:39 +00008155
Richard Smithe6c01442013-06-05 00:46:14 +00008156APValue *
8157ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8158 bool MayCreate) {
8159 assert(E && E->getStorageDuration() == SD_Static &&
8160 "don't need to cache the computed value for this temporary");
8161 if (MayCreate)
8162 return &MaterializedTemporaryValues[E];
8163
8164 llvm::DenseMap<const MaterializeTemporaryExpr *, APValue>::iterator I =
8165 MaterializedTemporaryValues.find(E);
8166 return I == MaterializedTemporaryValues.end() ? 0 : &I->second;
8167}
8168
Fariborz Jahanian615de762013-05-28 17:37:39 +00008169bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8170 const llvm::Triple &T = getTargetInfo().getTriple();
8171 if (!T.isOSDarwin())
8172 return false;
8173
Bob Wilson2c82c3d2013-11-02 23:27:49 +00008174 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
8175 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
8176 return false;
8177
Fariborz Jahanian615de762013-05-28 17:37:39 +00008178 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8179 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8180 uint64_t Size = sizeChars.getQuantity();
8181 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8182 unsigned Align = alignChars.getQuantity();
8183 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8184 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8185}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008186
8187namespace {
8188
8189 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8190 /// parents as defined by the \c RecursiveASTVisitor.
8191 ///
8192 /// Note that the relationship described here is purely in terms of AST
8193 /// traversal - there are other relationships (for example declaration context)
8194 /// in the AST that are better modeled by special matchers.
8195 ///
8196 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
8197 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
8198
8199 public:
8200 /// \brief Builds and returns the translation unit's parent map.
8201 ///
8202 /// The caller takes ownership of the returned \c ParentMap.
8203 static ASTContext::ParentMap *buildMap(TranslationUnitDecl &TU) {
8204 ParentMapASTVisitor Visitor(new ASTContext::ParentMap);
8205 Visitor.TraverseDecl(&TU);
8206 return Visitor.Parents;
8207 }
8208
8209 private:
8210 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8211
8212 ParentMapASTVisitor(ASTContext::ParentMap *Parents) : Parents(Parents) {
8213 }
8214
8215 bool shouldVisitTemplateInstantiations() const {
8216 return true;
8217 }
8218 bool shouldVisitImplicitCode() const {
8219 return true;
8220 }
8221 // Disables data recursion. We intercept Traverse* methods in the RAV, which
8222 // are not triggered during data recursion.
8223 bool shouldUseDataRecursionFor(clang::Stmt *S) const {
8224 return false;
8225 }
8226
8227 template <typename T>
8228 bool TraverseNode(T *Node, bool(VisitorBase:: *traverse) (T *)) {
8229 if (Node == NULL)
8230 return true;
8231 if (ParentStack.size() > 0)
8232 // FIXME: Currently we add the same parent multiple times, for example
8233 // when we visit all subexpressions of template instantiations; this is
8234 // suboptimal, bug benign: the only way to visit those is with
8235 // hasAncestor / hasParent, and those do not create new matches.
8236 // The plan is to enable DynTypedNode to be storable in a map or hash
8237 // map. The main problem there is to implement hash functions /
8238 // comparison operators for all types that DynTypedNode supports that
8239 // do not have pointer identity.
8240 (*Parents)[Node].push_back(ParentStack.back());
8241 ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node));
8242 bool Result = (this ->* traverse) (Node);
8243 ParentStack.pop_back();
8244 return Result;
8245 }
8246
8247 bool TraverseDecl(Decl *DeclNode) {
8248 return TraverseNode(DeclNode, &VisitorBase::TraverseDecl);
8249 }
8250
8251 bool TraverseStmt(Stmt *StmtNode) {
8252 return TraverseNode(StmtNode, &VisitorBase::TraverseStmt);
8253 }
8254
8255 ASTContext::ParentMap *Parents;
8256 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8257
8258 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8259 };
8260
8261} // end namespace
8262
8263ASTContext::ParentVector
8264ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
8265 assert(Node.getMemoizationData() &&
8266 "Invariant broken: only nodes that support memoization may be "
8267 "used in the parent map.");
8268 if (!AllParents) {
8269 // We always need to run over the whole translation unit, as
8270 // hasAncestor can escape any subtree.
8271 AllParents.reset(
8272 ParentMapASTVisitor::buildMap(*getTranslationUnitDecl()));
8273 }
8274 ParentMap::const_iterator I = AllParents->find(Node.getMemoizationData());
8275 if (I == AllParents->end()) {
8276 return ParentVector();
8277 }
8278 return I->second;
8279}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008280
8281bool
8282ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
8283 const ObjCMethodDecl *MethodImpl) {
8284 // No point trying to match an unavailable/deprecated mothod.
8285 if (MethodDecl->hasAttr<UnavailableAttr>()
8286 || MethodDecl->hasAttr<DeprecatedAttr>())
8287 return false;
8288 if (MethodDecl->getObjCDeclQualifier() !=
8289 MethodImpl->getObjCDeclQualifier())
8290 return false;
8291 if (!hasSameType(MethodDecl->getResultType(),
8292 MethodImpl->getResultType()))
8293 return false;
8294
8295 if (MethodDecl->param_size() != MethodImpl->param_size())
8296 return false;
8297
8298 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
8299 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
8300 EF = MethodDecl->param_end();
8301 IM != EM && IF != EF; ++IM, ++IF) {
8302 const ParmVarDecl *DeclVar = (*IF);
8303 const ParmVarDecl *ImplVar = (*IM);
8304 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
8305 return false;
8306 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
8307 return false;
8308 }
8309 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
8310
8311}