blob: 65bb024b2a93678da75f5d1f6676e9e60bf9f168 [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"
Reid Kleckner96f8f932014-02-05 17:27:08 +000032#include "clang/AST/VTableBuilder.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000033#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000034#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000035#include "clang/Basic/TargetInfo.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000036#include "llvm/ADT/SmallString.h"
Anders Carlssond8499822007-10-29 05:01:08 +000037#include "llvm/ADT/StringExtras.h"
Robert Lyttoneaf6f362013-11-12 10:09:34 +000038#include "llvm/ADT/Triple.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000039#include "llvm/Support/Capacity.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000040#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000041#include "llvm/Support/raw_ostream.h"
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +000042#include <map>
Anders Carlssona4267a62009-07-18 21:19:52 +000043
Chris Lattnerddc135e2006-11-10 06:34:16 +000044using namespace clang;
45
Douglas Gregor9672f922010-07-03 00:47:00 +000046unsigned ASTContext::NumImplicitDefaultConstructors;
47unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000048unsigned ASTContext::NumImplicitCopyConstructors;
49unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000050unsigned ASTContext::NumImplicitMoveConstructors;
51unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +000052unsigned ASTContext::NumImplicitCopyAssignmentOperators;
53unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000054unsigned ASTContext::NumImplicitMoveAssignmentOperators;
55unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +000056unsigned ASTContext::NumImplicitDestructors;
57unsigned ASTContext::NumImplicitDestructorsDeclared;
58
Steve Naroff0af91202007-04-27 21:51:21 +000059enum FloatingRank {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +000060 HalfRank, FloatRank, DoubleRank, LongDoubleRank
Steve Naroff0af91202007-04-27 21:51:21 +000061};
62
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000063RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000064 if (!CommentsLoaded && ExternalSource) {
65 ExternalSource->ReadComments();
66 CommentsLoaded = true;
67 }
68
69 assert(D);
70
Dmitri Gribenkodf17d642012-06-28 16:19:39 +000071 // User can not attach documentation to implicit declarations.
72 if (D->isImplicit())
73 return NULL;
74
Dmitri Gribenkob2610882012-08-14 17:17:18 +000075 // User can not attach documentation to implicit instantiations.
76 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
77 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
78 return NULL;
79 }
80
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000081 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
82 if (VD->isStaticDataMember() &&
83 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
84 return NULL;
85 }
86
87 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
88 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
89 return NULL;
90 }
91
Dmitri Gribenko01b06512013-01-27 21:18:39 +000092 if (const ClassTemplateSpecializationDecl *CTSD =
93 dyn_cast<ClassTemplateSpecializationDecl>(D)) {
94 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
95 if (TSK == TSK_ImplicitInstantiation ||
96 TSK == TSK_Undeclared)
97 return NULL;
98 }
99
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000100 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
101 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
102 return NULL;
103 }
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000104 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
105 // When tag declaration (but not definition!) is part of the
106 // decl-specifier-seq of some other declaration, it doesn't get comment
107 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
108 return NULL;
109 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000110 // TODO: handle comments for function parameters properly.
111 if (isa<ParmVarDecl>(D))
112 return NULL;
113
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000114 // TODO: we could look up template parameter documentation in the template
115 // documentation.
116 if (isa<TemplateTypeParmDecl>(D) ||
117 isa<NonTypeTemplateParmDecl>(D) ||
118 isa<TemplateTemplateParmDecl>(D))
119 return NULL;
120
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000121 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000122
123 // If there are no comments anywhere, we won't find anything.
124 if (RawComments.empty())
125 return NULL;
126
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000127 // Find declaration location.
128 // For Objective-C declarations we generally don't expect to have multiple
129 // declarators, thus use declaration starting location as the "declaration
130 // location".
131 // For all other declarations multiple declarators are used quite frequently,
132 // so we use the location of the identifier as the "declaration location".
133 SourceLocation DeclLoc;
134 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000135 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +0000136 isa<RedeclarableTemplateDecl>(D) ||
137 isa<ClassTemplateSpecializationDecl>(D))
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000138 DeclLoc = D->getLocStart();
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000139 else {
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000140 DeclLoc = D->getLocation();
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000141 // If location of the typedef name is in a macro, it is because being
142 // declared via a macro. Try using declaration's starting location
143 // as the "declaration location".
144 if (DeclLoc.isMacroID() && isa<TypedefDecl>(D))
145 DeclLoc = D->getLocStart();
146 }
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000147
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000148 // If the declaration doesn't map directly to a location in a file, we
149 // can't find the comment.
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000150 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
151 return NULL;
152
153 // Find the comment that occurs just after this declaration.
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000154 ArrayRef<RawComment *>::iterator Comment;
155 {
156 // When searching for comments during parsing, the comment we are looking
157 // for is usually among the last two comments we parsed -- check them
158 // first.
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +0000159 RawComment CommentAtDeclLoc(
160 SourceMgr, SourceRange(DeclLoc), false,
161 LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000162 BeforeThanCompare<RawComment> Compare(SourceMgr);
163 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
164 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
165 if (!Found && RawComments.size() >= 2) {
166 MaybeBeforeDecl--;
167 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
168 }
169
170 if (Found) {
171 Comment = MaybeBeforeDecl + 1;
172 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
173 &CommentAtDeclLoc, Compare));
174 } else {
175 // Slow path.
176 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
177 &CommentAtDeclLoc, Compare);
178 }
179 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000180
181 // Decompose the location for the declaration and find the beginning of the
182 // file buffer.
183 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
184
185 // First check whether we have a trailing comment.
186 if (Comment != RawComments.end() &&
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000187 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
Fariborz Jahanianfad28542013-08-06 23:29:00 +0000188 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
Fariborz Jahanian3ab62222013-08-07 16:40:29 +0000189 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000190 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000191 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000192 // Check that Doxygen trailing comment comes after the declaration, starts
193 // on the same line and in the same file as the declaration.
194 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
195 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
196 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
197 CommentBeginDecomp.second)) {
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000198 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000199 }
200 }
201
202 // The comment just after the declaration was not a trailing comment.
203 // Let's look at the previous comment.
204 if (Comment == RawComments.begin())
205 return NULL;
206 --Comment;
207
208 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000209 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000210 return NULL;
211
212 // Decompose the end of the comment.
213 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000214 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000215
216 // If the comment and the declaration aren't in the same file, then they
217 // aren't related.
218 if (DeclLocDecomp.first != CommentEndDecomp.first)
219 return NULL;
220
221 // Get the corresponding buffer.
222 bool Invalid = false;
223 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
224 &Invalid).data();
225 if (Invalid)
226 return NULL;
227
228 // Extract text between the comment and declaration.
229 StringRef Text(Buffer + CommentEndDecomp.second,
230 DeclLocDecomp.second - CommentEndDecomp.second);
231
Dmitri Gribenko7e8729b2012-06-27 23:43:37 +0000232 // There should be no other declarations or preprocessor directives between
233 // comment and declaration.
Argyrios Kyrtzidisb534d3a2013-07-26 18:38:12 +0000234 if (Text.find_first_of(";{}#@") != StringRef::npos)
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000235 return NULL;
236
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000237 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000238}
239
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000240namespace {
241/// If we have a 'templated' declaration for a template, adjust 'D' to
242/// refer to the actual template.
Dmitri Gribenko90631802012-08-22 17:44:32 +0000243/// If we have an implicit instantiation, adjust 'D' to refer to template.
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000244const Decl *adjustDeclToTemplate(const Decl *D) {
Douglas Gregor35ceb272012-08-13 16:37:30 +0000245 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000246 // Is this function declaration part of a function template?
Douglas Gregor35ceb272012-08-13 16:37:30 +0000247 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko90631802012-08-22 17:44:32 +0000248 return FTD;
249
250 // Nothing to do if function is not an implicit instantiation.
251 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
252 return D;
253
254 // Function is an implicit instantiation of a function template?
255 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
256 return FTD;
257
258 // Function is instantiated from a member definition of a class template?
259 if (const FunctionDecl *MemberDecl =
260 FD->getInstantiatedFromMemberFunction())
261 return MemberDecl;
262
263 return D;
Douglas Gregor35ceb272012-08-13 16:37:30 +0000264 }
Dmitri Gribenko90631802012-08-22 17:44:32 +0000265 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
266 // Static data member is instantiated from a member definition of a class
267 // template?
268 if (VD->isStaticDataMember())
269 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
270 return MemberDecl;
271
272 return D;
273 }
274 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
275 // Is this class declaration part of a class template?
276 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
277 return CTD;
278
279 // Class is an implicit instantiation of a class template or partial
280 // specialization?
281 if (const ClassTemplateSpecializationDecl *CTSD =
282 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
283 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
284 return D;
285 llvm::PointerUnion<ClassTemplateDecl *,
286 ClassTemplatePartialSpecializationDecl *>
287 PU = CTSD->getSpecializedTemplateOrPartial();
288 return PU.is<ClassTemplateDecl*>() ?
289 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
290 static_cast<const Decl*>(
291 PU.get<ClassTemplatePartialSpecializationDecl *>());
292 }
293
294 // Class is instantiated from a member definition of a class template?
295 if (const MemberSpecializationInfo *Info =
296 CRD->getMemberSpecializationInfo())
297 return Info->getInstantiatedFrom();
298
299 return D;
300 }
301 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
302 // Enum is instantiated from a member definition of a class template?
303 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
304 return MemberDecl;
305
306 return D;
307 }
308 // FIXME: Adjust alias templates?
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000309 return D;
310}
311} // unnamed namespace
312
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000313const RawComment *ASTContext::getRawCommentForAnyRedecl(
314 const Decl *D,
315 const Decl **OriginalDecl) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000316 D = adjustDeclToTemplate(D);
Douglas Gregor35ceb272012-08-13 16:37:30 +0000317
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000318 // Check whether we have cached a comment for this declaration already.
319 {
320 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
321 RedeclComments.find(D);
322 if (Pos != RedeclComments.end()) {
323 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000324 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
325 if (OriginalDecl)
326 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000327 return Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000328 }
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000329 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000330 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000331
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000332 // Search for comments attached to declarations in the redeclaration chain.
333 const RawComment *RC = NULL;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000334 const Decl *OriginalDeclForRC = NULL;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000335 for (Decl::redecl_iterator I = D->redecls_begin(),
336 E = D->redecls_end();
337 I != E; ++I) {
338 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
339 RedeclComments.find(*I);
340 if (Pos != RedeclComments.end()) {
341 const RawCommentAndCacheFlags &Raw = Pos->second;
342 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
343 RC = Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000344 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000345 break;
346 }
347 } else {
348 RC = getRawCommentForDeclNoCache(*I);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000349 OriginalDeclForRC = *I;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000350 RawCommentAndCacheFlags Raw;
351 if (RC) {
352 Raw.setRaw(RC);
353 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
354 } else
355 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000356 Raw.setOriginalDecl(*I);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000357 RedeclComments[*I] = Raw;
358 if (RC)
359 break;
360 }
361 }
362
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000363 // If we found a comment, it should be a documentation comment.
364 assert(!RC || RC->isDocumentation());
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000365
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000366 if (OriginalDecl)
367 *OriginalDecl = OriginalDeclForRC;
368
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000369 // Update cache for every declaration in the redeclaration chain.
370 RawCommentAndCacheFlags Raw;
371 Raw.setRaw(RC);
372 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000373 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000374
375 for (Decl::redecl_iterator I = D->redecls_begin(),
376 E = D->redecls_end();
377 I != E; ++I) {
378 RawCommentAndCacheFlags &R = RedeclComments[*I];
379 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
380 R = Raw;
381 }
382
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000383 return RC;
384}
385
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000386static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
387 SmallVectorImpl<const NamedDecl *> &Redeclared) {
388 const DeclContext *DC = ObjCMethod->getDeclContext();
389 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
390 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
391 if (!ID)
392 return;
393 // Add redeclared method here.
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000394 for (ObjCInterfaceDecl::known_extensions_iterator
395 Ext = ID->known_extensions_begin(),
396 ExtEnd = ID->known_extensions_end();
397 Ext != ExtEnd; ++Ext) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000398 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000399 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000400 ObjCMethod->isInstanceMethod()))
401 Redeclared.push_back(RedeclaredMethod);
402 }
403 }
404}
405
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000406comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
407 const Decl *D) const {
408 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
409 ThisDeclInfo->CommentDecl = D;
410 ThisDeclInfo->IsFilled = false;
411 ThisDeclInfo->fill();
412 ThisDeclInfo->CommentDecl = FC->getDecl();
413 comments::FullComment *CFC =
414 new (*this) comments::FullComment(FC->getBlocks(),
415 ThisDeclInfo);
416 return CFC;
417
418}
419
Richard Smithb39b9d52013-05-21 05:24:00 +0000420comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
421 const RawComment *RC = getRawCommentForDeclNoCache(D);
422 return RC ? RC->parse(*this, 0, D) : 0;
423}
424
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000425comments::FullComment *ASTContext::getCommentForDecl(
426 const Decl *D,
427 const Preprocessor *PP) const {
Fariborz Jahanian096f7c12013-05-13 17:27:00 +0000428 if (D->isInvalidDecl())
429 return NULL;
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000430 D = adjustDeclToTemplate(D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000431
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000432 const Decl *Canonical = D->getCanonicalDecl();
433 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
434 ParsedComments.find(Canonical);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000435
436 if (Pos != ParsedComments.end()) {
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000437 if (Canonical != D) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000438 comments::FullComment *FC = Pos->second;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000439 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000440 return CFC;
441 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000442 return Pos->second;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000443 }
444
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000445 const Decl *OriginalDecl;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000446
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000447 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000448 if (!RC) {
449 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000450 SmallVector<const NamedDecl*, 8> Overridden;
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000451 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000452 if (OMD && OMD->isPropertyAccessor())
453 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
454 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
455 return cloneFullComment(FC, D);
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000456 if (OMD)
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000457 addRedeclaredMethods(OMD, Overridden);
458 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000459 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
460 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
461 return cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000462 }
Fariborz Jahanian6384fbb2013-05-02 15:44:16 +0000463 else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000464 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000465 // does not have one of its own.
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000466 QualType QT = TD->getUnderlyingType();
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000467 if (const TagType *TT = QT->getAs<TagType>())
468 if (const Decl *TD = TT->getDecl())
469 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000470 return cloneFullComment(FC, D);
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000471 }
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000472 else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
473 while (IC->getSuperClass()) {
474 IC = IC->getSuperClass();
475 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
476 return cloneFullComment(FC, D);
477 }
478 }
479 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
480 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
481 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
482 return cloneFullComment(FC, D);
483 }
484 else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
485 if (!(RD = RD->getDefinition()))
486 return NULL;
487 // Check non-virtual bases.
488 for (CXXRecordDecl::base_class_const_iterator I =
489 RD->bases_begin(), E = RD->bases_end(); I != E; ++I) {
Fariborz Jahanian5a2e4a22013-04-26 23:34:36 +0000490 if (I->isVirtual() || (I->getAccessSpecifier() != AS_public))
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000491 continue;
492 QualType Ty = I->getType();
493 if (Ty.isNull())
494 continue;
495 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
496 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
497 continue;
498
499 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
500 return cloneFullComment(FC, D);
501 }
502 }
503 // Check virtual bases.
504 for (CXXRecordDecl::base_class_const_iterator I =
505 RD->vbases_begin(), E = RD->vbases_end(); I != E; ++I) {
Fariborz Jahanian5a2e4a22013-04-26 23:34:36 +0000506 if (I->getAccessSpecifier() != AS_public)
507 continue;
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000508 QualType Ty = I->getType();
509 if (Ty.isNull())
510 continue;
511 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
512 if (!(VirtualBase= VirtualBase->getDefinition()))
513 continue;
514 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
515 return cloneFullComment(FC, D);
516 }
517 }
518 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000519 return NULL;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000520 }
521
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000522 // If the RawComment was attached to other redeclaration of this Decl, we
523 // should parse the comment in context of that other Decl. This is important
524 // because comments can contain references to parameter names which can be
525 // different across redeclarations.
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000526 if (D != OriginalDecl)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000527 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000528
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000529 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000530 ParsedComments[Canonical] = FC;
531 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000532}
533
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000534void
535ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
536 TemplateTemplateParmDecl *Parm) {
537 ID.AddInteger(Parm->getDepth());
538 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000539 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000540
541 TemplateParameterList *Params = Parm->getTemplateParameters();
542 ID.AddInteger(Params->size());
543 for (TemplateParameterList::const_iterator P = Params->begin(),
544 PEnd = Params->end();
545 P != PEnd; ++P) {
546 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
547 ID.AddInteger(0);
548 ID.AddBoolean(TTP->isParameterPack());
549 continue;
550 }
551
552 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
553 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000554 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000555 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000556 if (NTTP->isExpandedParameterPack()) {
557 ID.AddBoolean(true);
558 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000559 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
560 QualType T = NTTP->getExpansionType(I);
561 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
562 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000563 } else
564 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000565 continue;
566 }
567
568 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
569 ID.AddInteger(2);
570 Profile(ID, TTP);
571 }
572}
573
574TemplateTemplateParmDecl *
575ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000576 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000577 // Check if we already have a canonical template template parameter.
578 llvm::FoldingSetNodeID ID;
579 CanonicalTemplateTemplateParm::Profile(ID, TTP);
580 void *InsertPos = 0;
581 CanonicalTemplateTemplateParm *Canonical
582 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
583 if (Canonical)
584 return Canonical->getParam();
585
586 // Build a canonical template parameter list.
587 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000588 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000589 CanonParams.reserve(Params->size());
590 for (TemplateParameterList::const_iterator P = Params->begin(),
591 PEnd = Params->end();
592 P != PEnd; ++P) {
593 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
594 CanonParams.push_back(
595 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000596 SourceLocation(),
597 SourceLocation(),
598 TTP->getDepth(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000599 TTP->getIndex(), 0, false,
600 TTP->isParameterPack()));
601 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000602 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
603 QualType T = getCanonicalType(NTTP->getType());
604 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
605 NonTypeTemplateParmDecl *Param;
606 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000607 SmallVector<QualType, 2> ExpandedTypes;
608 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000609 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
610 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
611 ExpandedTInfos.push_back(
612 getTrivialTypeSourceInfo(ExpandedTypes.back()));
613 }
614
615 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000616 SourceLocation(),
617 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000618 NTTP->getDepth(),
619 NTTP->getPosition(), 0,
620 T,
621 TInfo,
622 ExpandedTypes.data(),
623 ExpandedTypes.size(),
624 ExpandedTInfos.data());
625 } else {
626 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000627 SourceLocation(),
628 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000629 NTTP->getDepth(),
630 NTTP->getPosition(), 0,
631 T,
632 NTTP->isParameterPack(),
633 TInfo);
634 }
635 CanonParams.push_back(Param);
636
637 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000638 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
639 cast<TemplateTemplateParmDecl>(*P)));
640 }
641
642 TemplateTemplateParmDecl *CanonTTP
643 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
644 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000645 TTP->getPosition(),
646 TTP->isParameterPack(),
647 0,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000648 TemplateParameterList::Create(*this, SourceLocation(),
649 SourceLocation(),
650 CanonParams.data(),
651 CanonParams.size(),
652 SourceLocation()));
653
654 // Get the new insert position for the node we care about.
655 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
656 assert(Canonical == 0 && "Shouldn't be in the map!");
657 (void)Canonical;
658
659 // Create the canonical template template parameter entry.
660 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
661 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
662 return CanonTTP;
663}
664
Charles Davis53c59df2010-08-16 03:33:14 +0000665CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000666 if (!LangOpts.CPlusPlus) return 0;
667
John McCall359b8852013-01-25 22:30:49 +0000668 switch (T.getCXXABI().getKind()) {
669 case TargetCXXABI::GenericARM:
670 case TargetCXXABI::iOS:
John McCall86353412010-08-21 22:46:04 +0000671 return CreateARMCXXABI(*this);
Tim Northover9bb857a2013-01-31 12:13:10 +0000672 case TargetCXXABI::GenericAArch64: // Same as Itanium at this level
John McCall359b8852013-01-25 22:30:49 +0000673 case TargetCXXABI::GenericItanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000674 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000675 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000676 return CreateMicrosoftCXXABI(*this);
677 }
David Blaikie8a40f702012-01-17 06:56:22 +0000678 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000679}
680
Douglas Gregore8bbc122011-09-02 00:18:52 +0000681static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000682 const LangOptions &LOpts) {
683 if (LOpts.FakeAddressSpaceMap) {
684 // The fake address space map must have a distinct entry for each
685 // language-specific address space.
686 static const unsigned FakeAddrSpaceMap[] = {
687 1, // opencl_global
688 2, // opencl_local
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000689 3, // opencl_constant
690 4, // cuda_device
691 5, // cuda_constant
692 6 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000693 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000694 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000695 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000696 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000697 }
698}
699
David Tweed31d09b02013-09-13 12:04:22 +0000700static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
701 const LangOptions &LangOpts) {
702 switch (LangOpts.getAddressSpaceMapMangling()) {
David Tweed31d09b02013-09-13 12:04:22 +0000703 case LangOptions::ASMM_Target:
704 return TI.useAddressSpaceMapMangling();
705 case LangOptions::ASMM_On:
706 return true;
707 case LangOptions::ASMM_Off:
708 return false;
709 }
NAKAMURA Takumi5c81ca42013-09-13 17:12:09 +0000710 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
David Tweed31d09b02013-09-13 12:04:22 +0000711}
712
Douglas Gregor7018d5b2011-09-01 20:23:19 +0000713ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000714 const TargetInfo *t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000715 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000716 Builtin::Context &builtins,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000717 unsigned size_reserve,
718 bool DelayInitialization)
719 : FunctionProtoTypes(this_()),
720 TemplateSpecializationTypes(this_()),
721 DependentTemplateSpecializationTypes(this_()),
722 SubstTemplateTemplateParmPacks(this_()),
723 GlobalNestedNameSpecifier(0),
Nico Webere1687c52013-06-20 21:44:55 +0000724 Int128Decl(0), UInt128Decl(0), Float128StubDecl(0),
Meador Inge5d3fb222012-06-16 03:34:49 +0000725 BuiltinVaListDecl(0),
Douglas Gregord53ae832012-01-17 18:09:05 +0000726 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Fariborz Jahanianf2578572012-08-30 18:49:41 +0000727 BOOLDecl(0),
Douglas Gregorbab8a962011-09-08 01:46:34 +0000728 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000729 FILEDecl(0),
Rafael Espindola6cfa82b2011-11-13 21:51:09 +0000730 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
731 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
732 cudaConfigureCallDecl(0),
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000733 NullTypeSourceInfo(QualType()),
734 FirstLocalImport(), LastLocalImport(),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000735 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000736 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000737 Idents(idents), Selectors(sels),
738 BuiltinInfo(builtins),
739 DeclarationNames(*this),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000740 ExternalSource(0), Listener(0),
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000741 Comments(SM), CommentsLoaded(false),
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000742 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
Rafael Espindolace2168f2013-05-29 19:51:12 +0000743 LastSDM(0, 0)
Douglas Gregore8bbc122011-09-02 00:18:52 +0000744{
Mike Stump11289f42009-09-09 15:08:12 +0000745 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000746 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000747
748 if (!DelayInitialization) {
749 assert(t && "No target supplied for ASTContext initialization");
750 InitBuiltinTypes(*t);
751 }
Daniel Dunbar221fa942008-08-11 04:54:23 +0000752}
753
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000754ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000755 // Release the DenseMaps associated with DeclContext objects.
756 // FIXME: Is this the ideal solution?
757 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000758
Manuel Klimeka7328992013-06-03 13:51:33 +0000759 // Call all of the deallocation functions on all of their targets.
760 for (DeallocationMap::const_iterator I = Deallocations.begin(),
761 E = Deallocations.end(); I != E; ++I)
762 for (unsigned J = 0, N = I->second.size(); J != N; ++J)
763 (I->first)((I->second)[J]);
764
Ted Kremenek076baeb2010-06-08 23:00:58 +0000765 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000766 // because they can contain DenseMaps.
767 for (llvm::DenseMap<const ObjCContainerDecl*,
768 const ASTRecordLayout*>::iterator
769 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
770 // Increment in loop to prevent using deallocated memory.
771 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
772 R->Destroy(*this);
773
Ted Kremenek076baeb2010-06-08 23:00:58 +0000774 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
775 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
776 // Increment in loop to prevent using deallocated memory.
777 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
778 R->Destroy(*this);
779 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000780
781 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
782 AEnd = DeclAttrs.end();
783 A != AEnd; ++A)
784 A->second->~AttrVec();
Reid Klecknerd8110b62013-09-10 20:14:30 +0000785
Reid Kleckner588c9372014-02-19 23:44:52 +0000786 llvm::DeleteContainerSeconds(MangleNumberingContexts);
Douglas Gregor561eceb2010-08-30 16:49:28 +0000787}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000788
Douglas Gregor1a809332010-05-23 18:26:36 +0000789void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Manuel Klimeka7328992013-06-03 13:51:33 +0000790 Deallocations[Callback].push_back(Data);
Douglas Gregor1a809332010-05-23 18:26:36 +0000791}
792
Mike Stump11289f42009-09-09 15:08:12 +0000793void
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000794ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
795 ExternalSource = Source;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000796}
797
Chris Lattner4eb445d2007-01-26 01:27:23 +0000798void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000799 llvm::errs() << "\n*** AST Context Stats:\n";
800 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000801
Douglas Gregora30d0462009-05-26 14:40:08 +0000802 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000803#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000804#define ABSTRACT_TYPE(Name, Parent)
805#include "clang/AST/TypeNodes.def"
806 0 // Extra
807 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000808
Chris Lattner4eb445d2007-01-26 01:27:23 +0000809 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
810 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000811 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000812 }
813
Douglas Gregora30d0462009-05-26 14:40:08 +0000814 unsigned Idx = 0;
815 unsigned TotalBytes = 0;
816#define TYPE(Name, Parent) \
817 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000818 llvm::errs() << " " << counts[Idx] << " " << #Name \
819 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000820 TotalBytes += counts[Idx] * sizeof(Name##Type); \
821 ++Idx;
822#define ABSTRACT_TYPE(Name, Parent)
823#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000824
Chandler Carruth3c147a72011-07-04 05:32:14 +0000825 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
826
Douglas Gregor7454c562010-07-02 20:37:36 +0000827 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000828 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
829 << NumImplicitDefaultConstructors
830 << " implicit default constructors created\n";
831 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
832 << NumImplicitCopyConstructors
833 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000834 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000835 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
836 << NumImplicitMoveConstructors
837 << " implicit move constructors created\n";
838 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
839 << NumImplicitCopyAssignmentOperators
840 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000841 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000842 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
843 << NumImplicitMoveAssignmentOperators
844 << " implicit move assignment operators created\n";
845 llvm::errs() << NumImplicitDestructorsDeclared << "/"
846 << NumImplicitDestructors
847 << " implicit destructors created\n";
848
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000849 if (ExternalSource) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000850 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000851 ExternalSource->PrintStats();
852 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000853
Douglas Gregor5b11d492010-07-25 17:53:33 +0000854 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000855}
856
Alp Toker2dea15b2013-12-17 01:22:38 +0000857RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
858 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000859 SourceLocation Loc;
860 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +0000861 if (getLangOpts().CPlusPlus)
862 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
863 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000864 else
Alp Toker2dea15b2013-12-17 01:22:38 +0000865 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
866 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +0000867 NewDecl->setImplicit();
868 return NewDecl;
869}
870
871TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
872 StringRef Name) const {
873 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
874 TypedefDecl *NewDecl = TypedefDecl::Create(
875 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
876 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
877 NewDecl->setImplicit();
878 return NewDecl;
879}
880
Douglas Gregor801c99d2011-08-12 06:49:56 +0000881TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000882 if (!Int128Decl)
883 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000884 return Int128Decl;
885}
886
887TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +0000888 if (!UInt128Decl)
889 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +0000890 return UInt128Decl;
891}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000892
Nico Webere1687c52013-06-20 21:44:55 +0000893TypeDecl *ASTContext::getFloat128StubType() const {
Nico Weber5b0b46f2013-06-21 01:29:36 +0000894 assert(LangOpts.CPlusPlus && "should only be called for c++");
Alp Toker56b5cc92013-12-15 10:36:26 +0000895 if (!Float128StubDecl)
Alp Toker2dea15b2013-12-17 01:22:38 +0000896 Float128StubDecl = buildImplicitRecord("__float128");
Alp Toker56b5cc92013-12-15 10:36:26 +0000897
Nico Webere1687c52013-06-20 21:44:55 +0000898 return Float128StubDecl;
899}
900
John McCall48f2d582009-10-23 23:03:21 +0000901void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000902 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000903 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000904 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000905}
906
Douglas Gregore8bbc122011-09-02 00:18:52 +0000907void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
908 assert((!this->Target || this->Target == &Target) &&
909 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000910 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000911
Douglas Gregore8bbc122011-09-02 00:18:52 +0000912 this->Target = &Target;
913
914 ABI.reset(createCXXABI(Target));
915 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +0000916 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000917
Chris Lattner970e54e2006-11-12 00:37:36 +0000918 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000919 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000920
Chris Lattner970e54e2006-11-12 00:37:36 +0000921 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000922 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000923 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000924 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000925 InitBuiltinType(CharTy, BuiltinType::Char_S);
926 else
927 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000928 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000929 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
930 InitBuiltinType(ShortTy, BuiltinType::Short);
931 InitBuiltinType(IntTy, BuiltinType::Int);
932 InitBuiltinType(LongTy, BuiltinType::Long);
933 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000934
Chris Lattner970e54e2006-11-12 00:37:36 +0000935 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000936 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
937 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
938 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
939 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
940 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000941
Chris Lattner970e54e2006-11-12 00:37:36 +0000942 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000943 InitBuiltinType(FloatTy, BuiltinType::Float);
944 InitBuiltinType(DoubleTy, BuiltinType::Double);
945 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000946
Chris Lattnerf122cef2009-04-30 02:43:43 +0000947 // GNU extension, 128-bit integers.
948 InitBuiltinType(Int128Ty, BuiltinType::Int128);
949 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
950
Hans Wennborg0d81e012013-05-10 10:08:40 +0000951 // C++ 3.9.1p5
952 if (TargetInfo::isTypeSigned(Target.getWCharType()))
953 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
954 else // -fshort-wchar makes wchar_t be unsigned.
955 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
956 if (LangOpts.CPlusPlus && LangOpts.WChar)
957 WideCharTy = WCharTy;
958 else {
959 // C99 (or C++ using -fno-wchar).
960 WideCharTy = getFromTargetType(Target.getWCharType());
961 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000962
James Molloy36365542012-05-04 10:55:22 +0000963 WIntTy = getFromTargetType(Target.getWIntType());
964
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000965 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
966 InitBuiltinType(Char16Ty, BuiltinType::Char16);
967 else // C99
968 Char16Ty = getFromTargetType(Target.getChar16Type());
969
970 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
971 InitBuiltinType(Char32Ty, BuiltinType::Char32);
972 else // C99
973 Char32Ty = getFromTargetType(Target.getChar32Type());
974
Douglas Gregor4619e432008-12-05 23:32:09 +0000975 // Placeholder type for type-dependent expressions whose type is
976 // completely unknown. No code should ever check a type against
977 // DependentTy and users should never see it; however, it is here to
978 // help diagnose failures to properly check for type-dependent
979 // expressions.
980 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000981
John McCall36e7fe32010-10-12 00:20:44 +0000982 // Placeholder type for functions.
983 InitBuiltinType(OverloadTy, BuiltinType::Overload);
984
John McCall0009fcc2011-04-26 20:42:42 +0000985 // Placeholder type for bound members.
986 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
987
John McCall526ab472011-10-25 17:37:35 +0000988 // Placeholder type for pseudo-objects.
989 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
990
John McCall31996342011-04-07 08:22:57 +0000991 // "any" type; useful for debugger-like clients.
992 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
993
John McCall8a6b59a2011-10-17 18:09:15 +0000994 // Placeholder type for unbridged ARC casts.
995 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
996
Eli Friedman34866c72012-08-31 00:14:07 +0000997 // Placeholder type for builtin functions.
998 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
999
Chris Lattner970e54e2006-11-12 00:37:36 +00001000 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +00001001 FloatComplexTy = getComplexType(FloatTy);
1002 DoubleComplexTy = getComplexType(DoubleTy);
1003 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001004
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001005 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001006 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1007 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001008 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001009
1010 if (LangOpts.OpenCL) {
1011 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
1012 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
1013 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
1014 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
1015 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
1016 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001017
Guy Benyei61054192013-02-07 10:55:47 +00001018 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001019 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001020 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001021
1022 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001023 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1024 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001025
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001026 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001027
1028 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001029
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001030 // void * type
1031 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +00001032
1033 // nullptr type (C++0x 2.14.7)
1034 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001035
1036 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1037 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001038
1039 // Builtin type used to help define __builtin_va_list.
1040 VaListTagTy = QualType();
Chris Lattner970e54e2006-11-12 00:37:36 +00001041}
1042
David Blaikie9c902b52011-09-25 23:23:43 +00001043DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001044 return SourceMgr.getDiagnostics();
1045}
1046
Douglas Gregor561eceb2010-08-30 16:49:28 +00001047AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1048 AttrVec *&Result = DeclAttrs[D];
1049 if (!Result) {
1050 void *Mem = Allocate(sizeof(AttrVec));
1051 Result = new (Mem) AttrVec;
1052 }
1053
1054 return *Result;
1055}
1056
1057/// \brief Erase the attributes corresponding to the given declaration.
1058void ASTContext::eraseDeclAttrs(const Decl *D) {
1059 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1060 if (Pos != DeclAttrs.end()) {
1061 Pos->second->~AttrVec();
1062 DeclAttrs.erase(Pos);
1063 }
1064}
1065
Larisse Voufo39a1e502013-08-06 01:03:05 +00001066// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001067MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001068ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001069 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001070 return getTemplateOrSpecializationInfo(Var)
1071 .dyn_cast<MemberSpecializationInfo *>();
1072}
1073
1074ASTContext::TemplateOrSpecializationInfo
1075ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1076 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1077 TemplateOrInstantiation.find(Var);
1078 if (Pos == TemplateOrInstantiation.end())
1079 return TemplateOrSpecializationInfo();
Mike Stump11289f42009-09-09 15:08:12 +00001080
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001081 return Pos->second;
1082}
1083
Mike Stump11289f42009-09-09 15:08:12 +00001084void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001085ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001086 TemplateSpecializationKind TSK,
1087 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001088 assert(Inst->isStaticDataMember() && "Not a static data member");
1089 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001090 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1091 Tmpl, TSK, PointOfInstantiation));
1092}
1093
1094void
1095ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1096 TemplateOrSpecializationInfo TSI) {
1097 assert(!TemplateOrInstantiation[Inst] &&
1098 "Already noted what the variable was instantiated from");
1099 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001100}
1101
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001102FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1103 const FunctionDecl *FD){
1104 assert(FD && "Specialization is 0");
1105 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001106 = ClassScopeSpecializationPattern.find(FD);
1107 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001108 return 0;
1109
1110 return Pos->second;
1111}
1112
1113void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1114 FunctionDecl *Pattern) {
1115 assert(FD && "Specialization is 0");
1116 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001117 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001118}
1119
John McCalle61f2ba2009-11-18 02:36:19 +00001120NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +00001121ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +00001122 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +00001123 = InstantiatedFromUsingDecl.find(UUD);
1124 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001125 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001126
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001127 return Pos->second;
1128}
1129
1130void
John McCallb96ec562009-12-04 22:46:56 +00001131ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1132 assert((isa<UsingDecl>(Pattern) ||
1133 isa<UnresolvedUsingValueDecl>(Pattern) ||
1134 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1135 "pattern decl is not a using decl");
1136 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1137 InstantiatedFromUsingDecl[Inst] = Pattern;
1138}
1139
1140UsingShadowDecl *
1141ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1142 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1143 = InstantiatedFromUsingShadowDecl.find(Inst);
1144 if (Pos == InstantiatedFromUsingShadowDecl.end())
1145 return 0;
1146
1147 return Pos->second;
1148}
1149
1150void
1151ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1152 UsingShadowDecl *Pattern) {
1153 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1154 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001155}
1156
Anders Carlsson5da84842009-09-01 04:26:58 +00001157FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1158 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1159 = InstantiatedFromUnnamedFieldDecl.find(Field);
1160 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1161 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001162
Anders Carlsson5da84842009-09-01 04:26:58 +00001163 return Pos->second;
1164}
1165
1166void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1167 FieldDecl *Tmpl) {
1168 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1169 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1170 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1171 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001172
Anders Carlsson5da84842009-09-01 04:26:58 +00001173 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1174}
1175
Douglas Gregor832940b2010-03-02 23:58:15 +00001176ASTContext::overridden_cxx_method_iterator
1177ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1178 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001179 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001180 if (Pos == OverriddenMethods.end())
1181 return 0;
1182
1183 return Pos->second.begin();
1184}
1185
1186ASTContext::overridden_cxx_method_iterator
1187ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1188 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001189 = OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001190 if (Pos == OverriddenMethods.end())
1191 return 0;
1192
1193 return Pos->second.end();
1194}
1195
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001196unsigned
1197ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1198 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001199 = OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001200 if (Pos == OverriddenMethods.end())
1201 return 0;
1202
1203 return Pos->second.size();
1204}
1205
Douglas Gregor832940b2010-03-02 23:58:15 +00001206void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1207 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001208 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001209 OverriddenMethods[Method].push_back(Overridden);
1210}
1211
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001212void ASTContext::getOverriddenMethods(
1213 const NamedDecl *D,
1214 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001215 assert(D);
1216
1217 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001218 Overridden.append(overridden_methods_begin(CXXMethod),
1219 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001220 return;
1221 }
1222
1223 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1224 if (!Method)
1225 return;
1226
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001227 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1228 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001229 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001230}
1231
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001232void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1233 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1234 assert(!Import->isFromASTFile() && "Non-local import declaration");
1235 if (!FirstLocalImport) {
1236 FirstLocalImport = Import;
1237 LastLocalImport = Import;
1238 return;
1239 }
1240
1241 LastLocalImport->NextLocalImport = Import;
1242 LastLocalImport = Import;
1243}
1244
Chris Lattner53cfe802007-07-18 17:52:12 +00001245//===----------------------------------------------------------------------===//
1246// Type Sizing and Analysis
1247//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001248
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001249/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1250/// scalar floating point type.
1251const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001252 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001253 assert(BT && "Not a floating point type!");
1254 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001255 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001256 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001257 case BuiltinType::Float: return Target->getFloatFormat();
1258 case BuiltinType::Double: return Target->getDoubleFormat();
1259 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001260 }
1261}
1262
Rafael Espindola71eccb32013-08-08 19:53:46 +00001263CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001264 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001265
John McCall94268702010-10-08 18:24:19 +00001266 bool UseAlignAttrOnly = false;
1267 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1268 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001269
John McCall94268702010-10-08 18:24:19 +00001270 // __attribute__((aligned)) can increase or decrease alignment
1271 // *except* on a struct or struct member, where it only increases
1272 // alignment unless 'packed' is also specified.
1273 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001274 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001275 // ignore that possibility; Sema should diagnose it.
1276 if (isa<FieldDecl>(D)) {
1277 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1278 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1279 } else {
1280 UseAlignAttrOnly = true;
1281 }
1282 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001283 else if (isa<FieldDecl>(D))
1284 UseAlignAttrOnly =
1285 D->hasAttr<PackedAttr>() ||
1286 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001287
John McCall4e819612011-01-20 07:57:12 +00001288 // If we're using the align attribute only, just ignore everything
1289 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001290 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001291 // do nothing
1292
John McCall94268702010-10-08 18:24:19 +00001293 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001294 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001295 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001296 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001297 T = RT->getPointeeType();
1298 else
1299 T = getPointerType(RT->getPointeeType());
1300 }
1301 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +00001302 // Adjust alignments of declarations with array type by the
1303 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001304 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001305 unsigned MinWidth = Target->getLargeArrayMinWidth();
1306 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001307 if (isa<VariableArrayType>(arrayType))
1308 Align = std::max(Align, Target->getLargeArrayAlign());
1309 else if (isa<ConstantArrayType>(arrayType) &&
1310 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1311 Align = std::max(Align, Target->getLargeArrayAlign());
1312 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001313
John McCall33ddac02011-01-19 10:06:00 +00001314 // Walk through any array types while we're at it.
1315 T = getBaseElementType(arrayType);
1316 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001317 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Ulrich Weigandfa806422013-05-06 16:23:57 +00001318 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1319 if (VD->hasGlobalStorage())
1320 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1321 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001322 }
John McCall4e819612011-01-20 07:57:12 +00001323
1324 // Fields can be subject to extra alignment constraints, like if
1325 // the field is packed, the struct is packed, or the struct has a
1326 // a max-field-alignment constraint (#pragma pack). So calculate
1327 // the actual alignment of the field within the struct, and then
1328 // (as we're expected to) constrain that by the alignment of the type.
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001329 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1330 const RecordDecl *Parent = Field->getParent();
1331 // We can only produce a sensible answer if the record is valid.
1332 if (!Parent->isInvalidDecl()) {
1333 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001334
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001335 // Start with the record's overall alignment.
1336 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001337
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001338 // Use the GCD of that and the offset within the record.
1339 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1340 if (Offset > 0) {
1341 // Alignment is always a power of 2, so the GCD will be a power of 2,
1342 // which means we get to do this crazy thing instead of Euclid's.
1343 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1344 if (LowBitOfOffset < FieldAlign)
1345 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1346 }
1347
1348 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001349 }
Charles Davis3fc51072010-02-23 04:52:00 +00001350 }
Chris Lattner68061312009-01-24 21:53:27 +00001351 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001352
Ken Dyckcc56c542011-01-15 18:38:59 +00001353 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001354}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001355
John McCallf1249922012-08-21 04:10:00 +00001356// getTypeInfoDataSizeInChars - Return the size of a type, in
1357// chars. If the type is a record, its data size is returned. This is
1358// the size of the memcpy that's performed when assigning this type
1359// using a trivial copy/move assignment operator.
1360std::pair<CharUnits, CharUnits>
1361ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1362 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1363
1364 // In C++, objects can sometimes be allocated into the tail padding
1365 // of a base-class subobject. We decide whether that's possible
1366 // during class layout, so here we can just trust the layout results.
1367 if (getLangOpts().CPlusPlus) {
1368 if (const RecordType *RT = T->getAs<RecordType>()) {
1369 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1370 sizeAndAlign.first = layout.getDataSize();
1371 }
1372 }
1373
1374 return sizeAndAlign;
1375}
1376
Richard Trieu04d2d942013-05-14 21:59:17 +00001377/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1378/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1379std::pair<CharUnits, CharUnits>
1380static getConstantArrayInfoInChars(const ASTContext &Context,
1381 const ConstantArrayType *CAT) {
1382 std::pair<CharUnits, CharUnits> EltInfo =
1383 Context.getTypeInfoInChars(CAT->getElementType());
1384 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001385 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1386 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001387 "Overflow in array type char size evaluation");
1388 uint64_t Width = EltInfo.first.getQuantity() * Size;
1389 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001390 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1391 Context.getTargetInfo().getPointerWidth(0) == 64)
1392 Width = llvm::RoundUpToAlignment(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001393 return std::make_pair(CharUnits::fromQuantity(Width),
1394 CharUnits::fromQuantity(Align));
1395}
1396
John McCall87fe5d52010-05-20 01:18:31 +00001397std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001398ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001399 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1400 return getConstantArrayInfoInChars(*this, CAT);
John McCall87fe5d52010-05-20 01:18:31 +00001401 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +00001402 return std::make_pair(toCharUnitsFromBits(Info.first),
1403 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +00001404}
1405
1406std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001407ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001408 return getTypeInfoInChars(T.getTypePtr());
1409}
1410
Daniel Dunbarc6475872012-03-09 04:12:54 +00001411std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1412 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1413 if (it != MemoizedTypeInfo.end())
1414 return it->second;
1415
1416 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1417 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1418 return Info;
1419}
1420
1421/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1422/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001423///
1424/// FIXME: Pointers into different addr spaces could have different sizes and
1425/// alignment requirements: getPointerInfo should take an AddrSpace, this
1426/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +00001427std::pair<uint64_t, unsigned>
Daniel Dunbarc6475872012-03-09 04:12:54 +00001428ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +00001429 uint64_t Width=0;
1430 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001431 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001432#define TYPE(Class, Base)
1433#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001434#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001435#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001436#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1437 case Type::Class: \
1438 assert(!T->isDependentType() && "should not see dependent types here"); \
1439 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001440#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001441 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001442
Chris Lattner355332d2007-07-13 22:27:08 +00001443 case Type::FunctionNoProto:
1444 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001445 // GCC extension: alignof(function) = 32 bits
1446 Width = 0;
1447 Align = 32;
1448 break;
1449
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001450 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001451 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001452 Width = 0;
1453 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1454 break;
1455
Steve Naroff5c131802007-08-30 01:06:46 +00001456 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001457 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001458
Chris Lattner37e05872008-03-05 18:54:05 +00001459 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001460 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarc6475872012-03-09 04:12:54 +00001461 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1462 "Overflow in array type bit size evaluation");
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001463 Width = EltInfo.first*Size;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001464 Align = EltInfo.second;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001465 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1466 getTargetInfo().getPointerWidth(0) == 64)
1467 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001468 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001469 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001470 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001471 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001472 const VectorType *VT = cast<VectorType>(T);
1473 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1474 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001475 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001476 // If the alignment is not a power of 2, round up to the next power of 2.
1477 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001478 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001479 Align = llvm::NextPowerOf2(Align);
1480 Width = llvm::RoundUpToAlignment(Width, Align);
1481 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001482 // Adjust the alignment based on the target max.
1483 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1484 if (TargetVectorAlign && TargetVectorAlign < Align)
1485 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001486 break;
1487 }
Chris Lattner647fb222007-07-18 18:26:58 +00001488
Chris Lattner7570e9c2008-03-08 08:52:55 +00001489 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001490 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001491 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001492 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001493 // GCC extension: alignof(void) = 8 bits.
1494 Width = 0;
1495 Align = 8;
1496 break;
1497
Chris Lattner6a4f7452007-12-19 19:23:28 +00001498 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001499 Width = Target->getBoolWidth();
1500 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001501 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001502 case BuiltinType::Char_S:
1503 case BuiltinType::Char_U:
1504 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001505 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001506 Width = Target->getCharWidth();
1507 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001508 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001509 case BuiltinType::WChar_S:
1510 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001511 Width = Target->getWCharWidth();
1512 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001513 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001514 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001515 Width = Target->getChar16Width();
1516 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001517 break;
1518 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001519 Width = Target->getChar32Width();
1520 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001521 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001522 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001523 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001524 Width = Target->getShortWidth();
1525 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001526 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001527 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001528 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001529 Width = Target->getIntWidth();
1530 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001531 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001532 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001533 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001534 Width = Target->getLongWidth();
1535 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001536 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001537 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001538 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001539 Width = Target->getLongLongWidth();
1540 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001541 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001542 case BuiltinType::Int128:
1543 case BuiltinType::UInt128:
1544 Width = 128;
1545 Align = 128; // int128_t is 128-bit aligned on all targets.
1546 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001547 case BuiltinType::Half:
1548 Width = Target->getHalfWidth();
1549 Align = Target->getHalfAlign();
1550 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001551 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001552 Width = Target->getFloatWidth();
1553 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001554 break;
1555 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001556 Width = Target->getDoubleWidth();
1557 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001558 break;
1559 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001560 Width = Target->getLongDoubleWidth();
1561 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001562 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001563 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001564 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1565 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001566 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001567 case BuiltinType::ObjCId:
1568 case BuiltinType::ObjCClass:
1569 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001570 Width = Target->getPointerWidth(0);
1571 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001572 break;
Guy Benyei61054192013-02-07 10:55:47 +00001573 case BuiltinType::OCLSampler:
1574 // Samplers are modeled as integers.
1575 Width = Target->getIntWidth();
1576 Align = Target->getIntAlign();
1577 break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001578 case BuiltinType::OCLEvent:
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001579 case BuiltinType::OCLImage1d:
1580 case BuiltinType::OCLImage1dArray:
1581 case BuiltinType::OCLImage1dBuffer:
1582 case BuiltinType::OCLImage2d:
1583 case BuiltinType::OCLImage2dArray:
1584 case BuiltinType::OCLImage3d:
1585 // Currently these types are pointers to opaque types.
1586 Width = Target->getPointerWidth(0);
1587 Align = Target->getPointerAlign(0);
1588 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001589 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001590 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001591 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001592 Width = Target->getPointerWidth(0);
1593 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001594 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001595 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001596 unsigned AS = getTargetAddressSpace(
1597 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001598 Width = Target->getPointerWidth(AS);
1599 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001600 break;
1601 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001602 case Type::LValueReference:
1603 case Type::RValueReference: {
1604 // alignof and sizeof should never enter this code path here, so we go
1605 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001606 unsigned AS = getTargetAddressSpace(
1607 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001608 Width = Target->getPointerWidth(AS);
1609 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001610 break;
1611 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001612 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001613 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001614 Width = Target->getPointerWidth(AS);
1615 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001616 break;
1617 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001618 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001619 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Reid Kleckner3a52abf2013-03-28 20:02:56 +00001620 llvm::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001621 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001622 }
Chris Lattner647fb222007-07-18 18:26:58 +00001623 case Type::Complex: {
1624 // Complex types have the same alignment as their elements, but twice the
1625 // size.
Mike Stump11289f42009-09-09 15:08:12 +00001626 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +00001627 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +00001628 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +00001629 Align = EltInfo.second;
1630 break;
1631 }
John McCall8b07ec22010-05-15 11:32:37 +00001632 case Type::ObjCObject:
1633 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00001634 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00001635 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00001636 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().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
David Majnemer8b6bd572014-02-24 23:34:17 +00001764 const TypedefType *TT = T->getAs<TypedefType>();
1765
Eli Friedman7ab09572009-05-25 21:27:19 +00001766 // Double and long long should be naturally aligned if possible.
David Majnemer1d4db8f2014-02-24 23:43:27 +00001767 if (const ComplexType *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001768 T = CT->getElementType().getTypePtr();
1769 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001770 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1771 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00001772 // Don't increase the alignment if an alignment attribute was specified on a
1773 // typedef declaration.
1774 if (!TT || !TT->getDecl()->getMaxAlignment())
1775 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00001776
Chris Lattnera3402cd2009-01-27 18:08:34 +00001777 return ABIAlign;
1778}
1779
Ulrich Weigandfa806422013-05-06 16:23:57 +00001780/// getAlignOfGlobalVar - Return the alignment in bits that should be given
1781/// to a global variable of the specified type.
1782unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1783 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1784}
1785
1786/// getAlignOfGlobalVarInChars - Return the alignment in characters that
1787/// should be given to a global variable of the specified type.
1788CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1789 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1790}
1791
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001792/// DeepCollectObjCIvars -
1793/// This routine first collects all declared, but not synthesized, ivars in
1794/// super class and then collects all ivars, including those synthesized for
1795/// current class. This routine is used for implementation of current class
1796/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001797///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001798void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1799 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001800 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001801 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1802 DeepCollectObjCIvars(SuperClass, false, Ivars);
1803 if (!leafClass) {
1804 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1805 E = OI->ivar_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001806 Ivars.push_back(*I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001807 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001808 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001809 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001810 Iv= Iv->getNextIvar())
1811 Ivars.push_back(Iv);
1812 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001813}
1814
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001815/// CollectInheritedProtocols - Collect all protocols in current class and
1816/// those inherited by it.
1817void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001818 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001819 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001820 // We can use protocol_iterator here instead of
1821 // all_referenced_protocol_iterator since we are walking all categories.
1822 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1823 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001824 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001825 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001826 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001827 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001828 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001829 CollectInheritedProtocols(*P, Protocols);
1830 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001831 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001832
1833 // Categories of this Interface.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001834 for (ObjCInterfaceDecl::visible_categories_iterator
1835 Cat = OI->visible_categories_begin(),
1836 CatEnd = OI->visible_categories_end();
1837 Cat != CatEnd; ++Cat) {
1838 CollectInheritedProtocols(*Cat, Protocols);
1839 }
1840
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001841 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1842 while (SD) {
1843 CollectInheritedProtocols(SD, Protocols);
1844 SD = SD->getSuperClass();
1845 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001846 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001847 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001848 PE = OC->protocol_end(); P != PE; ++P) {
1849 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001850 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001851 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1852 PE = Proto->protocol_end(); P != PE; ++P)
1853 CollectInheritedProtocols(*P, Protocols);
1854 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001855 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001856 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1857 PE = OP->protocol_end(); P != PE; ++P) {
1858 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001859 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001860 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1861 PE = Proto->protocol_end(); P != PE; ++P)
1862 CollectInheritedProtocols(*P, Protocols);
1863 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001864 }
1865}
1866
Jay Foad39c79802011-01-12 09:06:06 +00001867unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001868 unsigned count = 0;
1869 // Count ivars declared in class extension.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001870 for (ObjCInterfaceDecl::known_extensions_iterator
1871 Ext = OI->known_extensions_begin(),
1872 ExtEnd = OI->known_extensions_end();
1873 Ext != ExtEnd; ++Ext) {
1874 count += Ext->ivar_size();
1875 }
1876
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001877 // Count ivar defined in this class's implementation. This
1878 // includes synthesized ivars.
1879 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001880 count += ImplDecl->ivar_size();
1881
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001882 return count;
1883}
1884
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001885bool ASTContext::isSentinelNullExpr(const Expr *E) {
1886 if (!E)
1887 return false;
1888
1889 // nullptr_t is always treated as null.
1890 if (E->getType()->isNullPtrType()) return true;
1891
1892 if (E->getType()->isAnyPointerType() &&
1893 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1894 Expr::NPC_ValueDependentIsNull))
1895 return true;
1896
1897 // Unfortunately, __null has type 'int'.
1898 if (isa<GNUNullExpr>(E)) return true;
1899
1900 return false;
1901}
1902
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001903/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1904ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1905 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1906 I = ObjCImpls.find(D);
1907 if (I != ObjCImpls.end())
1908 return cast<ObjCImplementationDecl>(I->second);
1909 return 0;
1910}
1911/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1912ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1913 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1914 I = ObjCImpls.find(D);
1915 if (I != ObjCImpls.end())
1916 return cast<ObjCCategoryImplDecl>(I->second);
1917 return 0;
1918}
1919
1920/// \brief Set the implementation of ObjCInterfaceDecl.
1921void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1922 ObjCImplementationDecl *ImplD) {
1923 assert(IFaceD && ImplD && "Passed null params");
1924 ObjCImpls[IFaceD] = ImplD;
1925}
1926/// \brief Set the implementation of ObjCCategoryDecl.
1927void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1928 ObjCCategoryImplDecl *ImplD) {
1929 assert(CatD && ImplD && "Passed null params");
1930 ObjCImpls[CatD] = ImplD;
1931}
1932
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001933const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
1934 const NamedDecl *ND) const {
1935 if (const ObjCInterfaceDecl *ID =
1936 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001937 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001938 if (const ObjCCategoryDecl *CD =
1939 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001940 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00001941 if (const ObjCImplDecl *IMD =
1942 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001943 return IMD->getClassInterface();
1944
1945 return 0;
1946}
1947
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001948/// \brief Get the copy initialization expression of VarDecl,or NULL if
1949/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001950Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001951 assert(VD && "Passed null params");
1952 assert(VD->hasAttr<BlocksAttr>() &&
1953 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001954 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001955 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001956 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1957}
1958
1959/// \brief Set the copy inialization expression of a block var decl.
1960void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1961 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001962 assert(VD->hasAttr<BlocksAttr>() &&
1963 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001964 BlockVarCopyInits[VD] = Init;
1965}
1966
John McCallbcd03502009-12-07 02:54:59 +00001967TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001968 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001969 if (!DataSize)
1970 DataSize = TypeLoc::getFullDataSizeForType(T);
1971 else
1972 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001973 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001974
John McCallbcd03502009-12-07 02:54:59 +00001975 TypeSourceInfo *TInfo =
1976 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1977 new (TInfo) TypeSourceInfo(T);
1978 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001979}
1980
John McCallbcd03502009-12-07 02:54:59 +00001981TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001982 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001983 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001984 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001985 return DI;
1986}
1987
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001988const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001989ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001990 return getObjCLayout(D, 0);
1991}
1992
1993const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001994ASTContext::getASTObjCImplementationLayout(
1995 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001996 return getObjCLayout(D->getClassInterface(), D);
1997}
1998
Chris Lattner983a8bb2007-07-13 22:13:22 +00001999//===----------------------------------------------------------------------===//
2000// Type creation/memoization methods
2001//===----------------------------------------------------------------------===//
2002
Jay Foad39c79802011-01-12 09:06:06 +00002003QualType
John McCall33ddac02011-01-19 10:06:00 +00002004ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2005 unsigned fastQuals = quals.getFastQualifiers();
2006 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002007
2008 // Check if we've already instantiated this type.
2009 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002010 ExtQuals::Profile(ID, baseType, quals);
2011 void *insertPos = 0;
2012 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2013 assert(eq->getQualifiers() == quals);
2014 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002015 }
2016
John McCall33ddac02011-01-19 10:06:00 +00002017 // If the base type is not canonical, make the appropriate canonical type.
2018 QualType canon;
2019 if (!baseType->isCanonicalUnqualified()) {
2020 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002021 canonSplit.Quals.addConsistentQualifiers(quals);
2022 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002023
2024 // Re-find the insert position.
2025 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2026 }
2027
2028 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2029 ExtQualNodes.InsertNode(eq, insertPos);
2030 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002031}
2032
Jay Foad39c79802011-01-12 09:06:06 +00002033QualType
2034ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002035 QualType CanT = getCanonicalType(T);
2036 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002037 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002038
John McCall8ccfcb52009-09-24 19:53:00 +00002039 // If we are composing extended qualifiers together, merge together
2040 // into one ExtQuals node.
2041 QualifierCollector Quals;
2042 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002043
John McCall8ccfcb52009-09-24 19:53:00 +00002044 // If this type already has an address space specified, it cannot get
2045 // another one.
2046 assert(!Quals.hasAddressSpace() &&
2047 "Type cannot be in multiple addr spaces!");
2048 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002049
John McCall8ccfcb52009-09-24 19:53:00 +00002050 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002051}
2052
Chris Lattnerd60183d2009-02-18 22:53:11 +00002053QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002054 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002055 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002056 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002057 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002058
John McCall53fa7142010-12-24 02:08:15 +00002059 if (const PointerType *ptr = T->getAs<PointerType>()) {
2060 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002061 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002062 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2063 return getPointerType(ResultType);
2064 }
2065 }
Mike Stump11289f42009-09-09 15:08:12 +00002066
John McCall8ccfcb52009-09-24 19:53:00 +00002067 // If we are composing extended qualifiers together, merge together
2068 // into one ExtQuals node.
2069 QualifierCollector Quals;
2070 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002071
John McCall8ccfcb52009-09-24 19:53:00 +00002072 // If this type already has an ObjCGC specified, it cannot get
2073 // another one.
2074 assert(!Quals.hasObjCGCAttr() &&
2075 "Type cannot have multiple ObjCGCs!");
2076 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002077
John McCall8ccfcb52009-09-24 19:53:00 +00002078 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002079}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002080
John McCall4f5019e2010-12-19 02:44:49 +00002081const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2082 FunctionType::ExtInfo Info) {
2083 if (T->getExtInfo() == Info)
2084 return T;
2085
2086 QualType Result;
2087 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002088 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002089 } else {
2090 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2091 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2092 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002093 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002094 }
2095
2096 return cast<FunctionType>(Result.getTypePtr());
2097}
2098
Richard Smith2a7d4812013-05-04 07:00:32 +00002099void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2100 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002101 FD = FD->getMostRecentDecl();
2102 while (true) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002103 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2104 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002105 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002106 if (FunctionDecl *Next = FD->getPreviousDecl())
2107 FD = Next;
2108 else
2109 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002110 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002111 if (ASTMutationListener *L = getASTMutationListener())
2112 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002113}
2114
Chris Lattnerc6395932007-06-22 20:56:16 +00002115/// getComplexType - Return the uniqued reference to the type for a complex
2116/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002117QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002118 // Unique pointers, to guarantee there is only one pointer of a particular
2119 // structure.
2120 llvm::FoldingSetNodeID ID;
2121 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002122
Chris Lattnerc6395932007-06-22 20:56:16 +00002123 void *InsertPos = 0;
2124 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2125 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002126
Chris Lattnerc6395932007-06-22 20:56:16 +00002127 // If the pointee type isn't canonical, this won't be a canonical type either,
2128 // so fill in the canonical type field.
2129 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002130 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002131 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002132
Chris Lattnerc6395932007-06-22 20:56:16 +00002133 // Get the new insert position for the node we care about.
2134 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002135 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002136 }
John McCall90d1c2d2009-09-24 23:30:46 +00002137 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002138 Types.push_back(New);
2139 ComplexTypes.InsertNode(New, InsertPos);
2140 return QualType(New, 0);
2141}
2142
Chris Lattner970e54e2006-11-12 00:37:36 +00002143/// getPointerType - Return the uniqued reference to the type for a pointer to
2144/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002145QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002146 // Unique pointers, to guarantee there is only one pointer of a particular
2147 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002148 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002149 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002150
Chris Lattner67521df2007-01-27 01:29:36 +00002151 void *InsertPos = 0;
2152 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002153 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002154
Chris Lattner7ccecb92006-11-12 08:50:50 +00002155 // If the pointee type isn't canonical, this won't be a canonical type either,
2156 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002157 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002158 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002159 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002160
Bob Wilsonc8541f22013-03-15 17:12:43 +00002161 // Get the new insert position for the node we care about.
2162 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2163 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2164 }
John McCall90d1c2d2009-09-24 23:30:46 +00002165 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002166 Types.push_back(New);
2167 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002168 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002169}
2170
Reid Kleckner0503a872013-12-05 01:23:43 +00002171QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2172 llvm::FoldingSetNodeID ID;
2173 AdjustedType::Profile(ID, Orig, New);
2174 void *InsertPos = 0;
2175 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2176 if (AT)
2177 return QualType(AT, 0);
2178
2179 QualType Canonical = getCanonicalType(New);
2180
2181 // Get the new insert position for the node we care about.
2182 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2183 assert(AT == 0 && "Shouldn't be in the map!");
2184
2185 AT = new (*this, TypeAlignment)
2186 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2187 Types.push_back(AT);
2188 AdjustedTypes.InsertNode(AT, InsertPos);
2189 return QualType(AT, 0);
2190}
2191
Reid Kleckner8a365022013-06-24 17:51:48 +00002192QualType ASTContext::getDecayedType(QualType T) const {
2193 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2194
Reid Kleckner8a365022013-06-24 17:51:48 +00002195 QualType Decayed;
2196
2197 // C99 6.7.5.3p7:
2198 // A declaration of a parameter as "array of type" shall be
2199 // adjusted to "qualified pointer to type", where the type
2200 // qualifiers (if any) are those specified within the [ and ] of
2201 // the array type derivation.
2202 if (T->isArrayType())
2203 Decayed = getArrayDecayedType(T);
2204
2205 // C99 6.7.5.3p8:
2206 // A declaration of a parameter as "function returning type"
2207 // shall be adjusted to "pointer to function returning type", as
2208 // in 6.3.2.1.
2209 if (T->isFunctionType())
2210 Decayed = getPointerType(T);
2211
Reid Kleckner0503a872013-12-05 01:23:43 +00002212 llvm::FoldingSetNodeID ID;
2213 AdjustedType::Profile(ID, T, Decayed);
2214 void *InsertPos = 0;
2215 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2216 if (AT)
2217 return QualType(AT, 0);
2218
Reid Kleckner8a365022013-06-24 17:51:48 +00002219 QualType Canonical = getCanonicalType(Decayed);
2220
2221 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002222 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2223 assert(AT == 0 && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002224
Reid Kleckner0503a872013-12-05 01:23:43 +00002225 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2226 Types.push_back(AT);
2227 AdjustedTypes.InsertNode(AT, InsertPos);
2228 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002229}
2230
Mike Stump11289f42009-09-09 15:08:12 +00002231/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002232/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002233QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002234 assert(T->isFunctionType() && "block of function types only");
2235 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002236 // structure.
2237 llvm::FoldingSetNodeID ID;
2238 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002239
Steve Naroffec33ed92008-08-27 16:04:49 +00002240 void *InsertPos = 0;
2241 if (BlockPointerType *PT =
2242 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2243 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002244
2245 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002246 // type either so fill in the canonical type field.
2247 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002248 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002249 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002250
Steve Naroffec33ed92008-08-27 16:04:49 +00002251 // Get the new insert position for the node we care about.
2252 BlockPointerType *NewIP =
2253 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002254 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002255 }
John McCall90d1c2d2009-09-24 23:30:46 +00002256 BlockPointerType *New
2257 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002258 Types.push_back(New);
2259 BlockPointerTypes.InsertNode(New, InsertPos);
2260 return QualType(New, 0);
2261}
2262
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002263/// getLValueReferenceType - Return the uniqued reference to the type for an
2264/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002265QualType
2266ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002267 assert(getCanonicalType(T) != OverloadTy &&
2268 "Unresolved overloaded function type");
2269
Bill Wendling3708c182007-05-27 10:15:43 +00002270 // Unique pointers, to guarantee there is only one pointer of a particular
2271 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002272 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002273 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002274
2275 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002276 if (LValueReferenceType *RT =
2277 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002278 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002279
John McCallfc93cf92009-10-22 22:37:11 +00002280 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2281
Bill Wendling3708c182007-05-27 10:15:43 +00002282 // If the referencee type isn't canonical, this won't be a canonical type
2283 // either, so fill in the canonical type field.
2284 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002285 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2286 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2287 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002288
Bill Wendling3708c182007-05-27 10:15:43 +00002289 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002290 LValueReferenceType *NewIP =
2291 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002292 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002293 }
2294
John McCall90d1c2d2009-09-24 23:30:46 +00002295 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002296 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2297 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002298 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002299 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002300
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002301 return QualType(New, 0);
2302}
2303
2304/// getRValueReferenceType - Return the uniqued reference to the type for an
2305/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002306QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002307 // Unique pointers, to guarantee there is only one pointer of a particular
2308 // structure.
2309 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002310 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002311
2312 void *InsertPos = 0;
2313 if (RValueReferenceType *RT =
2314 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2315 return QualType(RT, 0);
2316
John McCallfc93cf92009-10-22 22:37:11 +00002317 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2318
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002319 // If the referencee type isn't canonical, this won't be a canonical type
2320 // either, so fill in the canonical type field.
2321 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002322 if (InnerRef || !T.isCanonical()) {
2323 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2324 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002325
2326 // Get the new insert position for the node we care about.
2327 RValueReferenceType *NewIP =
2328 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002329 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002330 }
2331
John McCall90d1c2d2009-09-24 23:30:46 +00002332 RValueReferenceType *New
2333 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002334 Types.push_back(New);
2335 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002336 return QualType(New, 0);
2337}
2338
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002339/// getMemberPointerType - Return the uniqued reference to the type for a
2340/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002341QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002342 // Unique pointers, to guarantee there is only one pointer of a particular
2343 // structure.
2344 llvm::FoldingSetNodeID ID;
2345 MemberPointerType::Profile(ID, T, Cls);
2346
2347 void *InsertPos = 0;
2348 if (MemberPointerType *PT =
2349 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2350 return QualType(PT, 0);
2351
2352 // If the pointee or class type isn't canonical, this won't be a canonical
2353 // type either, so fill in the canonical type field.
2354 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002355 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002356 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2357
2358 // Get the new insert position for the node we care about.
2359 MemberPointerType *NewIP =
2360 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002361 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002362 }
John McCall90d1c2d2009-09-24 23:30:46 +00002363 MemberPointerType *New
2364 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002365 Types.push_back(New);
2366 MemberPointerTypes.InsertNode(New, InsertPos);
2367 return QualType(New, 0);
2368}
2369
Mike Stump11289f42009-09-09 15:08:12 +00002370/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002371/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002372QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002373 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002374 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002375 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002376 assert((EltTy->isDependentType() ||
2377 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002378 "Constant array of VLAs is illegal!");
2379
Chris Lattnere2df3f92009-05-13 04:12:56 +00002380 // Convert the array size into a canonical width matching the pointer size for
2381 // the target.
2382 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002383 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002384 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002385
Chris Lattner23b7eb62007-06-15 23:05:46 +00002386 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002387 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002388
Chris Lattner36f8e652007-01-27 08:31:04 +00002389 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002390 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002391 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002392 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002393
John McCall33ddac02011-01-19 10:06:00 +00002394 // If the element type isn't canonical or has qualifiers, this won't
2395 // be a canonical type either, so fill in the canonical type field.
2396 QualType Canon;
2397 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2398 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002399 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002400 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002401 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002402
Chris Lattner36f8e652007-01-27 08:31:04 +00002403 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002404 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002405 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002406 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002407 }
Mike Stump11289f42009-09-09 15:08:12 +00002408
John McCall90d1c2d2009-09-24 23:30:46 +00002409 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002410 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002411 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002412 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002413 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002414}
2415
John McCall06549462011-01-18 08:40:38 +00002416/// getVariableArrayDecayedType - Turns the given type, which may be
2417/// variably-modified, into the corresponding type with all the known
2418/// sizes replaced with [*].
2419QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2420 // Vastly most common case.
2421 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002422
John McCall06549462011-01-18 08:40:38 +00002423 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002424
John McCall06549462011-01-18 08:40:38 +00002425 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002426 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002427 switch (ty->getTypeClass()) {
2428#define TYPE(Class, Base)
2429#define ABSTRACT_TYPE(Class, Base)
2430#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2431#include "clang/AST/TypeNodes.def"
2432 llvm_unreachable("didn't desugar past all non-canonical types?");
2433
2434 // These types should never be variably-modified.
2435 case Type::Builtin:
2436 case Type::Complex:
2437 case Type::Vector:
2438 case Type::ExtVector:
2439 case Type::DependentSizedExtVector:
2440 case Type::ObjCObject:
2441 case Type::ObjCInterface:
2442 case Type::ObjCObjectPointer:
2443 case Type::Record:
2444 case Type::Enum:
2445 case Type::UnresolvedUsing:
2446 case Type::TypeOfExpr:
2447 case Type::TypeOf:
2448 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002449 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002450 case Type::DependentName:
2451 case Type::InjectedClassName:
2452 case Type::TemplateSpecialization:
2453 case Type::DependentTemplateSpecialization:
2454 case Type::TemplateTypeParm:
2455 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002456 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00002457 case Type::PackExpansion:
2458 llvm_unreachable("type should never be variably-modified");
2459
2460 // These types can be variably-modified but should never need to
2461 // further decay.
2462 case Type::FunctionNoProto:
2463 case Type::FunctionProto:
2464 case Type::BlockPointer:
2465 case Type::MemberPointer:
2466 return type;
2467
2468 // These types can be variably-modified. All these modifications
2469 // preserve structure except as noted by comments.
2470 // TODO: if we ever care about optimizing VLAs, there are no-op
2471 // optimizations available here.
2472 case Type::Pointer:
2473 result = getPointerType(getVariableArrayDecayedType(
2474 cast<PointerType>(ty)->getPointeeType()));
2475 break;
2476
2477 case Type::LValueReference: {
2478 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2479 result = getLValueReferenceType(
2480 getVariableArrayDecayedType(lv->getPointeeType()),
2481 lv->isSpelledAsLValue());
2482 break;
2483 }
2484
2485 case Type::RValueReference: {
2486 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2487 result = getRValueReferenceType(
2488 getVariableArrayDecayedType(lv->getPointeeType()));
2489 break;
2490 }
2491
Eli Friedman0dfb8892011-10-06 23:00:33 +00002492 case Type::Atomic: {
2493 const AtomicType *at = cast<AtomicType>(ty);
2494 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2495 break;
2496 }
2497
John McCall06549462011-01-18 08:40:38 +00002498 case Type::ConstantArray: {
2499 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2500 result = getConstantArrayType(
2501 getVariableArrayDecayedType(cat->getElementType()),
2502 cat->getSize(),
2503 cat->getSizeModifier(),
2504 cat->getIndexTypeCVRQualifiers());
2505 break;
2506 }
2507
2508 case Type::DependentSizedArray: {
2509 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2510 result = getDependentSizedArrayType(
2511 getVariableArrayDecayedType(dat->getElementType()),
2512 dat->getSizeExpr(),
2513 dat->getSizeModifier(),
2514 dat->getIndexTypeCVRQualifiers(),
2515 dat->getBracketsRange());
2516 break;
2517 }
2518
2519 // Turn incomplete types into [*] types.
2520 case Type::IncompleteArray: {
2521 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2522 result = getVariableArrayType(
2523 getVariableArrayDecayedType(iat->getElementType()),
2524 /*size*/ 0,
2525 ArrayType::Normal,
2526 iat->getIndexTypeCVRQualifiers(),
2527 SourceRange());
2528 break;
2529 }
2530
2531 // Turn VLA types into [*] types.
2532 case Type::VariableArray: {
2533 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2534 result = getVariableArrayType(
2535 getVariableArrayDecayedType(vat->getElementType()),
2536 /*size*/ 0,
2537 ArrayType::Star,
2538 vat->getIndexTypeCVRQualifiers(),
2539 vat->getBracketsRange());
2540 break;
2541 }
2542 }
2543
2544 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002545 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002546}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002547
Steve Naroffcadebd02007-08-30 18:14:25 +00002548/// getVariableArrayType - Returns a non-unique reference to the type for a
2549/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002550QualType ASTContext::getVariableArrayType(QualType EltTy,
2551 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002552 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002553 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002554 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002555 // Since we don't unique expressions, it isn't possible to unique VLA's
2556 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002557 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002558
John McCall33ddac02011-01-19 10:06:00 +00002559 // Be sure to pull qualifiers off the element type.
2560 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2561 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002562 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002563 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002564 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002565 }
2566
John McCall90d1c2d2009-09-24 23:30:46 +00002567 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002568 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002569
2570 VariableArrayTypes.push_back(New);
2571 Types.push_back(New);
2572 return QualType(New, 0);
2573}
2574
Douglas Gregor4619e432008-12-05 23:32:09 +00002575/// getDependentSizedArrayType - Returns a non-unique reference to
2576/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002577/// type.
John McCall33ddac02011-01-19 10:06:00 +00002578QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2579 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002580 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002581 unsigned elementTypeQuals,
2582 SourceRange brackets) const {
2583 assert((!numElements || numElements->isTypeDependent() ||
2584 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002585 "Size must be type- or value-dependent!");
2586
John McCall33ddac02011-01-19 10:06:00 +00002587 // Dependently-sized array types that do not have a specified number
2588 // of elements will have their sizes deduced from a dependent
2589 // initializer. We do no canonicalization here at all, which is okay
2590 // because they can't be used in most locations.
2591 if (!numElements) {
2592 DependentSizedArrayType *newType
2593 = new (*this, TypeAlignment)
2594 DependentSizedArrayType(*this, elementType, QualType(),
2595 numElements, ASM, elementTypeQuals,
2596 brackets);
2597 Types.push_back(newType);
2598 return QualType(newType, 0);
2599 }
2600
2601 // Otherwise, we actually build a new type every time, but we
2602 // also build a canonical type.
2603
2604 SplitQualType canonElementType = getCanonicalType(elementType).split();
2605
2606 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002607 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002608 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002609 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002610 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002611
John McCall33ddac02011-01-19 10:06:00 +00002612 // Look for an existing type with these properties.
2613 DependentSizedArrayType *canonTy =
2614 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002615
John McCall33ddac02011-01-19 10:06:00 +00002616 // If we don't have one, build one.
2617 if (!canonTy) {
2618 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002619 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002620 QualType(), numElements, ASM, elementTypeQuals,
2621 brackets);
2622 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2623 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002624 }
2625
John McCall33ddac02011-01-19 10:06:00 +00002626 // Apply qualifiers from the element type to the array.
2627 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002628 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002629
John McCall33ddac02011-01-19 10:06:00 +00002630 // If we didn't need extra canonicalization for the element type,
2631 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00002632 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00002633 return canon;
2634
2635 // Otherwise, we need to build a type which follows the spelling
2636 // of the element type.
2637 DependentSizedArrayType *sugaredType
2638 = new (*this, TypeAlignment)
2639 DependentSizedArrayType(*this, elementType, canon, numElements,
2640 ASM, elementTypeQuals, brackets);
2641 Types.push_back(sugaredType);
2642 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002643}
2644
John McCall33ddac02011-01-19 10:06:00 +00002645QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002646 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002647 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002648 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002649 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002650
John McCall33ddac02011-01-19 10:06:00 +00002651 void *insertPos = 0;
2652 if (IncompleteArrayType *iat =
2653 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2654 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002655
2656 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002657 // either, so fill in the canonical type field. We also have to pull
2658 // qualifiers off the element type.
2659 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002660
John McCall33ddac02011-01-19 10:06:00 +00002661 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2662 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002663 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002664 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002665 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002666
2667 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002668 IncompleteArrayType *existing =
2669 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2670 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002671 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002672
John McCall33ddac02011-01-19 10:06:00 +00002673 IncompleteArrayType *newType = new (*this, TypeAlignment)
2674 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002675
John McCall33ddac02011-01-19 10:06:00 +00002676 IncompleteArrayTypes.InsertNode(newType, insertPos);
2677 Types.push_back(newType);
2678 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002679}
2680
Steve Naroff91fcddb2007-07-18 18:00:27 +00002681/// getVectorType - Return the unique reference to a vector type of
2682/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002683QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002684 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00002685 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00002686
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002687 // Check if we've already instantiated a vector of this type.
2688 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002689 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002690
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002691 void *InsertPos = 0;
2692 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2693 return QualType(VTP, 0);
2694
2695 // If the element type isn't canonical, this won't be a canonical type either,
2696 // so fill in the canonical type field.
2697 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002698 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002699 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002700
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002701 // Get the new insert position for the node we care about.
2702 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002703 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002704 }
John McCall90d1c2d2009-09-24 23:30:46 +00002705 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002706 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002707 VectorTypes.InsertNode(New, InsertPos);
2708 Types.push_back(New);
2709 return QualType(New, 0);
2710}
2711
Nate Begemance4d7fc2008-04-18 23:10:10 +00002712/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002713/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002714QualType
2715ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002716 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002717
Steve Naroff91fcddb2007-07-18 18:00:27 +00002718 // Check if we've already instantiated a vector of this type.
2719 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002720 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002721 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002722 void *InsertPos = 0;
2723 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2724 return QualType(VTP, 0);
2725
2726 // If the element type isn't canonical, this won't be a canonical type either,
2727 // so fill in the canonical type field.
2728 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002729 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002730 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002731
Steve Naroff91fcddb2007-07-18 18:00:27 +00002732 // Get the new insert position for the node we care about.
2733 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002734 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002735 }
John McCall90d1c2d2009-09-24 23:30:46 +00002736 ExtVectorType *New = new (*this, TypeAlignment)
2737 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002738 VectorTypes.InsertNode(New, InsertPos);
2739 Types.push_back(New);
2740 return QualType(New, 0);
2741}
2742
Jay Foad39c79802011-01-12 09:06:06 +00002743QualType
2744ASTContext::getDependentSizedExtVectorType(QualType vecType,
2745 Expr *SizeExpr,
2746 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002747 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002748 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002749 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002750
Douglas Gregor352169a2009-07-31 03:54:25 +00002751 void *InsertPos = 0;
2752 DependentSizedExtVectorType *Canon
2753 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2754 DependentSizedExtVectorType *New;
2755 if (Canon) {
2756 // We already have a canonical version of this array type; use it as
2757 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002758 New = new (*this, TypeAlignment)
2759 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2760 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002761 } else {
2762 QualType CanonVecTy = getCanonicalType(vecType);
2763 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002764 New = new (*this, TypeAlignment)
2765 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2766 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002767
2768 DependentSizedExtVectorType *CanonCheck
2769 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2770 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2771 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002772 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2773 } else {
2774 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2775 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002776 New = new (*this, TypeAlignment)
2777 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002778 }
2779 }
Mike Stump11289f42009-09-09 15:08:12 +00002780
Douglas Gregor758a8692009-06-17 21:51:59 +00002781 Types.push_back(New);
2782 return QualType(New, 0);
2783}
2784
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002785/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002786///
Jay Foad39c79802011-01-12 09:06:06 +00002787QualType
2788ASTContext::getFunctionNoProtoType(QualType ResultTy,
2789 const FunctionType::ExtInfo &Info) const {
Reid Kleckner78af0702013-08-27 23:08:25 +00002790 const CallingConv CallConv = Info.getCC();
2791
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002792 // Unique functions, to guarantee there is only one function of a particular
2793 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002794 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002795 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002796
Chris Lattner47955de2007-01-27 08:37:20 +00002797 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002798 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002799 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002800 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002801
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002802 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002803 if (!ResultTy.isCanonical()) {
2804 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00002805
Chris Lattner47955de2007-01-27 08:37:20 +00002806 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002807 FunctionNoProtoType *NewIP =
2808 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002809 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002810 }
Mike Stump11289f42009-09-09 15:08:12 +00002811
Roman Divacky65b88cd2011-03-01 17:40:53 +00002812 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002813 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002814 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002815 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002816 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002817 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002818}
2819
Douglas Gregorcd780372013-01-17 23:36:45 +00002820/// \brief Determine whether \p T is canonical as the result type of a function.
2821static bool isCanonicalResultType(QualType T) {
2822 return T.isCanonical() &&
2823 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2824 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2825}
2826
Jay Foad39c79802011-01-12 09:06:06 +00002827QualType
Jordan Rose5c382722013-03-08 21:51:21 +00002828ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
Jay Foad39c79802011-01-12 09:06:06 +00002829 const FunctionProtoType::ExtProtoInfo &EPI) const {
Jordan Rose5c382722013-03-08 21:51:21 +00002830 size_t NumArgs = ArgArray.size();
2831
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002832 // Unique functions, to guarantee there is only one function of a particular
2833 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002834 llvm::FoldingSetNodeID ID;
Jordan Rose5c382722013-03-08 21:51:21 +00002835 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
2836 *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002837
2838 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002839 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002840 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002841 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002842
2843 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002844 bool isCanonical =
Douglas Gregorcd780372013-01-17 23:36:45 +00002845 EPI.ExceptionSpecType == EST_None && isCanonicalResultType(ResultTy) &&
Richard Smith5e580292012-02-10 09:58:53 +00002846 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002847 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002848 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002849 isCanonical = false;
2850
2851 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002852 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002853 QualType Canonical;
Reid Kleckner78af0702013-08-27 23:08:25 +00002854 if (!isCanonical) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002855 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002856 CanonicalArgs.reserve(NumArgs);
2857 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002858 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002859
John McCalldb40c7f2010-12-14 08:05:40 +00002860 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002861 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002862 CanonicalEPI.ExceptionSpecType = EST_None;
2863 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002864
Douglas Gregorcd780372013-01-17 23:36:45 +00002865 // Result types do not have ARC lifetime qualifiers.
2866 QualType CanResultTy = getCanonicalType(ResultTy);
2867 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2868 Qualifiers Qs = CanResultTy.getQualifiers();
2869 Qs.removeObjCLifetime();
2870 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2871 }
2872
Jordan Rose5c382722013-03-08 21:51:21 +00002873 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002874
Chris Lattnerfd4de792007-01-27 01:15:32 +00002875 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002876 FunctionProtoType *NewIP =
2877 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002878 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002879 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002880
John McCall31168b02011-06-15 23:02:42 +00002881 // FunctionProtoType objects are allocated with extra bytes after
2882 // them for three variable size arrays at the end:
2883 // - parameter types
2884 // - exception types
2885 // - consumed-arguments flags
2886 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00002887 // expression, or information used to resolve the exception
2888 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00002889 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002890 NumArgs * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002891 if (EPI.ExceptionSpecType == EST_Dynamic) {
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002892 Size += EPI.NumExceptions * sizeof(QualType);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002893 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002894 Size += sizeof(Expr*);
Richard Smithf623c962012-04-17 00:58:00 +00002895 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00002896 Size += 2 * sizeof(FunctionDecl*);
Richard Smithd3b5c9082012-07-27 04:22:15 +00002897 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2898 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002899 }
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002900 if (EPI.ConsumedParameters)
John McCall31168b02011-06-15 23:02:42 +00002901 Size += NumArgs * sizeof(bool);
2902
John McCalldb40c7f2010-12-14 08:05:40 +00002903 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002904 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00002905 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002906 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002907 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002908 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002909}
Chris Lattneref51c202006-11-10 07:17:23 +00002910
John McCalle78aac42010-03-10 03:28:59 +00002911#ifndef NDEBUG
2912static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2913 if (!isa<CXXRecordDecl>(D)) return false;
2914 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2915 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2916 return true;
2917 if (RD->getDescribedClassTemplate() &&
2918 !isa<ClassTemplateSpecializationDecl>(RD))
2919 return true;
2920 return false;
2921}
2922#endif
2923
2924/// getInjectedClassNameType - Return the unique reference to the
2925/// injected class name type for the specified templated declaration.
2926QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002927 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002928 assert(NeedsInjectedClassNameType(Decl));
2929 if (Decl->TypeForDecl) {
2930 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00002931 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00002932 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2933 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2934 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2935 } else {
John McCall424cec92011-01-19 06:33:43 +00002936 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002937 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002938 Decl->TypeForDecl = newType;
2939 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002940 }
2941 return QualType(Decl->TypeForDecl, 0);
2942}
2943
Douglas Gregor83a586e2008-04-13 21:07:44 +00002944/// getTypeDeclType - Return the unique reference to the type for the
2945/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002946QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002947 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002948 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002949
Richard Smithdda56e42011-04-15 14:24:37 +00002950 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002951 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002952
John McCall96f0b5f2010-03-10 06:48:02 +00002953 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2954 "Template type parameter types are always available.");
2955
John McCall81e38502010-02-16 03:57:14 +00002956 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00002957 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00002958 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002959 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002960 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00002961 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002962 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002963 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002964 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002965 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2966 Decl->TypeForDecl = newType;
2967 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002968 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002969 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002970
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002971 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002972}
2973
Chris Lattner32d920b2007-01-26 02:01:53 +00002974/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002975/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002976QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002977ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2978 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002979 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002980
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002981 if (Canonical.isNull())
2982 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002983 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002984 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002985 Decl->TypeForDecl = newType;
2986 Types.push_back(newType);
2987 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002988}
2989
Jay Foad39c79802011-01-12 09:06:06 +00002990QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002991 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2992
Douglas Gregorec9fd132012-01-14 16:38:05 +00002993 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002994 if (PrevDecl->TypeForDecl)
2995 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2996
John McCall424cec92011-01-19 06:33:43 +00002997 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2998 Decl->TypeForDecl = newType;
2999 Types.push_back(newType);
3000 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003001}
3002
Jay Foad39c79802011-01-12 09:06:06 +00003003QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003004 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3005
Douglas Gregorec9fd132012-01-14 16:38:05 +00003006 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003007 if (PrevDecl->TypeForDecl)
3008 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3009
John McCall424cec92011-01-19 06:33:43 +00003010 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3011 Decl->TypeForDecl = newType;
3012 Types.push_back(newType);
3013 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003014}
3015
John McCall81904512011-01-06 01:58:22 +00003016QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3017 QualType modifiedType,
3018 QualType equivalentType) {
3019 llvm::FoldingSetNodeID id;
3020 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3021
3022 void *insertPos = 0;
3023 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3024 if (type) return QualType(type, 0);
3025
3026 QualType canon = getCanonicalType(equivalentType);
3027 type = new (*this, TypeAlignment)
3028 AttributedType(canon, attrKind, modifiedType, equivalentType);
3029
3030 Types.push_back(type);
3031 AttributedTypes.InsertNode(type, insertPos);
3032
3033 return QualType(type, 0);
3034}
3035
3036
John McCallcebee162009-10-18 09:09:24 +00003037/// \brief Retrieve a substitution-result type.
3038QualType
3039ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003040 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003041 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003042 && "replacement types must always be canonical");
3043
3044 llvm::FoldingSetNodeID ID;
3045 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
3046 void *InsertPos = 0;
3047 SubstTemplateTypeParmType *SubstParm
3048 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3049
3050 if (!SubstParm) {
3051 SubstParm = new (*this, TypeAlignment)
3052 SubstTemplateTypeParmType(Parm, Replacement);
3053 Types.push_back(SubstParm);
3054 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3055 }
3056
3057 return QualType(SubstParm, 0);
3058}
3059
Douglas Gregorada4b792011-01-14 02:55:32 +00003060/// \brief Retrieve a
3061QualType ASTContext::getSubstTemplateTypeParmPackType(
3062 const TemplateTypeParmType *Parm,
3063 const TemplateArgument &ArgPack) {
3064#ifndef NDEBUG
3065 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
3066 PEnd = ArgPack.pack_end();
3067 P != PEnd; ++P) {
3068 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3069 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
3070 }
3071#endif
3072
3073 llvm::FoldingSetNodeID ID;
3074 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
3075 void *InsertPos = 0;
3076 if (SubstTemplateTypeParmPackType *SubstParm
3077 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3078 return QualType(SubstParm, 0);
3079
3080 QualType Canon;
3081 if (!Parm->isCanonicalUnqualified()) {
3082 Canon = getCanonicalType(QualType(Parm, 0));
3083 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3084 ArgPack);
3085 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3086 }
3087
3088 SubstTemplateTypeParmPackType *SubstParm
3089 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3090 ArgPack);
3091 Types.push_back(SubstParm);
3092 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3093 return QualType(SubstParm, 0);
3094}
3095
Douglas Gregoreff93e02009-02-05 23:33:38 +00003096/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003097/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003098/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003099QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003100 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003101 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003102 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003103 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003104 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003105 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003106 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3107
3108 if (TypeParm)
3109 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003110
Chandler Carruth08836322011-05-01 00:51:33 +00003111 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003112 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003113 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003114
3115 TemplateTypeParmType *TypeCheck
3116 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3117 assert(!TypeCheck && "Template type parameter canonical type broken");
3118 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003119 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003120 TypeParm = new (*this, TypeAlignment)
3121 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003122
3123 Types.push_back(TypeParm);
3124 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3125
3126 return QualType(TypeParm, 0);
3127}
3128
John McCalle78aac42010-03-10 03:28:59 +00003129TypeSourceInfo *
3130ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3131 SourceLocation NameLoc,
3132 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003133 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003134 assert(!Name.getAsDependentTemplateName() &&
3135 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003136 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003137
3138 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003139 TemplateSpecializationTypeLoc TL =
3140 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003141 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003142 TL.setTemplateNameLoc(NameLoc);
3143 TL.setLAngleLoc(Args.getLAngleLoc());
3144 TL.setRAngleLoc(Args.getRAngleLoc());
3145 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3146 TL.setArgLocInfo(i, Args[i].getLocInfo());
3147 return DI;
3148}
3149
Mike Stump11289f42009-09-09 15:08:12 +00003150QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003151ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003152 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003153 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003154 assert(!Template.getAsDependentTemplateName() &&
3155 "No dependent template names here!");
3156
John McCall6b51f282009-11-23 01:53:49 +00003157 unsigned NumArgs = Args.size();
3158
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003159 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00003160 ArgVec.reserve(NumArgs);
3161 for (unsigned i = 0; i != NumArgs; ++i)
3162 ArgVec.push_back(Args[i].getArgument());
3163
John McCall2408e322010-04-27 00:57:59 +00003164 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003165 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003166}
3167
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003168#ifndef NDEBUG
3169static bool hasAnyPackExpansions(const TemplateArgument *Args,
3170 unsigned NumArgs) {
3171 for (unsigned I = 0; I != NumArgs; ++I)
3172 if (Args[I].isPackExpansion())
3173 return true;
3174
3175 return true;
3176}
3177#endif
3178
John McCall0ad16662009-10-29 08:12:44 +00003179QualType
3180ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00003181 const TemplateArgument *Args,
3182 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003183 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003184 assert(!Template.getAsDependentTemplateName() &&
3185 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003186 // Look through qualified template names.
3187 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3188 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003189
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003190 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003191 Template.getAsTemplateDecl() &&
3192 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003193 QualType CanonType;
3194 if (!Underlying.isNull())
3195 CanonType = getCanonicalType(Underlying);
3196 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003197 // We can get here with an alias template when the specialization contains
3198 // a pack expansion that does not match up with a parameter pack.
3199 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3200 "Caller must compute aliased type");
3201 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00003202 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3203 NumArgs);
3204 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003205
Douglas Gregora8e02e72009-07-28 23:00:59 +00003206 // Allocate the (non-canonical) template specialization type, but don't
3207 // try to unique it: these types typically have location information that
3208 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003209 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3210 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003211 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003212 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003213 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003214 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3215 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003216
Douglas Gregor8bf42052009-02-09 18:46:07 +00003217 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003218 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003219}
3220
Mike Stump11289f42009-09-09 15:08:12 +00003221QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003222ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3223 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00003224 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003225 assert(!Template.getAsDependentTemplateName() &&
3226 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003227
Douglas Gregore29139c2011-03-03 17:04:51 +00003228 // Look through qualified template names.
3229 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3230 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003231
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003232 // Build the canonical template specialization type.
3233 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003234 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003235 CanonArgs.reserve(NumArgs);
3236 for (unsigned I = 0; I != NumArgs; ++I)
3237 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3238
3239 // Determine whether this canonical template specialization type already
3240 // exists.
3241 llvm::FoldingSetNodeID ID;
3242 TemplateSpecializationType::Profile(ID, CanonTemplate,
3243 CanonArgs.data(), NumArgs, *this);
3244
3245 void *InsertPos = 0;
3246 TemplateSpecializationType *Spec
3247 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3248
3249 if (!Spec) {
3250 // Allocate a new canonical template specialization type.
3251 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3252 sizeof(TemplateArgument) * NumArgs),
3253 TypeAlignment);
3254 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3255 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003256 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003257 Types.push_back(Spec);
3258 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3259 }
3260
3261 assert(Spec->isDependentType() &&
3262 "Non-dependent template-id type must have a canonical type");
3263 return QualType(Spec, 0);
3264}
3265
3266QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003267ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3268 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003269 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003270 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003271 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003272
3273 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003274 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003275 if (T)
3276 return QualType(T, 0);
3277
Douglas Gregorc42075a2010-02-04 18:10:26 +00003278 QualType Canon = NamedType;
3279 if (!Canon.isCanonical()) {
3280 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003281 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3282 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003283 (void)CheckT;
3284 }
3285
Abramo Bagnara6150c882010-05-11 21:36:43 +00003286 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003287 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003288 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003289 return QualType(T, 0);
3290}
3291
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003292QualType
Jay Foad39c79802011-01-12 09:06:06 +00003293ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003294 llvm::FoldingSetNodeID ID;
3295 ParenType::Profile(ID, InnerType);
3296
3297 void *InsertPos = 0;
3298 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3299 if (T)
3300 return QualType(T, 0);
3301
3302 QualType Canon = InnerType;
3303 if (!Canon.isCanonical()) {
3304 Canon = getCanonicalType(InnerType);
3305 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3306 assert(!CheckT && "Paren canonical type broken");
3307 (void)CheckT;
3308 }
3309
3310 T = new (*this) ParenType(InnerType, Canon);
3311 Types.push_back(T);
3312 ParenTypes.InsertNode(T, InsertPos);
3313 return QualType(T, 0);
3314}
3315
Douglas Gregor02085352010-03-31 20:19:30 +00003316QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3317 NestedNameSpecifier *NNS,
3318 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003319 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003320 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
3321
3322 if (Canon.isNull()) {
3323 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00003324 ElaboratedTypeKeyword CanonKeyword = Keyword;
3325 if (Keyword == ETK_None)
3326 CanonKeyword = ETK_Typename;
3327
3328 if (CanonNNS != NNS || CanonKeyword != Keyword)
3329 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003330 }
3331
3332 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003333 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003334
3335 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003336 DependentNameType *T
3337 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003338 if (T)
3339 return QualType(T, 0);
3340
Douglas Gregor02085352010-03-31 20:19:30 +00003341 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003342 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003343 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003344 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003345}
3346
Mike Stump11289f42009-09-09 15:08:12 +00003347QualType
John McCallc392f372010-06-11 00:33:02 +00003348ASTContext::getDependentTemplateSpecializationType(
3349 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003350 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003351 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003352 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003353 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003354 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003355 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3356 ArgCopy.push_back(Args[I].getArgument());
3357 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3358 ArgCopy.size(),
3359 ArgCopy.data());
3360}
3361
3362QualType
3363ASTContext::getDependentTemplateSpecializationType(
3364 ElaboratedTypeKeyword Keyword,
3365 NestedNameSpecifier *NNS,
3366 const IdentifierInfo *Name,
3367 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00003368 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003369 assert((!NNS || NNS->isDependent()) &&
3370 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003371
Douglas Gregorc42075a2010-02-04 18:10:26 +00003372 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003373 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3374 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003375
3376 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00003377 DependentTemplateSpecializationType *T
3378 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003379 if (T)
3380 return QualType(T, 0);
3381
John McCallc392f372010-06-11 00:33:02 +00003382 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003383
John McCallc392f372010-06-11 00:33:02 +00003384 ElaboratedTypeKeyword CanonKeyword = Keyword;
3385 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3386
3387 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003388 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003389 for (unsigned I = 0; I != NumArgs; ++I) {
3390 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3391 if (!CanonArgs[I].structurallyEquals(Args[I]))
3392 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003393 }
3394
John McCallc392f372010-06-11 00:33:02 +00003395 QualType Canon;
3396 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3397 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3398 Name, NumArgs,
3399 CanonArgs.data());
3400
3401 // Find the insert position again.
3402 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3403 }
3404
3405 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3406 sizeof(TemplateArgument) * NumArgs),
3407 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003408 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00003409 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003410 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003411 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003412 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003413}
3414
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003415QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00003416 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003417 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003418 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003419
3420 assert(Pattern->containsUnexpandedParameterPack() &&
3421 "Pack expansions must expand one or more parameter packs");
3422 void *InsertPos = 0;
3423 PackExpansionType *T
3424 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3425 if (T)
3426 return QualType(T, 0);
3427
3428 QualType Canon;
3429 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003430 Canon = getCanonicalType(Pattern);
3431 // The canonical type might not contain an unexpanded parameter pack, if it
3432 // contains an alias template specialization which ignores one of its
3433 // parameters.
3434 if (Canon->containsUnexpandedParameterPack()) {
3435 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003436
Richard Smith68eea502012-07-16 00:20:35 +00003437 // Find the insert position again, in case we inserted an element into
3438 // PackExpansionTypes and invalidated our insert position.
3439 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3440 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003441 }
3442
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003443 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003444 Types.push_back(T);
3445 PackExpansionTypes.InsertNode(T, InsertPos);
3446 return QualType(T, 0);
3447}
3448
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003449/// CmpProtocolNames - Comparison predicate for sorting protocols
3450/// alphabetically.
3451static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3452 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00003453 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003454}
3455
John McCall8b07ec22010-05-15 11:32:37 +00003456static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00003457 unsigned NumProtocols) {
3458 if (NumProtocols == 0) return true;
3459
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003460 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3461 return false;
3462
John McCallfc93cf92009-10-22 22:37:11 +00003463 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003464 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3465 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003466 return false;
3467 return true;
3468}
3469
3470static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003471 unsigned &NumProtocols) {
3472 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00003473
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003474 // Sort protocols, keyed by name.
3475 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3476
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003477 // Canonicalize.
3478 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3479 Protocols[I] = Protocols[I]->getCanonicalDecl();
3480
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003481 // Remove duplicates.
3482 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3483 NumProtocols = ProtocolsEnd-Protocols;
3484}
3485
John McCall8b07ec22010-05-15 11:32:37 +00003486QualType ASTContext::getObjCObjectType(QualType BaseType,
3487 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003488 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00003489 // If the base type is an interface and there aren't any protocols
3490 // to add, then the interface type will do just fine.
3491 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3492 return BaseType;
3493
3494 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00003495 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00003496 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00003497 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00003498 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3499 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003500
John McCall8b07ec22010-05-15 11:32:37 +00003501 // Build the canonical type, which has the canonical base type and
3502 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00003503 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00003504 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3505 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3506 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003507 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00003508 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003509 unsigned UniqueCount = NumProtocols;
3510
John McCallfc93cf92009-10-22 22:37:11 +00003511 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00003512 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3513 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00003514 } else {
John McCall8b07ec22010-05-15 11:32:37 +00003515 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3516 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00003517 }
3518
3519 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00003520 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3521 }
3522
3523 unsigned Size = sizeof(ObjCObjectTypeImpl);
3524 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3525 void *Mem = Allocate(Size, TypeAlignment);
3526 ObjCObjectTypeImpl *T =
3527 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3528
3529 Types.push_back(T);
3530 ObjCObjectTypes.InsertNode(T, InsertPos);
3531 return QualType(T, 0);
3532}
3533
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003534/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
3535/// protocol list adopt all protocols in QT's qualified-id protocol
3536/// list.
3537bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
3538 ObjCInterfaceDecl *IC) {
3539 if (!QT->isObjCQualifiedIdType())
3540 return false;
3541
3542 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
3543 // If both the right and left sides have qualifiers.
3544 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3545 E = OPT->qual_end(); I != E; ++I) {
3546 ObjCProtocolDecl *Proto = *I;
3547 if (!IC->ClassImplementsProtocol(Proto, false))
3548 return false;
3549 }
3550 return true;
3551 }
3552 return false;
3553}
3554
3555/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
3556/// QT's qualified-id protocol list adopt all protocols in IDecl's list
3557/// of protocols.
3558bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
3559 ObjCInterfaceDecl *IDecl) {
3560 if (!QT->isObjCQualifiedIdType())
3561 return false;
3562 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
3563 if (!OPT)
3564 return false;
3565 if (!IDecl->hasDefinition())
3566 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003567 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
3568 CollectInheritedProtocols(IDecl, InheritedProtocols);
3569 if (InheritedProtocols.empty())
3570 return false;
3571
3572 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator PI =
3573 InheritedProtocols.begin(),
3574 E = InheritedProtocols.end(); PI != E; ++PI) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003575 // If both the right and left sides have qualifiers.
3576 bool Adopts = false;
3577 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3578 E = OPT->qual_end(); I != E; ++I) {
3579 ObjCProtocolDecl *Proto = *I;
3580 // return 'true' if '*PI' is in the inheritance hierarchy of Proto
3581 if ((Adopts = ProtocolCompatibleWithProtocol(*PI, Proto)))
3582 break;
3583 }
3584 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00003585 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003586 }
3587 return true;
3588}
3589
John McCall8b07ec22010-05-15 11:32:37 +00003590/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3591/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00003592QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00003593 llvm::FoldingSetNodeID ID;
3594 ObjCObjectPointerType::Profile(ID, ObjectT);
3595
3596 void *InsertPos = 0;
3597 if (ObjCObjectPointerType *QT =
3598 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3599 return QualType(QT, 0);
3600
3601 // Find the canonical object type.
3602 QualType Canonical;
3603 if (!ObjectT.isCanonical()) {
3604 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3605
3606 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00003607 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3608 }
3609
Douglas Gregorf85bee62010-02-08 22:59:26 +00003610 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00003611 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3612 ObjCObjectPointerType *QType =
3613 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00003614
Steve Narofffb4330f2009-06-17 22:40:22 +00003615 Types.push_back(QType);
3616 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00003617 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00003618}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003619
Douglas Gregor1c283312010-08-11 12:19:30 +00003620/// getObjCInterfaceType - Return the unique reference to the type for the
3621/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003622QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3623 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00003624 if (Decl->TypeForDecl)
3625 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003626
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003627 if (PrevDecl) {
3628 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3629 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3630 return QualType(PrevDecl->TypeForDecl, 0);
3631 }
3632
Douglas Gregor7671e532011-12-16 16:34:57 +00003633 // Prefer the definition, if there is one.
3634 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3635 Decl = Def;
3636
Douglas Gregor1c283312010-08-11 12:19:30 +00003637 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3638 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3639 Decl->TypeForDecl = T;
3640 Types.push_back(T);
3641 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00003642}
3643
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003644/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3645/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00003646/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00003647/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003648/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003649QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003650 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003651 if (tofExpr->isTypeDependent()) {
3652 llvm::FoldingSetNodeID ID;
3653 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003654
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003655 void *InsertPos = 0;
3656 DependentTypeOfExprType *Canon
3657 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3658 if (Canon) {
3659 // We already have a "canonical" version of an identical, dependent
3660 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00003661 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003662 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003663 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003664 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003665 Canon
3666 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00003667 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3668 toe = Canon;
3669 }
3670 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00003671 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00003672 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00003673 }
Steve Naroffa773cd52007-08-01 18:02:17 +00003674 Types.push_back(toe);
3675 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003676}
3677
Steve Naroffa773cd52007-08-01 18:02:17 +00003678/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3679/// TypeOfType AST's. The only motivation to unique these nodes would be
3680/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003681/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00003682/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00003683QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003684 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00003685 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00003686 Types.push_back(tot);
3687 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00003688}
3689
Anders Carlssonad6bd352009-06-24 21:24:56 +00003690
Anders Carlsson81df7b82009-06-24 19:06:50 +00003691/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3692/// DecltypeType AST's. The only motivation to unique these nodes would be
3693/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00003694/// an issue. This doesn't effect the type checker, since it operates
David Blaikie876657b2011-11-06 22:28:03 +00003695/// on canonical types (which are always unique).
Douglas Gregor81495f32012-02-12 18:42:33 +00003696QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00003697 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00003698
3699 // C++0x [temp.type]p2:
3700 // If an expression e involves a template parameter, decltype(e) denotes a
3701 // unique dependent type. Two such decltype-specifiers refer to the same
3702 // type only if their expressions are equivalent (14.5.6.1).
3703 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003704 llvm::FoldingSetNodeID ID;
3705 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00003706
Douglas Gregora21f6c32009-07-30 23:36:40 +00003707 void *InsertPos = 0;
3708 DependentDecltypeType *Canon
3709 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3710 if (Canon) {
3711 // We already have a "canonical" version of an equivalent, dependent
3712 // decltype type. Use that as our canonical type.
Richard Smithef8bf432012-08-13 20:08:14 +00003713 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
Douglas Gregora21f6c32009-07-30 23:36:40 +00003714 QualType((DecltypeType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003715 } else {
Douglas Gregora21f6c32009-07-30 23:36:40 +00003716 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00003717 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00003718 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3719 dt = Canon;
3720 }
3721 } else {
Douglas Gregor81495f32012-02-12 18:42:33 +00003722 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3723 getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00003724 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00003725 Types.push_back(dt);
3726 return QualType(dt, 0);
3727}
3728
Alexis Hunte852b102011-05-24 22:41:36 +00003729/// getUnaryTransformationType - We don't unique these, since the memory
3730/// savings are minimal and these are rare.
3731QualType ASTContext::getUnaryTransformType(QualType BaseType,
3732 QualType UnderlyingType,
3733 UnaryTransformType::UTTKind Kind)
3734 const {
3735 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00003736 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3737 Kind,
3738 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00003739 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00003740 Types.push_back(Ty);
3741 return QualType(Ty, 0);
3742}
3743
Richard Smith2a7d4812013-05-04 07:00:32 +00003744/// getAutoType - Return the uniqued reference to the 'auto' type which has been
3745/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3746/// canonical deduced-but-dependent 'auto' type.
3747QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003748 bool IsDependent) const {
3749 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00003750 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003751
Richard Smith2a7d4812013-05-04 07:00:32 +00003752 // Look in the folding set for an existing type.
Richard Smithb2bc2e62011-02-21 20:05:19 +00003753 void *InsertPos = 0;
Richard Smith2a7d4812013-05-04 07:00:32 +00003754 llvm::FoldingSetNodeID ID;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003755 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00003756 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3757 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003758
Richard Smith74aeef52013-04-26 16:15:35 +00003759 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smith27d807c2013-04-30 13:56:41 +00003760 IsDecltypeAuto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003761 IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00003762 Types.push_back(AT);
3763 if (InsertPos)
3764 AutoTypes.InsertNode(AT, InsertPos);
3765 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003766}
3767
Eli Friedman0dfb8892011-10-06 23:00:33 +00003768/// getAtomicType - Return the uniqued reference to the atomic type for
3769/// the given value type.
3770QualType ASTContext::getAtomicType(QualType T) const {
3771 // Unique pointers, to guarantee there is only one pointer of a particular
3772 // structure.
3773 llvm::FoldingSetNodeID ID;
3774 AtomicType::Profile(ID, T);
3775
3776 void *InsertPos = 0;
3777 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3778 return QualType(AT, 0);
3779
3780 // If the atomic value type isn't canonical, this won't be a canonical type
3781 // either, so fill in the canonical type field.
3782 QualType Canonical;
3783 if (!T.isCanonical()) {
3784 Canonical = getAtomicType(getCanonicalType(T));
3785
3786 // Get the new insert position for the node we care about.
3787 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3788 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3789 }
3790 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3791 Types.push_back(New);
3792 AtomicTypes.InsertNode(New, InsertPos);
3793 return QualType(New, 0);
3794}
3795
Richard Smith02e85f32011-04-14 22:09:26 +00003796/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3797QualType ASTContext::getAutoDeductType() const {
3798 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00003799 AutoDeductTy = QualType(
3800 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003801 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00003802 0);
Richard Smith02e85f32011-04-14 22:09:26 +00003803 return AutoDeductTy;
3804}
3805
3806/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3807QualType ASTContext::getAutoRRefDeductType() const {
3808 if (AutoRRefDeductTy.isNull())
3809 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3810 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3811 return AutoRRefDeductTy;
3812}
3813
Chris Lattnerfb072462007-01-23 05:45:31 +00003814/// getTagDeclType - Return the unique reference to the type for the
3815/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003816QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003817 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003818 // FIXME: What is the design on getTagDeclType when it requires casting
3819 // away const? mutable?
3820 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003821}
3822
Mike Stump11289f42009-09-09 15:08:12 +00003823/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3824/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3825/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003826CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003827 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003828}
Chris Lattnerfb072462007-01-23 05:45:31 +00003829
Hans Wennborg27541db2011-10-27 08:29:09 +00003830/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3831CanQualType ASTContext::getIntMaxType() const {
3832 return getFromTargetType(Target->getIntMaxType());
3833}
3834
3835/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3836CanQualType ASTContext::getUIntMaxType() const {
3837 return getFromTargetType(Target->getUIntMaxType());
3838}
3839
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003840/// getSignedWCharType - Return the type of "signed wchar_t".
3841/// Used when in C++, as a GCC extension.
3842QualType ASTContext::getSignedWCharType() const {
3843 // FIXME: derive from "Target" ?
3844 return WCharTy;
3845}
3846
3847/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3848/// Used when in C++, as a GCC extension.
3849QualType ASTContext::getUnsignedWCharType() const {
3850 // FIXME: derive from "Target" ?
3851 return UnsignedIntTy;
3852}
3853
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00003854QualType ASTContext::getIntPtrType() const {
3855 return getFromTargetType(Target->getIntPtrType());
3856}
3857
3858QualType ASTContext::getUIntPtrType() const {
3859 return getCorrespondingUnsignedType(getIntPtrType());
3860}
3861
Hans Wennborg27541db2011-10-27 08:29:09 +00003862/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003863/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3864QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003865 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003866}
3867
Eli Friedman4e91899e2012-11-27 02:58:24 +00003868/// \brief Return the unique type for "pid_t" defined in
3869/// <sys/types.h>. We need this to compute the correct type for vfork().
3870QualType ASTContext::getProcessIDType() const {
3871 return getFromTargetType(Target->getProcessIDType());
3872}
3873
Chris Lattnera21ad802008-04-02 05:18:44 +00003874//===----------------------------------------------------------------------===//
3875// Type Operators
3876//===----------------------------------------------------------------------===//
3877
Jay Foad39c79802011-01-12 09:06:06 +00003878CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003879 // Push qualifiers into arrays, and then discard any remaining
3880 // qualifiers.
3881 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003882 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003883 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003884 QualType Result;
3885 if (isa<ArrayType>(Ty)) {
3886 Result = getArrayDecayedType(QualType(Ty,0));
3887 } else if (isa<FunctionType>(Ty)) {
3888 Result = getPointerType(QualType(Ty, 0));
3889 } else {
3890 Result = QualType(Ty, 0);
3891 }
3892
3893 return CanQualType::CreateUnsafe(Result);
3894}
3895
John McCall6c9dd522011-01-18 07:41:22 +00003896QualType ASTContext::getUnqualifiedArrayType(QualType type,
3897 Qualifiers &quals) {
3898 SplitQualType splitType = type.getSplitUnqualifiedType();
3899
3900 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3901 // the unqualified desugared type and then drops it on the floor.
3902 // We then have to strip that sugar back off with
3903 // getUnqualifiedDesugaredType(), which is silly.
3904 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003905 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003906
3907 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003908 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003909 quals = splitType.Quals;
3910 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003911 }
3912
John McCall6c9dd522011-01-18 07:41:22 +00003913 // Otherwise, recurse on the array's element type.
3914 QualType elementType = AT->getElementType();
3915 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3916
3917 // If that didn't change the element type, AT has no qualifiers, so we
3918 // can just use the results in splitType.
3919 if (elementType == unqualElementType) {
3920 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00003921 quals = splitType.Quals;
3922 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00003923 }
3924
3925 // Otherwise, add in the qualifiers from the outermost type, then
3926 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00003927 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003928
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003929 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003930 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003931 CAT->getSizeModifier(), 0);
3932 }
3933
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003934 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003935 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003936 }
3937
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003938 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003939 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003940 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003941 VAT->getSizeModifier(),
3942 VAT->getIndexTypeCVRQualifiers(),
3943 VAT->getBracketsRange());
3944 }
3945
3946 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003947 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003948 DSAT->getSizeModifier(), 0,
3949 SourceRange());
3950}
3951
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003952/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3953/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3954/// they point to and return true. If T1 and T2 aren't pointer types
3955/// or pointer-to-member types, or if they are not similar at this
3956/// level, returns false and leaves T1 and T2 unchanged. Top-level
3957/// qualifiers on T1 and T2 are ignored. This function will typically
3958/// be called in a loop that successively "unwraps" pointer and
3959/// pointer-to-member types to compare them at each level.
3960bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3961 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3962 *T2PtrType = T2->getAs<PointerType>();
3963 if (T1PtrType && T2PtrType) {
3964 T1 = T1PtrType->getPointeeType();
3965 T2 = T2PtrType->getPointeeType();
3966 return true;
3967 }
3968
3969 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3970 *T2MPType = T2->getAs<MemberPointerType>();
3971 if (T1MPType && T2MPType &&
3972 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3973 QualType(T2MPType->getClass(), 0))) {
3974 T1 = T1MPType->getPointeeType();
3975 T2 = T2MPType->getPointeeType();
3976 return true;
3977 }
3978
David Blaikiebbafb8a2012-03-11 07:00:24 +00003979 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003980 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3981 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3982 if (T1OPType && T2OPType) {
3983 T1 = T1OPType->getPointeeType();
3984 T2 = T2OPType->getPointeeType();
3985 return true;
3986 }
3987 }
3988
3989 // FIXME: Block pointers, too?
3990
3991 return false;
3992}
3993
Jay Foad39c79802011-01-12 09:06:06 +00003994DeclarationNameInfo
3995ASTContext::getNameForTemplate(TemplateName Name,
3996 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003997 switch (Name.getKind()) {
3998 case TemplateName::QualifiedTemplate:
3999 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004000 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00004001 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4002 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004003
John McCalld9dfe3a2011-06-30 08:33:18 +00004004 case TemplateName::OverloadedTemplate: {
4005 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4006 // DNInfo work in progress: CHECKME: what about DNLoc?
4007 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4008 }
4009
4010 case TemplateName::DependentTemplate: {
4011 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004012 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00004013 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004014 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4015 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00004016 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004017 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4018 // DNInfo work in progress: FIXME: source locations?
4019 DeclarationNameLoc DNLoc;
4020 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4021 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4022 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00004023 }
4024 }
4025
John McCalld9dfe3a2011-06-30 08:33:18 +00004026 case TemplateName::SubstTemplateTemplateParm: {
4027 SubstTemplateTemplateParmStorage *subst
4028 = Name.getAsSubstTemplateTemplateParm();
4029 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4030 NameLoc);
4031 }
4032
4033 case TemplateName::SubstTemplateTemplateParmPack: {
4034 SubstTemplateTemplateParmPackStorage *subst
4035 = Name.getAsSubstTemplateTemplateParmPack();
4036 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4037 NameLoc);
4038 }
4039 }
4040
4041 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00004042}
4043
Jay Foad39c79802011-01-12 09:06:06 +00004044TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004045 switch (Name.getKind()) {
4046 case TemplateName::QualifiedTemplate:
4047 case TemplateName::Template: {
4048 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004049 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00004050 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004051 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4052
4053 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004054 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004055 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00004056
John McCalld9dfe3a2011-06-30 08:33:18 +00004057 case TemplateName::OverloadedTemplate:
4058 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00004059
John McCalld9dfe3a2011-06-30 08:33:18 +00004060 case TemplateName::DependentTemplate: {
4061 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4062 assert(DTN && "Non-dependent template names must refer to template decls.");
4063 return DTN->CanonicalTemplateName;
4064 }
4065
4066 case TemplateName::SubstTemplateTemplateParm: {
4067 SubstTemplateTemplateParmStorage *subst
4068 = Name.getAsSubstTemplateTemplateParm();
4069 return getCanonicalTemplateName(subst->getReplacement());
4070 }
4071
4072 case TemplateName::SubstTemplateTemplateParmPack: {
4073 SubstTemplateTemplateParmPackStorage *subst
4074 = Name.getAsSubstTemplateTemplateParmPack();
4075 TemplateTemplateParmDecl *canonParameter
4076 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4077 TemplateArgument canonArgPack
4078 = getCanonicalTemplateArgument(subst->getArgumentPack());
4079 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4080 }
4081 }
4082
4083 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00004084}
4085
Douglas Gregoradee3e32009-11-11 23:06:43 +00004086bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4087 X = getCanonicalTemplateName(X);
4088 Y = getCanonicalTemplateName(Y);
4089 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4090}
4091
Mike Stump11289f42009-09-09 15:08:12 +00004092TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00004093ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00004094 switch (Arg.getKind()) {
4095 case TemplateArgument::Null:
4096 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004097
Douglas Gregora8e02e72009-07-28 23:00:59 +00004098 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00004099 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004100
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004101 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00004102 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
4103 return TemplateArgument(D, Arg.isDeclForReferenceParam());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004104 }
Mike Stump11289f42009-09-09 15:08:12 +00004105
Eli Friedmanb826a002012-09-26 02:36:12 +00004106 case TemplateArgument::NullPtr:
4107 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4108 /*isNullPtr*/true);
4109
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004110 case TemplateArgument::Template:
4111 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004112
4113 case TemplateArgument::TemplateExpansion:
4114 return TemplateArgument(getCanonicalTemplateName(
4115 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00004116 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004117
Douglas Gregora8e02e72009-07-28 23:00:59 +00004118 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004119 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00004120
Douglas Gregora8e02e72009-07-28 23:00:59 +00004121 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00004122 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00004123
Douglas Gregora8e02e72009-07-28 23:00:59 +00004124 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00004125 if (Arg.pack_size() == 0)
4126 return Arg;
4127
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004128 TemplateArgument *CanonArgs
4129 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00004130 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004131 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00004132 AEnd = Arg.pack_end();
4133 A != AEnd; (void)++A, ++Idx)
4134 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00004135
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004136 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00004137 }
4138 }
4139
4140 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00004141 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00004142}
4143
Douglas Gregor333489b2009-03-27 23:10:48 +00004144NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00004145ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00004146 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00004147 return 0;
4148
4149 switch (NNS->getKind()) {
4150 case NestedNameSpecifier::Identifier:
4151 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00004152 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00004153 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4154 NNS->getAsIdentifier());
4155
4156 case NestedNameSpecifier::Namespace:
4157 // A namespace is canonical; build a nested-name-specifier with
4158 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004159 return NestedNameSpecifier::Create(*this, 0,
4160 NNS->getAsNamespace()->getOriginalNamespace());
4161
4162 case NestedNameSpecifier::NamespaceAlias:
4163 // A namespace is canonical; build a nested-name-specifier with
4164 // this namespace and no prefix.
4165 return NestedNameSpecifier::Create(*this, 0,
4166 NNS->getAsNamespaceAlias()->getNamespace()
4167 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00004168
4169 case NestedNameSpecifier::TypeSpec:
4170 case NestedNameSpecifier::TypeSpecWithTemplate: {
4171 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004172
4173 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4174 // break it apart into its prefix and identifier, then reconsititute those
4175 // as the canonical nested-name-specifier. This is required to canonicalize
4176 // a dependent nested-name-specifier involving typedefs of dependent-name
4177 // types, e.g.,
4178 // typedef typename T::type T1;
4179 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00004180 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4181 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00004182 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004183
Eli Friedman5358a0a2012-03-03 04:09:56 +00004184 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4185 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4186 // first place?
John McCall33ddac02011-01-19 10:06:00 +00004187 return NestedNameSpecifier::Create(*this, 0, false,
4188 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00004189 }
4190
4191 case NestedNameSpecifier::Global:
4192 // The global specifier is canonical and unique.
4193 return NNS;
4194 }
4195
David Blaikie8a40f702012-01-17 06:56:22 +00004196 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00004197}
4198
Chris Lattner7adf0762008-08-04 07:31:14 +00004199
Jay Foad39c79802011-01-12 09:06:06 +00004200const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004201 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004202 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00004203 // Handle the common positive case fast.
4204 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4205 return AT;
4206 }
Mike Stump11289f42009-09-09 15:08:12 +00004207
John McCall8ccfcb52009-09-24 19:53:00 +00004208 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00004209 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00004210 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004211
John McCall8ccfcb52009-09-24 19:53:00 +00004212 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00004213 // implements C99 6.7.3p8: "If the specification of an array type includes
4214 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00004215
Chris Lattner7adf0762008-08-04 07:31:14 +00004216 // If we get here, we either have type qualifiers on the type, or we have
4217 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00004218 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00004219
John McCall33ddac02011-01-19 10:06:00 +00004220 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004221 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00004222
Chris Lattner7adf0762008-08-04 07:31:14 +00004223 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00004224 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall33ddac02011-01-19 10:06:00 +00004225 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00004226 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00004227
Chris Lattner7adf0762008-08-04 07:31:14 +00004228 // Otherwise, we have an array and we have qualifiers on it. Push the
4229 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00004230 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00004231
Chris Lattner7adf0762008-08-04 07:31:14 +00004232 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4233 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4234 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004235 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00004236 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4237 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4238 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004239 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00004240
Mike Stump11289f42009-09-09 15:08:12 +00004241 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00004242 = dyn_cast<DependentSizedArrayType>(ATy))
4243 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00004244 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004245 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00004246 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004247 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004248 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00004249
Chris Lattner7adf0762008-08-04 07:31:14 +00004250 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00004251 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004252 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00004253 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004254 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004255 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00004256}
4257
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004258QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00004259 if (T->isArrayType() || T->isFunctionType())
4260 return getDecayedType(T);
4261 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00004262}
4263
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004264QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004265 T = getVariableArrayDecayedType(T);
4266 T = getAdjustedParameterType(T);
4267 return T.getUnqualifiedType();
4268}
4269
Chris Lattnera21ad802008-04-02 05:18:44 +00004270/// getArrayDecayedType - Return the properly qualified result of decaying the
4271/// specified array type to a pointer. This operation is non-trivial when
4272/// handling typedefs etc. The canonical type of "T" must be an array type,
4273/// this returns a pointer to a properly qualified element of the array.
4274///
4275/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004276QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004277 // Get the element type with 'getAsArrayType' so that we don't lose any
4278 // typedefs in the element type of the array. This also handles propagation
4279 // of type qualifiers from the array type into the element type if present
4280 // (C99 6.7.3p8).
4281 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4282 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004283
Chris Lattner7adf0762008-08-04 07:31:14 +00004284 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004285
4286 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00004287 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00004288}
4289
John McCall33ddac02011-01-19 10:06:00 +00004290QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4291 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00004292}
4293
John McCall33ddac02011-01-19 10:06:00 +00004294QualType ASTContext::getBaseElementType(QualType type) const {
4295 Qualifiers qs;
4296 while (true) {
4297 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004298 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00004299 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00004300
John McCall33ddac02011-01-19 10:06:00 +00004301 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00004302 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00004303 }
Mike Stump11289f42009-09-09 15:08:12 +00004304
John McCall33ddac02011-01-19 10:06:00 +00004305 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00004306}
4307
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004308/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00004309uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004310ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4311 uint64_t ElementCount = 1;
4312 do {
4313 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00004314 CA = dyn_cast_or_null<ConstantArrayType>(
4315 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00004316 } while (CA);
4317 return ElementCount;
4318}
4319
Steve Naroff0af91202007-04-27 21:51:21 +00004320/// getFloatingRank - Return a relative rank for floating point types.
4321/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00004322static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00004323 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00004324 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00004325
John McCall9dd450b2009-09-21 23:43:11 +00004326 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4327 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004328 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004329 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00004330 case BuiltinType::Float: return FloatRank;
4331 case BuiltinType::Double: return DoubleRank;
4332 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00004333 }
4334}
4335
Mike Stump11289f42009-09-09 15:08:12 +00004336/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4337/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00004338/// 'typeDomain' is a real floating point or complex type.
4339/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004340QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4341 QualType Domain) const {
4342 FloatingRank EltRank = getFloatingRank(Size);
4343 if (Domain->isComplexType()) {
4344 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00004345 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00004346 case FloatRank: return FloatComplexTy;
4347 case DoubleRank: return DoubleComplexTy;
4348 case LongDoubleRank: return LongDoubleComplexTy;
4349 }
Steve Naroff0af91202007-04-27 21:51:21 +00004350 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004351
4352 assert(Domain->isRealFloatingType() && "Unknown domain!");
4353 switch (EltRank) {
Joey Goulydd7f4562013-01-23 11:56:20 +00004354 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00004355 case FloatRank: return FloatTy;
4356 case DoubleRank: return DoubleTy;
4357 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00004358 }
David Blaikief47fa302012-01-17 02:30:50 +00004359 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00004360}
4361
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004362/// getFloatingTypeOrder - Compare the rank of the two specified floating
4363/// point types, ignoring the domain of the type (i.e. 'double' ==
4364/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004365/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004366int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00004367 FloatingRank LHSR = getFloatingRank(LHS);
4368 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004369
Chris Lattnerb90739d2008-04-06 23:38:49 +00004370 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004371 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00004372 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00004373 return 1;
4374 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00004375}
4376
Chris Lattner76a00cf2008-04-06 22:59:24 +00004377/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4378/// routine will assert if passed a built-in type that isn't an integer or enum,
4379/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00004380unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00004381 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00004382
Chris Lattner76a00cf2008-04-06 22:59:24 +00004383 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004384 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004385 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004386 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004387 case BuiltinType::Char_S:
4388 case BuiltinType::Char_U:
4389 case BuiltinType::SChar:
4390 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004391 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004392 case BuiltinType::Short:
4393 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004394 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004395 case BuiltinType::Int:
4396 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004397 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004398 case BuiltinType::Long:
4399 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004400 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004401 case BuiltinType::LongLong:
4402 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00004403 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00004404 case BuiltinType::Int128:
4405 case BuiltinType::UInt128:
4406 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00004407 }
4408}
4409
Eli Friedman629ffb92009-08-20 04:21:42 +00004410/// \brief Whether this is a promotable bitfield reference according
4411/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4412///
4413/// \returns the type this bit-field will promote to, or NULL if no
4414/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00004415QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00004416 if (E->isTypeDependent() || E->isValueDependent())
4417 return QualType();
4418
John McCalld25db7e2013-05-06 21:39:12 +00004419 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00004420 if (!Field)
4421 return QualType();
4422
4423 QualType FT = Field->getType();
4424
Richard Smithcaf33902011-10-10 18:28:20 +00004425 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00004426 uint64_t IntSize = getTypeSize(IntTy);
4427 // GCC extension compatibility: if the bit-field size is less than or equal
4428 // to the size of int, it gets promoted no matter what its type is.
4429 // For instance, unsigned long bf : 4 gets promoted to signed int.
4430 if (BitWidth < IntSize)
4431 return IntTy;
4432
4433 if (BitWidth == IntSize)
4434 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4435
4436 // Types bigger than int are not subject to promotions, and therefore act
4437 // like the base type.
4438 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4439 // is ridiculous.
4440 return QualType();
4441}
4442
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004443/// getPromotedIntegerType - Returns the type that Promotable will
4444/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4445/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00004446QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004447 assert(!Promotable.isNull());
4448 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00004449 if (const EnumType *ET = Promotable->getAs<EnumType>())
4450 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00004451
4452 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4453 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4454 // (3.9.1) can be converted to a prvalue of the first of the following
4455 // types that can represent all the values of its underlying type:
4456 // int, unsigned int, long int, unsigned long int, long long int, or
4457 // unsigned long long int [...]
4458 // FIXME: Is there some better way to compute this?
4459 if (BT->getKind() == BuiltinType::WChar_S ||
4460 BT->getKind() == BuiltinType::WChar_U ||
4461 BT->getKind() == BuiltinType::Char16 ||
4462 BT->getKind() == BuiltinType::Char32) {
4463 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4464 uint64_t FromSize = getTypeSize(BT);
4465 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4466 LongLongTy, UnsignedLongLongTy };
4467 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4468 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4469 if (FromSize < ToSize ||
4470 (FromSize == ToSize &&
4471 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4472 return PromoteTypes[Idx];
4473 }
4474 llvm_unreachable("char type should fit into long long");
4475 }
4476 }
4477
4478 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004479 if (Promotable->isSignedIntegerType())
4480 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00004481 uint64_t PromotableSize = getIntWidth(Promotable);
4482 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004483 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4484 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4485}
4486
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004487/// \brief Recurses in pointer/array types until it finds an objc retainable
4488/// type and returns its ownership.
4489Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4490 while (!T.isNull()) {
4491 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4492 return T.getObjCLifetime();
4493 if (T->isArrayType())
4494 T = getBaseElementType(T);
4495 else if (const PointerType *PT = T->getAs<PointerType>())
4496 T = PT->getPointeeType();
4497 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00004498 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00004499 else
4500 break;
4501 }
4502
4503 return Qualifiers::OCL_None;
4504}
4505
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004506static const Type *getIntegerTypeForEnum(const EnumType *ET) {
4507 // Incomplete enum types are not treated as integer types.
4508 // FIXME: In C++, enum types are never integer types.
4509 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
4510 return ET->getDecl()->getIntegerType().getTypePtr();
4511 return NULL;
4512}
4513
Mike Stump11289f42009-09-09 15:08:12 +00004514/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004515/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00004516/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00004517int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00004518 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4519 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00004520
4521 // Unwrap enums to their underlying type.
4522 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
4523 LHSC = getIntegerTypeForEnum(ET);
4524 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
4525 RHSC = getIntegerTypeForEnum(ET);
4526
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004527 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004528
Chris Lattner76a00cf2008-04-06 22:59:24 +00004529 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4530 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00004531
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004532 unsigned LHSRank = getIntegerRank(LHSC);
4533 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00004534
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004535 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4536 if (LHSRank == RHSRank) return 0;
4537 return LHSRank > RHSRank ? 1 : -1;
4538 }
Mike Stump11289f42009-09-09 15:08:12 +00004539
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004540 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4541 if (LHSUnsigned) {
4542 // If the unsigned [LHS] type is larger, return it.
4543 if (LHSRank >= RHSRank)
4544 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00004545
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004546 // If the signed type can represent all values of the unsigned type, it
4547 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004548 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004549 return -1;
4550 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00004551
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004552 // If the unsigned [RHS] type is larger, return it.
4553 if (RHSRank >= LHSRank)
4554 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00004555
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004556 // If the signed type can represent all values of the unsigned type, it
4557 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00004558 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00004559 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00004560}
Anders Carlsson98f07902007-08-17 05:31:46 +00004561
Mike Stump11289f42009-09-09 15:08:12 +00004562// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00004563QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00004564 if (!CFConstantStringTypeDecl) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004565 CFConstantStringTypeDecl = buildImplicitRecord("NSConstantString");
John McCallae580fe2010-02-05 01:33:36 +00004566 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00004567
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004568 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00004569
Anders Carlsson98f07902007-08-17 05:31:46 +00004570 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00004571 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00004572 // int flags;
4573 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00004574 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00004575 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00004576 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00004577 FieldTypes[3] = LongTy;
4578
Anders Carlsson98f07902007-08-17 05:31:46 +00004579 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00004580 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00004581 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004582 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00004583 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00004584 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00004585 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00004586 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004587 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004588 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004589 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00004590 }
4591
Douglas Gregord5058122010-02-11 01:19:42 +00004592 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00004593 }
Mike Stump11289f42009-09-09 15:08:12 +00004594
Anders Carlsson98f07902007-08-17 05:31:46 +00004595 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00004596}
Anders Carlsson87c149b2007-10-11 01:00:40 +00004597
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004598QualType ASTContext::getObjCSuperType() const {
4599 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004600 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00004601 TUDecl->addDecl(ObjCSuperTypeDecl);
4602 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4603 }
4604 return ObjCSuperType;
4605}
4606
Douglas Gregor512b0772009-04-23 22:29:11 +00004607void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004608 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00004609 assert(Rec && "Invalid CFConstantStringType");
4610 CFConstantStringTypeDecl = Rec->getDecl();
4611}
4612
Jay Foad39c79802011-01-12 09:06:06 +00004613QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00004614 if (BlockDescriptorType)
4615 return getTagDeclType(BlockDescriptorType);
4616
Alp Toker2dea15b2013-12-17 01:22:38 +00004617 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004618 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004619 RD = buildImplicitRecord("__block_descriptor");
4620 RD->startDefinition();
4621
Mike Stumpd0153282009-10-20 02:12:22 +00004622 QualType FieldTypes[] = {
4623 UnsignedLongTy,
4624 UnsignedLongTy,
4625 };
4626
Craig Topperd6d31ac2013-07-15 08:24:27 +00004627 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00004628 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004629 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00004630 };
4631
4632 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004633 FieldDecl *Field = FieldDecl::Create(
4634 *this, RD, SourceLocation(), SourceLocation(),
4635 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/0,
4636 /*BitWidth=*/0, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004637 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004638 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00004639 }
4640
Alp Toker2dea15b2013-12-17 01:22:38 +00004641 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00004642
Alp Toker2dea15b2013-12-17 01:22:38 +00004643 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00004644
4645 return getTagDeclType(BlockDescriptorType);
4646}
4647
Jay Foad39c79802011-01-12 09:06:06 +00004648QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004649 if (BlockDescriptorExtendedType)
4650 return getTagDeclType(BlockDescriptorExtendedType);
4651
Alp Toker2dea15b2013-12-17 01:22:38 +00004652 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004653 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00004654 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
4655 RD->startDefinition();
4656
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004657 QualType FieldTypes[] = {
4658 UnsignedLongTy,
4659 UnsignedLongTy,
4660 getPointerType(VoidPtrTy),
4661 getPointerType(VoidPtrTy)
4662 };
4663
Craig Topperd6d31ac2013-07-15 08:24:27 +00004664 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004665 "reserved",
4666 "Size",
4667 "CopyFuncPtr",
4668 "DestroyFuncPtr"
4669 };
4670
4671 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004672 FieldDecl *Field = FieldDecl::Create(
4673 *this, RD, SourceLocation(), SourceLocation(),
4674 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/0,
4675 /*BitWidth=*/0,
4676 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00004677 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00004678 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004679 }
4680
Alp Toker2dea15b2013-12-17 01:22:38 +00004681 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004682
Alp Toker2dea15b2013-12-17 01:22:38 +00004683 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00004684 return getTagDeclType(BlockDescriptorExtendedType);
4685}
4686
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004687/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4688/// requires copy/dispose. Note that this must match the logic
4689/// in buildByrefHelpers.
4690bool ASTContext::BlockRequiresCopying(QualType Ty,
4691 const VarDecl *D) {
4692 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4693 const Expr *copyExpr = getBlockVarCopyInits(D);
4694 if (!copyExpr && record->hasTrivialDestructor()) return false;
4695
Mike Stump94967902009-10-21 18:16:27 +00004696 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00004697 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004698
4699 if (!Ty->isObjCRetainableType()) return false;
4700
4701 Qualifiers qs = Ty.getQualifiers();
4702
4703 // If we have lifetime, that dominates.
4704 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4705 assert(getLangOpts().ObjCAutoRefCount);
4706
4707 switch (lifetime) {
4708 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4709
4710 // These are just bits as far as the runtime is concerned.
4711 case Qualifiers::OCL_ExplicitNone:
4712 case Qualifiers::OCL_Autoreleasing:
4713 return false;
4714
4715 // Tell the runtime that this is ARC __weak, called by the
4716 // byref routines.
4717 case Qualifiers::OCL_Weak:
4718 // ARC __strong __block variables need to be retained.
4719 case Qualifiers::OCL_Strong:
4720 return true;
4721 }
4722 llvm_unreachable("fell out of lifetime switch!");
4723 }
4724 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4725 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00004726}
4727
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004728bool ASTContext::getByrefLifetime(QualType Ty,
4729 Qualifiers::ObjCLifetime &LifeTime,
4730 bool &HasByrefExtendedLayout) const {
4731
4732 if (!getLangOpts().ObjC1 ||
4733 getLangOpts().getGC() != LangOptions::NonGC)
4734 return false;
4735
4736 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00004737 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00004738 HasByrefExtendedLayout = true;
4739 LifeTime = Qualifiers::OCL_None;
4740 }
4741 else if (getLangOpts().ObjCAutoRefCount)
4742 LifeTime = Ty.getObjCLifetime();
4743 // MRR.
4744 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4745 LifeTime = Qualifiers::OCL_ExplicitNone;
4746 else
4747 LifeTime = Qualifiers::OCL_None;
4748 return true;
4749}
4750
Douglas Gregorbab8a962011-09-08 01:46:34 +00004751TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4752 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00004753 ObjCInstanceTypeDecl =
4754 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00004755 return ObjCInstanceTypeDecl;
4756}
4757
Anders Carlsson18acd442007-10-29 06:33:42 +00004758// This returns true if a type has been typedefed to BOOL:
4759// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004760static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004761 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004762 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4763 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004764
Anders Carlssond8499822007-10-29 05:01:08 +00004765 return false;
4766}
4767
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004768/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004769/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004770CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004771 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4772 return CharUnits::Zero();
4773
Ken Dyck40775002010-01-11 17:06:35 +00004774 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004775
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004776 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004777 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004778 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004779 // Treat arrays as pointers, since that's how they're passed in.
4780 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004781 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004782 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004783}
4784
4785static inline
4786std::string charUnitsToString(const CharUnits &CU) {
4787 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004788}
4789
John McCall351762c2011-02-07 10:33:21 +00004790/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004791/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004792std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4793 std::string S;
4794
David Chisnall950a9512009-11-17 19:33:30 +00004795 const BlockDecl *Decl = Expr->getBlockDecl();
4796 QualType BlockTy =
4797 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4798 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004799 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00004800 getObjCEncodingForMethodParameter(
4801 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
4802 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004803 else
Alp Toker314cc812014-01-25 16:55:45 +00004804 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00004805 // Compute size of all parameters.
4806 // Start with computing size of a pointer in number of bytes.
4807 // FIXME: There might(should) be a better way of doing this computation!
4808 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004809 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4810 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00004811 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00004812 E = Decl->param_end(); PI != E; ++PI) {
4813 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004814 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00004815 if (sz.isZero())
4816 continue;
Ken Dyck40775002010-01-11 17:06:35 +00004817 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004818 ParmOffset += sz;
4819 }
4820 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004821 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004822 // Block pointer and offset.
4823 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004824
4825 // Argument types.
4826 ParmOffset = PtrSize;
4827 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4828 Decl->param_end(); PI != E; ++PI) {
4829 ParmVarDecl *PVDecl = *PI;
4830 QualType PType = PVDecl->getOriginalType();
4831 if (const ArrayType *AT =
4832 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4833 // Use array's original type only if it has known number of
4834 // elements.
4835 if (!isa<ConstantArrayType>(AT))
4836 PType = PVDecl->getType();
4837 } else if (PType->isFunctionType())
4838 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00004839 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00004840 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4841 S, true /*Extended*/);
4842 else
4843 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004844 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004845 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004846 }
John McCall351762c2011-02-07 10:33:21 +00004847
4848 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004849}
4850
Douglas Gregora9d84932011-05-27 01:19:52 +00004851bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004852 std::string& S) {
4853 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00004854 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00004855 CharUnits ParmOffset;
4856 // Compute size of all parameters.
4857 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4858 E = Decl->param_end(); PI != E; ++PI) {
4859 QualType PType = (*PI)->getType();
4860 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004861 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004862 continue;
4863
David Chisnall50e4eba2010-12-30 14:05:53 +00004864 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004865 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004866 ParmOffset += sz;
4867 }
4868 S += charUnitsToString(ParmOffset);
4869 ParmOffset = CharUnits::Zero();
4870
4871 // Argument types.
4872 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4873 E = Decl->param_end(); PI != E; ++PI) {
4874 ParmVarDecl *PVDecl = *PI;
4875 QualType PType = PVDecl->getOriginalType();
4876 if (const ArrayType *AT =
4877 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4878 // Use array's original type only if it has known number of
4879 // elements.
4880 if (!isa<ConstantArrayType>(AT))
4881 PType = PVDecl->getType();
4882 } else if (PType->isFunctionType())
4883 PType = PVDecl->getType();
4884 getObjCEncodingForType(PType, S);
4885 S += charUnitsToString(ParmOffset);
4886 ParmOffset += getObjCEncodingTypeSize(PType);
4887 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004888
4889 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004890}
4891
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004892/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4893/// method parameter or return type. If Extended, include class names and
4894/// block object types.
4895void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4896 QualType T, std::string& S,
4897 bool Extended) const {
4898 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4899 getObjCEncodingForTypeQualifier(QT, S);
4900 // Encode parameter type.
4901 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4902 true /*OutermostType*/,
4903 false /*EncodingProperty*/,
4904 false /*StructField*/,
4905 Extended /*EncodeBlockParameters*/,
4906 Extended /*EncodeClassNames*/);
4907}
4908
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004909/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004910/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004911bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004912 std::string& S,
4913 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004914 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004915 // Encode return type.
Alp Toker314cc812014-01-25 16:55:45 +00004916 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4917 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004918 // Compute size of all parameters.
4919 // Start with computing size of a pointer in number of bytes.
4920 // FIXME: There might(should) be a better way of doing this computation!
4921 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004922 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004923 // The first two arguments (self and _cmd) are pointers; account for
4924 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004925 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004926 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004927 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004928 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004929 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004930 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00004931 continue;
4932
Ken Dyck40775002010-01-11 17:06:35 +00004933 assert (sz.isPositive() &&
4934 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004935 ParmOffset += sz;
4936 }
Ken Dyck40775002010-01-11 17:06:35 +00004937 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004938 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004939 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004940
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004941 // Argument types.
4942 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004943 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004944 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004945 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004946 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004947 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004948 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4949 // Use array's original type only if it has known number of
4950 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004951 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004952 PType = PVDecl->getType();
4953 } else if (PType->isFunctionType())
4954 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004955 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4956 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00004957 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004958 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004959 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004960
4961 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004962}
4963
Fariborz Jahaniandad96302014-01-22 19:02:20 +00004964ObjCPropertyImplDecl *
4965ASTContext::getObjCPropertyImplDeclForPropertyDecl(
4966 const ObjCPropertyDecl *PD,
4967 const Decl *Container) const {
4968 if (!Container)
4969 return 0;
4970 if (const ObjCCategoryImplDecl *CID =
4971 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4972 for (ObjCCategoryImplDecl::propimpl_iterator
4973 i = CID->propimpl_begin(), e = CID->propimpl_end();
4974 i != e; ++i) {
4975 ObjCPropertyImplDecl *PID = *i;
4976 if (PID->getPropertyDecl() == PD)
4977 return PID;
4978 }
4979 } else {
4980 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
4981 for (ObjCCategoryImplDecl::propimpl_iterator
4982 i = OID->propimpl_begin(), e = OID->propimpl_end();
4983 i != e; ++i) {
4984 ObjCPropertyImplDecl *PID = *i;
4985 if (PID->getPropertyDecl() == PD)
4986 return PID;
4987 }
4988 }
4989 return 0;
4990}
4991
Daniel Dunbar4932b362008-08-28 04:38:10 +00004992/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004993/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004994/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4995/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004996/// Property attributes are stored as a comma-delimited C string. The simple
4997/// attributes readonly and bycopy are encoded as single characters. The
4998/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4999/// encoded as single characters, followed by an identifier. Property types
5000/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005001/// these attributes are defined by the following enumeration:
5002/// @code
5003/// enum PropertyAttributes {
5004/// kPropertyReadOnly = 'R', // property is read-only.
5005/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
5006/// kPropertyByref = '&', // property is a reference to the value last assigned
5007/// kPropertyDynamic = 'D', // property is dynamic
5008/// kPropertyGetter = 'G', // followed by getter selector name
5009/// kPropertySetter = 'S', // followed by setter selector name
5010/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00005011/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005012/// kPropertyWeak = 'W' // 'weak' property
5013/// kPropertyStrong = 'P' // property GC'able
5014/// kPropertyNonAtomic = 'N' // property non-atomic
5015/// };
5016/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00005017void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00005018 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00005019 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005020 // Collect information from the property implementation decl(s).
5021 bool Dynamic = false;
5022 ObjCPropertyImplDecl *SynthesizePID = 0;
5023
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005024 if (ObjCPropertyImplDecl *PropertyImpDecl =
5025 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5026 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5027 Dynamic = true;
5028 else
5029 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005030 }
5031
5032 // FIXME: This is not very efficient.
5033 S = "T";
5034
5035 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005036 // GCC has some special rules regarding encoding of properties which
5037 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00005038 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005039 true /* outermost type */,
5040 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00005041
5042 if (PD->isReadOnly()) {
5043 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00005044 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5045 S += ",C";
5046 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5047 S += ",&";
Daniel Dunbar4932b362008-08-28 04:38:10 +00005048 } else {
5049 switch (PD->getSetterKind()) {
5050 case ObjCPropertyDecl::Assign: break;
5051 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00005052 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00005053 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005054 }
5055 }
5056
5057 // It really isn't clear at all what this means, since properties
5058 // are "dynamic by default".
5059 if (Dynamic)
5060 S += ",D";
5061
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005062 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5063 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00005064
Daniel Dunbar4932b362008-08-28 04:38:10 +00005065 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5066 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00005067 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005068 }
5069
5070 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5071 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00005072 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005073 }
5074
5075 if (SynthesizePID) {
5076 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5077 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00005078 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005079 }
5080
5081 // FIXME: OBJCGC: weak & strong
5082}
5083
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005084/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00005085/// Another legacy compatibility encoding: 32-bit longs are encoded as
5086/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005087/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5088///
5089void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00005090 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00005091 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00005092 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005093 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00005094 else
Jay Foad39c79802011-01-12 09:06:06 +00005095 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005096 PointeeTy = IntTy;
5097 }
5098 }
5099}
5100
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005101void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00005102 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005103 // We follow the behavior of gcc, expanding structures which are
5104 // directly pointed to, and expanding embedded structures. Note that
5105 // these rules are sufficient to prevent recursive encoding of the
5106 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00005107 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00005108 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005109}
5110
John McCall393a78d2012-12-20 02:45:14 +00005111static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5112 BuiltinType::Kind kind) {
5113 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005114 case BuiltinType::Void: return 'v';
5115 case BuiltinType::Bool: return 'B';
5116 case BuiltinType::Char_U:
5117 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00005118 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00005119 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00005120 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00005121 case BuiltinType::UInt: return 'I';
5122 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00005123 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005124 case BuiltinType::UInt128: return 'T';
5125 case BuiltinType::ULongLong: return 'Q';
5126 case BuiltinType::Char_S:
5127 case BuiltinType::SChar: return 'c';
5128 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00005129 case BuiltinType::WChar_S:
5130 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00005131 case BuiltinType::Int: return 'i';
5132 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00005133 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005134 case BuiltinType::LongLong: return 'q';
5135 case BuiltinType::Int128: return 't';
5136 case BuiltinType::Float: return 'f';
5137 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00005138 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00005139 case BuiltinType::NullPtr: return '*'; // like char*
5140
5141 case BuiltinType::Half:
5142 // FIXME: potentially need @encodes for these!
5143 return ' ';
5144
5145 case BuiltinType::ObjCId:
5146 case BuiltinType::ObjCClass:
5147 case BuiltinType::ObjCSel:
5148 llvm_unreachable("@encoding ObjC primitive type");
5149
5150 // OpenCL and placeholder types don't need @encodings.
5151 case BuiltinType::OCLImage1d:
5152 case BuiltinType::OCLImage1dArray:
5153 case BuiltinType::OCLImage1dBuffer:
5154 case BuiltinType::OCLImage2d:
5155 case BuiltinType::OCLImage2dArray:
5156 case BuiltinType::OCLImage3d:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005157 case BuiltinType::OCLEvent:
Guy Benyei61054192013-02-07 10:55:47 +00005158 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00005159 case BuiltinType::Dependent:
5160#define BUILTIN_TYPE(KIND, ID)
5161#define PLACEHOLDER_TYPE(KIND, ID) \
5162 case BuiltinType::KIND:
5163#include "clang/AST/BuiltinTypes.def"
5164 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00005165 }
David Blaikie5a6a0202013-01-09 17:48:41 +00005166 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00005167}
5168
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005169static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5170 EnumDecl *Enum = ET->getDecl();
5171
5172 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5173 if (!Enum->isFixed())
5174 return 'i';
5175
5176 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00005177 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5178 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005179}
5180
Jay Foad39c79802011-01-12 09:06:06 +00005181static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00005182 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00005183 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005184 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00005185 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5186 // The GNU runtime requires more information; bitfields are encoded as b,
5187 // then the offset (in bits) of the first element, then the type of the
5188 // bitfield, then the size in bits. For example, in this structure:
5189 //
5190 // struct
5191 // {
5192 // int integer;
5193 // int flags:2;
5194 // };
5195 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5196 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5197 // information is not especially sensible, but we're stuck with it for
5198 // compatibility with GCC, although providing it breaks anything that
5199 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00005200 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005201 const RecordDecl *RD = FD->getParent();
5202 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00005203 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005204 if (const EnumType *ET = T->getAs<EnumType>())
5205 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00005206 else {
5207 const BuiltinType *BT = T->castAs<BuiltinType>();
5208 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5209 }
David Chisnallb190a2c2010-06-04 01:10:52 +00005210 }
Richard Smithcaf33902011-10-10 18:28:20 +00005211 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005212}
5213
Daniel Dunbar07d07852009-10-18 21:17:35 +00005214// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005215void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5216 bool ExpandPointedToStructures,
5217 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00005218 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005219 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005220 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005221 bool StructField,
5222 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005223 bool EncodeClassNames,
5224 bool EncodePointerToObjCTypedef) const {
John McCall393a78d2012-12-20 02:45:14 +00005225 CanQualType CT = getCanonicalType(T);
5226 switch (CT->getTypeClass()) {
5227 case Type::Builtin:
5228 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00005229 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00005230 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00005231 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5232 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5233 else
5234 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00005235 return;
Mike Stump11289f42009-09-09 15:08:12 +00005236
John McCall393a78d2012-12-20 02:45:14 +00005237 case Type::Complex: {
5238 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00005239 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00005240 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00005241 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005242 return;
5243 }
John McCall393a78d2012-12-20 02:45:14 +00005244
5245 case Type::Atomic: {
5246 const AtomicType *AT = T->castAs<AtomicType>();
5247 S += 'A';
5248 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, 0,
5249 false, false);
5250 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00005251 }
John McCall393a78d2012-12-20 02:45:14 +00005252
5253 // encoding for pointer or reference types.
5254 case Type::Pointer:
5255 case Type::LValueReference:
5256 case Type::RValueReference: {
5257 QualType PointeeTy;
5258 if (isa<PointerType>(CT)) {
5259 const PointerType *PT = T->castAs<PointerType>();
5260 if (PT->isObjCSelType()) {
5261 S += ':';
5262 return;
5263 }
5264 PointeeTy = PT->getPointeeType();
5265 } else {
5266 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5267 }
5268
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005269 bool isReadOnly = false;
5270 // For historical/compatibility reasons, the read-only qualifier of the
5271 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5272 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00005273 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00005274 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005275 if (OutermostType && T.isConstQualified()) {
5276 isReadOnly = true;
5277 S += 'r';
5278 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00005279 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005280 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005281 while (P->getAs<PointerType>())
5282 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005283 if (P.isConstQualified()) {
5284 isReadOnly = true;
5285 S += 'r';
5286 }
5287 }
5288 if (isReadOnly) {
5289 // Another legacy compatibility encoding. Some ObjC qualifier and type
5290 // combinations need to be rearranged.
5291 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005292 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00005293 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005294 }
Mike Stump11289f42009-09-09 15:08:12 +00005295
Anders Carlssond8499822007-10-29 05:01:08 +00005296 if (PointeeTy->isCharType()) {
5297 // char pointer types should be encoded as '*' unless it is a
5298 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00005299 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00005300 S += '*';
5301 return;
5302 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005303 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00005304 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5305 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5306 S += '#';
5307 return;
5308 }
5309 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5310 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5311 S += '@';
5312 return;
5313 }
5314 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00005315 }
Anders Carlssond8499822007-10-29 05:01:08 +00005316 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005317 getLegacyIntegralTypeEncoding(PointeeTy);
5318
Mike Stump11289f42009-09-09 15:08:12 +00005319 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005320 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00005321 return;
5322 }
John McCall393a78d2012-12-20 02:45:14 +00005323
5324 case Type::ConstantArray:
5325 case Type::IncompleteArray:
5326 case Type::VariableArray: {
5327 const ArrayType *AT = cast<ArrayType>(CT);
5328
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005329 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005330 // Incomplete arrays are encoded as a pointer to the array element.
5331 S += '^';
5332
Mike Stump11289f42009-09-09 15:08:12 +00005333 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005334 false, ExpandStructures, FD);
5335 } else {
5336 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00005337
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00005338 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5339 S += llvm::utostr(CAT->getSize().getZExtValue());
5340 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00005341 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005342 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5343 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00005344 S += '0';
5345 }
Mike Stump11289f42009-09-09 15:08:12 +00005346
5347 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00005348 false, ExpandStructures, FD);
5349 S += ']';
5350 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005351 return;
5352 }
Mike Stump11289f42009-09-09 15:08:12 +00005353
John McCall393a78d2012-12-20 02:45:14 +00005354 case Type::FunctionNoProto:
5355 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00005356 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005357 return;
Mike Stump11289f42009-09-09 15:08:12 +00005358
John McCall393a78d2012-12-20 02:45:14 +00005359 case Type::Record: {
5360 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005361 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00005362 // Anonymous structures print as '?'
5363 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5364 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005365 if (ClassTemplateSpecializationDecl *Spec
5366 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5367 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00005368 llvm::raw_string_ostream OS(S);
5369 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005370 TemplateArgs.data(),
5371 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00005372 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00005373 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00005374 } else {
5375 S += '?';
5376 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00005377 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005378 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005379 if (!RDecl->isUnion()) {
5380 getObjCEncodingForStructureImpl(RDecl, S, FD);
5381 } else {
5382 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5383 FieldEnd = RDecl->field_end();
5384 Field != FieldEnd; ++Field) {
5385 if (FD) {
5386 S += '"';
5387 S += Field->getNameAsString();
5388 S += '"';
5389 }
Mike Stump11289f42009-09-09 15:08:12 +00005390
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005391 // Special case bit-fields.
5392 if (Field->isBitField()) {
5393 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie40ed2972012-06-06 20:45:41 +00005394 *Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005395 } else {
5396 QualType qt = Field->getType();
5397 getLegacyIntegralTypeEncoding(qt);
5398 getObjCEncodingForTypeImpl(qt, S, false, true,
5399 FD, /*OutermostType*/false,
5400 /*EncodingProperty*/false,
5401 /*StructField*/true);
5402 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005403 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005404 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00005405 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00005406 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005407 return;
5408 }
Mike Stump11289f42009-09-09 15:08:12 +00005409
John McCall393a78d2012-12-20 02:45:14 +00005410 case Type::BlockPointer: {
5411 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00005412 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005413 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00005414 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005415
5416 S += '<';
5417 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00005418 getObjCEncodingForTypeImpl(
5419 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
5420 FD, false /* OutermostType */, EncodingProperty,
5421 false /* StructField */, EncodeBlockParameters, EncodeClassNames);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005422 // Block self
5423 S += "@?";
5424 // Block parameters
5425 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
Alp Toker9cacbab2014-01-20 20:26:09 +00005426 for (FunctionProtoType::param_type_iterator I = FPT->param_type_begin(),
5427 E = FPT->param_type_end();
5428 I && (I != E); ++I) {
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005429 getObjCEncodingForTypeImpl(*I, S,
5430 ExpandPointedToStructures,
5431 ExpandStructures,
5432 FD,
5433 false /* OutermostType */,
5434 EncodingProperty,
5435 false /* StructField */,
5436 EncodeBlockParameters,
5437 EncodeClassNames);
5438 }
5439 }
5440 S += '>';
5441 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005442 return;
5443 }
Mike Stump11289f42009-09-09 15:08:12 +00005444
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00005445 case Type::ObjCObject: {
5446 // hack to match legacy encoding of *id and *Class
5447 QualType Ty = getObjCObjectPointerType(CT);
5448 if (Ty->isObjCIdType()) {
5449 S += "{objc_object=}";
5450 return;
5451 }
5452 else if (Ty->isObjCClassType()) {
5453 S += "{objc_class=}";
5454 return;
5455 }
5456 }
5457
John McCall393a78d2012-12-20 02:45:14 +00005458 case Type::ObjCInterface: {
5459 // Ignore protocol qualifiers when mangling at this level.
5460 T = T->castAs<ObjCObjectType>()->getBaseType();
John McCall8b07ec22010-05-15 11:32:37 +00005461
John McCall393a78d2012-12-20 02:45:14 +00005462 // The assumption seems to be that this assert will succeed
5463 // because nested levels will have filtered out 'id' and 'Class'.
5464 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005465 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00005466 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005467 S += '{';
5468 const IdentifierInfo *II = OI->getIdentifier();
5469 S += II->getName();
5470 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00005471 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005472 DeepCollectObjCIvars(OI, true, Ivars);
5473 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00005474 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00005475 if (Field->isBitField())
5476 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005477 else
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005478 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5479 false, false, false, false, false,
5480 EncodePointerToObjCTypedef);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005481 }
5482 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00005483 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00005484 }
Mike Stump11289f42009-09-09 15:08:12 +00005485
John McCall393a78d2012-12-20 02:45:14 +00005486 case Type::ObjCObjectPointer: {
5487 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005488 if (OPT->isObjCIdType()) {
5489 S += '@';
5490 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005491 }
Mike Stump11289f42009-09-09 15:08:12 +00005492
Steve Narofff0c86112009-10-28 22:03:49 +00005493 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5494 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5495 // Since this is a binary compatibility issue, need to consult with runtime
5496 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005497 S += '#';
5498 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005499 }
Mike Stump11289f42009-09-09 15:08:12 +00005500
Chris Lattnere7cabb92009-07-13 00:10:46 +00005501 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005502 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00005503 ExpandPointedToStructures,
5504 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005505 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005506 // Note that we do extended encoding of protocol qualifer list
5507 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00005508 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00005509 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5510 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00005511 S += '<';
5512 S += (*I)->getNameAsString();
5513 S += '>';
5514 }
5515 S += '"';
5516 }
5517 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00005518 }
Mike Stump11289f42009-09-09 15:08:12 +00005519
Chris Lattnere7cabb92009-07-13 00:10:46 +00005520 QualType PointeeTy = OPT->getPointeeType();
5521 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005522 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5523 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005524 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00005525 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00005526 // {...};
5527 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005528 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00005529 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00005530 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5531 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5532 DeepCollectObjCIvars(OI, true, Ivars);
5533 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5534 if (cast<FieldDecl>(Ivars[i]) == FD) {
5535 S += '{';
5536 S += OI->getIdentifier()->getName();
5537 S += '}';
5538 return;
5539 }
5540 }
5541 }
Mike Stump11289f42009-09-09 15:08:12 +00005542 getObjCEncodingForTypeImpl(PointeeTy, S,
5543 false, ExpandPointedToStructures,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00005544 NULL,
5545 false, false, false, false, false,
5546 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00005547 return;
5548 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005549
5550 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005551 if (OPT->getInterfaceDecl() &&
5552 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005553 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00005554 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00005555 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5556 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00005557 S += '<';
5558 S += (*I)->getNameAsString();
5559 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00005560 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00005561 S += '"';
5562 }
5563 return;
5564 }
Mike Stump11289f42009-09-09 15:08:12 +00005565
John McCalla9e6e8d2010-05-17 23:56:34 +00005566 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00005567 // FIXME: we shoul do better than that. 'M' is available.
5568 case Type::MemberPointer:
John McCalla9e6e8d2010-05-17 23:56:34 +00005569 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005570
John McCall393a78d2012-12-20 02:45:14 +00005571 case Type::Vector:
5572 case Type::ExtVector:
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005573 // This matches gcc's encoding, even though technically it is
5574 // insufficient.
5575 // FIXME. We should do a better job than gcc.
5576 return;
John McCall393a78d2012-12-20 02:45:14 +00005577
Richard Smith27d807c2013-04-30 13:56:41 +00005578 case Type::Auto:
5579 // We could see an undeduced auto type here during error recovery.
5580 // Just ignore it.
5581 return;
5582
John McCall393a78d2012-12-20 02:45:14 +00005583#define ABSTRACT_TYPE(KIND, BASE)
5584#define TYPE(KIND, BASE)
5585#define DEPENDENT_TYPE(KIND, BASE) \
5586 case Type::KIND:
5587#define NON_CANONICAL_TYPE(KIND, BASE) \
5588 case Type::KIND:
5589#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5590 case Type::KIND:
5591#include "clang/AST/TypeNodes.def"
5592 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00005593 }
John McCall393a78d2012-12-20 02:45:14 +00005594 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00005595}
5596
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005597void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5598 std::string &S,
5599 const FieldDecl *FD,
5600 bool includeVBases) const {
5601 assert(RDecl && "Expected non-null RecordDecl");
5602 assert(!RDecl->isUnion() && "Should not be called for unions");
5603 if (!RDecl->getDefinition())
5604 return;
5605
5606 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5607 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5608 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5609
5610 if (CXXRec) {
5611 for (CXXRecordDecl::base_class_iterator
5612 BI = CXXRec->bases_begin(),
5613 BE = CXXRec->bases_end(); BI != BE; ++BI) {
5614 if (!BI->isVirtual()) {
5615 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005616 if (base->isEmpty())
5617 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005618 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005619 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5620 std::make_pair(offs, base));
5621 }
5622 }
5623 }
5624
5625 unsigned i = 0;
5626 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5627 FieldEnd = RDecl->field_end();
5628 Field != FieldEnd; ++Field, ++i) {
5629 uint64_t offs = layout.getFieldOffset(i);
5630 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie40ed2972012-06-06 20:45:41 +00005631 std::make_pair(offs, *Field));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005632 }
5633
5634 if (CXXRec && includeVBases) {
5635 for (CXXRecordDecl::base_class_iterator
5636 BI = CXXRec->vbases_begin(),
5637 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
5638 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005639 if (base->isEmpty())
5640 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00005641 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00005642 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
5643 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00005644 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5645 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005646 }
5647 }
5648
5649 CharUnits size;
5650 if (CXXRec) {
5651 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5652 } else {
5653 size = layout.getSize();
5654 }
5655
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005656#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005657 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005658#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005659 std::multimap<uint64_t, NamedDecl *>::iterator
5660 CurLayObj = FieldOrBaseOffsets.begin();
5661
Douglas Gregorf5d6c742012-04-27 22:30:01 +00005662 if (CXXRec && CXXRec->isDynamicClass() &&
5663 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005664 if (FD) {
5665 S += "\"_vptr$";
5666 std::string recname = CXXRec->getNameAsString();
5667 if (recname.empty()) recname = "?";
5668 S += recname;
5669 S += '"';
5670 }
5671 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005672#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005673 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005674#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005675 }
5676
5677 if (!RDecl->hasFlexibleArrayMember()) {
5678 // Mark the end of the structure.
5679 uint64_t offs = toBits(size);
5680 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5681 std::make_pair(offs, (NamedDecl*)0));
5682 }
5683
5684 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005685#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005686 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005687 if (CurOffs < CurLayObj->first) {
5688 uint64_t padding = CurLayObj->first - CurOffs;
5689 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5690 // packing/alignment of members is different that normal, in which case
5691 // the encoding will be out-of-sync with the real layout.
5692 // If the runtime switches to just consider the size of types without
5693 // taking into account alignment, we could make padding explicit in the
5694 // encoding (e.g. using arrays of chars). The encoding strings would be
5695 // longer then though.
5696 CurOffs += padding;
5697 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005698#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005699
5700 NamedDecl *dcl = CurLayObj->second;
5701 if (dcl == 0)
5702 break; // reached end of structure.
5703
5704 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5705 // We expand the bases without their virtual bases since those are going
5706 // in the initial structure. Note that this differs from gcc which
5707 // expands virtual bases each time one is encountered in the hierarchy,
5708 // making the encoding type bigger than it really is.
5709 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005710 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005711#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00005712 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005713#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005714 } else {
5715 FieldDecl *field = cast<FieldDecl>(dcl);
5716 if (FD) {
5717 S += '"';
5718 S += field->getNameAsString();
5719 S += '"';
5720 }
5721
5722 if (field->isBitField()) {
5723 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005724#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00005725 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005726#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005727 } else {
5728 QualType qt = field->getType();
5729 getLegacyIntegralTypeEncoding(qt);
5730 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5731 /*OutermostType*/false,
5732 /*EncodingProperty*/false,
5733 /*StructField*/true);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005734#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005735 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00005736#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00005737 }
5738 }
5739 }
5740}
5741
Mike Stump11289f42009-09-09 15:08:12 +00005742void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00005743 std::string& S) const {
5744 if (QT & Decl::OBJC_TQ_In)
5745 S += 'n';
5746 if (QT & Decl::OBJC_TQ_Inout)
5747 S += 'N';
5748 if (QT & Decl::OBJC_TQ_Out)
5749 S += 'o';
5750 if (QT & Decl::OBJC_TQ_Bycopy)
5751 S += 'O';
5752 if (QT & Decl::OBJC_TQ_Byref)
5753 S += 'R';
5754 if (QT & Decl::OBJC_TQ_Oneway)
5755 S += 'V';
5756}
5757
Douglas Gregor3ea72692011-08-12 05:46:01 +00005758TypedefDecl *ASTContext::getObjCIdDecl() const {
5759 if (!ObjCIdDecl) {
5760 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5761 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00005762 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00005763 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00005764 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00005765}
5766
Douglas Gregor52e02802011-08-12 06:17:30 +00005767TypedefDecl *ASTContext::getObjCSelDecl() const {
5768 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00005769 QualType T = getPointerType(ObjCBuiltinSelTy);
5770 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00005771 }
5772 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00005773}
5774
Douglas Gregor0a586182011-08-12 05:59:41 +00005775TypedefDecl *ASTContext::getObjCClassDecl() const {
5776 if (!ObjCClassDecl) {
5777 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5778 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00005779 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00005780 }
Douglas Gregor0a586182011-08-12 05:59:41 +00005781 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00005782}
5783
Douglas Gregord53ae832012-01-17 18:09:05 +00005784ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5785 if (!ObjCProtocolClassDecl) {
5786 ObjCProtocolClassDecl
5787 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5788 SourceLocation(),
5789 &Idents.get("Protocol"),
5790 /*PrevDecl=*/0,
5791 SourceLocation(), true);
5792 }
5793
5794 return ObjCProtocolClassDecl;
5795}
5796
Meador Inge5d3fb222012-06-16 03:34:49 +00005797//===----------------------------------------------------------------------===//
5798// __builtin_va_list Construction Functions
5799//===----------------------------------------------------------------------===//
5800
5801static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5802 // typedef char* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005803 QualType T = Context->getPointerType(Context->CharTy);
5804 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005805}
5806
5807static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5808 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005809 QualType T = Context->getPointerType(Context->VoidTy);
5810 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005811}
5812
Tim Northover9bb857a2013-01-31 12:13:10 +00005813static TypedefDecl *
5814CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00005815 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00005816 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00005817 if (Context->getLangOpts().CPlusPlus) {
5818 // namespace std { struct __va_list {
5819 NamespaceDecl *NS;
5820 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5821 Context->getTranslationUnitDecl(),
5822 /*Inline*/false, SourceLocation(),
5823 SourceLocation(), &Context->Idents.get("std"),
5824 /*PrevDecl*/0);
Alp Toker56b5cc92013-12-15 10:36:26 +00005825 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00005826 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00005827 }
5828
5829 VaListTagDecl->startDefinition();
5830
5831 const size_t NumFields = 5;
5832 QualType FieldTypes[NumFields];
5833 const char *FieldNames[NumFields];
5834
5835 // void *__stack;
5836 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
5837 FieldNames[0] = "__stack";
5838
5839 // void *__gr_top;
5840 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
5841 FieldNames[1] = "__gr_top";
5842
5843 // void *__vr_top;
5844 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5845 FieldNames[2] = "__vr_top";
5846
5847 // int __gr_offs;
5848 FieldTypes[3] = Context->IntTy;
5849 FieldNames[3] = "__gr_offs";
5850
5851 // int __vr_offs;
5852 FieldTypes[4] = Context->IntTy;
5853 FieldNames[4] = "__vr_offs";
5854
5855 // Create fields
5856 for (unsigned i = 0; i < NumFields; ++i) {
5857 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5858 VaListTagDecl,
5859 SourceLocation(),
5860 SourceLocation(),
5861 &Context->Idents.get(FieldNames[i]),
5862 FieldTypes[i], /*TInfo=*/0,
5863 /*BitWidth=*/0,
5864 /*Mutable=*/false,
5865 ICIS_NoInit);
5866 Field->setAccess(AS_public);
5867 VaListTagDecl->addDecl(Field);
5868 }
5869 VaListTagDecl->completeDefinition();
5870 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5871 Context->VaListTagTy = VaListTagType;
5872
5873 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00005874 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00005875}
5876
Meador Inge5d3fb222012-06-16 03:34:49 +00005877static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5878 // typedef struct __va_list_tag {
5879 RecordDecl *VaListTagDecl;
5880
Alp Toker2dea15b2013-12-17 01:22:38 +00005881 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00005882 VaListTagDecl->startDefinition();
5883
5884 const size_t NumFields = 5;
5885 QualType FieldTypes[NumFields];
5886 const char *FieldNames[NumFields];
5887
5888 // unsigned char gpr;
5889 FieldTypes[0] = Context->UnsignedCharTy;
5890 FieldNames[0] = "gpr";
5891
5892 // unsigned char fpr;
5893 FieldTypes[1] = Context->UnsignedCharTy;
5894 FieldNames[1] = "fpr";
5895
5896 // unsigned short reserved;
5897 FieldTypes[2] = Context->UnsignedShortTy;
5898 FieldNames[2] = "reserved";
5899
5900 // void* overflow_arg_area;
5901 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5902 FieldNames[3] = "overflow_arg_area";
5903
5904 // void* reg_save_area;
5905 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5906 FieldNames[4] = "reg_save_area";
5907
5908 // Create fields
5909 for (unsigned i = 0; i < NumFields; ++i) {
5910 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5911 SourceLocation(),
5912 SourceLocation(),
5913 &Context->Idents.get(FieldNames[i]),
5914 FieldTypes[i], /*TInfo=*/0,
5915 /*BitWidth=*/0,
5916 /*Mutable=*/false,
5917 ICIS_NoInit);
5918 Field->setAccess(AS_public);
5919 VaListTagDecl->addDecl(Field);
5920 }
5921 VaListTagDecl->completeDefinition();
5922 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005923 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005924
5925 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00005926 TypedefDecl *VaListTagTypedefDecl =
5927 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
5928
Meador Inge5d3fb222012-06-16 03:34:49 +00005929 QualType VaListTagTypedefType =
5930 Context->getTypedefType(VaListTagTypedefDecl);
5931
5932 // typedef __va_list_tag __builtin_va_list[1];
5933 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5934 QualType VaListTagArrayType
5935 = Context->getConstantArrayType(VaListTagTypedefType,
5936 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00005937 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005938}
5939
5940static TypedefDecl *
5941CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5942 // typedef struct __va_list_tag {
5943 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00005944 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00005945 VaListTagDecl->startDefinition();
5946
5947 const size_t NumFields = 4;
5948 QualType FieldTypes[NumFields];
5949 const char *FieldNames[NumFields];
5950
5951 // unsigned gp_offset;
5952 FieldTypes[0] = Context->UnsignedIntTy;
5953 FieldNames[0] = "gp_offset";
5954
5955 // unsigned fp_offset;
5956 FieldTypes[1] = Context->UnsignedIntTy;
5957 FieldNames[1] = "fp_offset";
5958
5959 // void* overflow_arg_area;
5960 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5961 FieldNames[2] = "overflow_arg_area";
5962
5963 // void* reg_save_area;
5964 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5965 FieldNames[3] = "reg_save_area";
5966
5967 // Create fields
5968 for (unsigned i = 0; i < NumFields; ++i) {
5969 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5970 VaListTagDecl,
5971 SourceLocation(),
5972 SourceLocation(),
5973 &Context->Idents.get(FieldNames[i]),
5974 FieldTypes[i], /*TInfo=*/0,
5975 /*BitWidth=*/0,
5976 /*Mutable=*/false,
5977 ICIS_NoInit);
5978 Field->setAccess(AS_public);
5979 VaListTagDecl->addDecl(Field);
5980 }
5981 VaListTagDecl->completeDefinition();
5982 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Meador Ingecfb60902012-07-01 15:57:25 +00005983 Context->VaListTagTy = VaListTagType;
Meador Inge5d3fb222012-06-16 03:34:49 +00005984
5985 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00005986 TypedefDecl *VaListTagTypedefDecl =
5987 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
5988
Meador Inge5d3fb222012-06-16 03:34:49 +00005989 QualType VaListTagTypedefType =
5990 Context->getTypedefType(VaListTagTypedefDecl);
5991
5992 // typedef __va_list_tag __builtin_va_list[1];
5993 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5994 QualType VaListTagArrayType
5995 = Context->getConstantArrayType(VaListTagTypedefType,
5996 Size, ArrayType::Normal,0);
Alp Toker56b5cc92013-12-15 10:36:26 +00005997 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00005998}
5999
6000static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
6001 // typedef int __builtin_va_list[4];
6002 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
6003 QualType IntArrayType
6004 = Context->getConstantArrayType(Context->IntTy,
6005 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006006 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006007}
6008
Logan Chien57086ce2012-10-10 06:56:20 +00006009static TypedefDecl *
6010CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006011 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006012 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006013 if (Context->getLangOpts().CPlusPlus) {
6014 // namespace std { struct __va_list {
6015 NamespaceDecl *NS;
6016 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6017 Context->getTranslationUnitDecl(),
6018 /*Inline*/false, SourceLocation(),
6019 SourceLocation(), &Context->Idents.get("std"),
6020 /*PrevDecl*/0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006021 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00006022 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00006023 }
6024
6025 VaListDecl->startDefinition();
6026
6027 // void * __ap;
6028 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6029 VaListDecl,
6030 SourceLocation(),
6031 SourceLocation(),
6032 &Context->Idents.get("__ap"),
6033 Context->getPointerType(Context->VoidTy),
6034 /*TInfo=*/0,
6035 /*BitWidth=*/0,
6036 /*Mutable=*/false,
6037 ICIS_NoInit);
6038 Field->setAccess(AS_public);
6039 VaListDecl->addDecl(Field);
6040
6041 // };
6042 VaListDecl->completeDefinition();
6043
6044 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006045 QualType T = Context->getRecordType(VaListDecl);
6046 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006047}
6048
Ulrich Weigand47445072013-05-06 16:26:41 +00006049static TypedefDecl *
6050CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
6051 // typedef struct __va_list_tag {
6052 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006053 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006054 VaListTagDecl->startDefinition();
6055
6056 const size_t NumFields = 4;
6057 QualType FieldTypes[NumFields];
6058 const char *FieldNames[NumFields];
6059
6060 // long __gpr;
6061 FieldTypes[0] = Context->LongTy;
6062 FieldNames[0] = "__gpr";
6063
6064 // long __fpr;
6065 FieldTypes[1] = Context->LongTy;
6066 FieldNames[1] = "__fpr";
6067
6068 // void *__overflow_arg_area;
6069 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6070 FieldNames[2] = "__overflow_arg_area";
6071
6072 // void *__reg_save_area;
6073 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6074 FieldNames[3] = "__reg_save_area";
6075
6076 // Create fields
6077 for (unsigned i = 0; i < NumFields; ++i) {
6078 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6079 VaListTagDecl,
6080 SourceLocation(),
6081 SourceLocation(),
6082 &Context->Idents.get(FieldNames[i]),
6083 FieldTypes[i], /*TInfo=*/0,
6084 /*BitWidth=*/0,
6085 /*Mutable=*/false,
6086 ICIS_NoInit);
6087 Field->setAccess(AS_public);
6088 VaListTagDecl->addDecl(Field);
6089 }
6090 VaListTagDecl->completeDefinition();
6091 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6092 Context->VaListTagTy = VaListTagType;
6093
6094 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006095 TypedefDecl *VaListTagTypedefDecl =
6096 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006097 QualType VaListTagTypedefType =
6098 Context->getTypedefType(VaListTagTypedefDecl);
6099
6100 // typedef __va_list_tag __builtin_va_list[1];
6101 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6102 QualType VaListTagArrayType
6103 = Context->getConstantArrayType(VaListTagTypedefType,
6104 Size, ArrayType::Normal,0);
Ulrich Weigand47445072013-05-06 16:26:41 +00006105
Alp Toker56b5cc92013-12-15 10:36:26 +00006106 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00006107}
6108
Meador Inge5d3fb222012-06-16 03:34:49 +00006109static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6110 TargetInfo::BuiltinVaListKind Kind) {
6111 switch (Kind) {
6112 case TargetInfo::CharPtrBuiltinVaList:
6113 return CreateCharPtrBuiltinVaListDecl(Context);
6114 case TargetInfo::VoidPtrBuiltinVaList:
6115 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00006116 case TargetInfo::AArch64ABIBuiltinVaList:
6117 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006118 case TargetInfo::PowerABIBuiltinVaList:
6119 return CreatePowerABIBuiltinVaListDecl(Context);
6120 case TargetInfo::X86_64ABIBuiltinVaList:
6121 return CreateX86_64ABIBuiltinVaListDecl(Context);
6122 case TargetInfo::PNaClABIBuiltinVaList:
6123 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00006124 case TargetInfo::AAPCSABIBuiltinVaList:
6125 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00006126 case TargetInfo::SystemZBuiltinVaList:
6127 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006128 }
6129
6130 llvm_unreachable("Unhandled __builtin_va_list type kind");
6131}
6132
6133TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00006134 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00006135 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00006136 assert(BuiltinVaListDecl->isImplicit());
6137 }
Meador Inge5d3fb222012-06-16 03:34:49 +00006138
6139 return BuiltinVaListDecl;
6140}
6141
Meador Ingecfb60902012-07-01 15:57:25 +00006142QualType ASTContext::getVaListTagType() const {
6143 // Force the creation of VaListTagTy by building the __builtin_va_list
6144 // declaration.
6145 if (VaListTagTy.isNull())
6146 (void) getBuiltinVaListDecl();
6147
6148 return VaListTagTy;
6149}
6150
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006151void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00006152 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00006153 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00006154
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006155 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00006156}
6157
John McCalld28ae272009-12-02 08:04:21 +00006158/// \brief Retrieve the template name that corresponds to a non-empty
6159/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00006160TemplateName
6161ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6162 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00006163 unsigned size = End - Begin;
6164 assert(size > 1 && "set is not overloaded!");
6165
6166 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6167 size * sizeof(FunctionTemplateDecl*));
6168 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6169
6170 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00006171 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00006172 NamedDecl *D = *I;
6173 assert(isa<FunctionTemplateDecl>(D) ||
6174 (isa<UsingShadowDecl>(D) &&
6175 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6176 *Storage++ = D;
6177 }
6178
6179 return TemplateName(OT);
6180}
6181
Douglas Gregordc572a32009-03-30 22:58:21 +00006182/// \brief Retrieve the template name that represents a qualified
6183/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00006184TemplateName
6185ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6186 bool TemplateKeyword,
6187 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00006188 assert(NNS && "Missing nested-name-specifier in qualified template name");
6189
Douglas Gregorc42075a2010-02-04 18:10:26 +00006190 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00006191 llvm::FoldingSetNodeID ID;
6192 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6193
6194 void *InsertPos = 0;
6195 QualifiedTemplateName *QTN =
6196 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6197 if (!QTN) {
Richard Smitha5e69762012-08-16 01:19:31 +00006198 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6199 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00006200 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6201 }
6202
6203 return TemplateName(QTN);
6204}
6205
6206/// \brief Retrieve the template name that represents a dependent
6207/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00006208TemplateName
6209ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6210 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00006211 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00006212 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00006213
6214 llvm::FoldingSetNodeID ID;
6215 DependentTemplateName::Profile(ID, NNS, Name);
6216
6217 void *InsertPos = 0;
6218 DependentTemplateName *QTN =
6219 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6220
6221 if (QTN)
6222 return TemplateName(QTN);
6223
6224 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6225 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006226 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6227 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00006228 } else {
6229 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Richard Smitha5e69762012-08-16 01:19:31 +00006230 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6231 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006232 DependentTemplateName *CheckQTN =
6233 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6234 assert(!CheckQTN && "Dependent type name canonicalization broken");
6235 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00006236 }
6237
6238 DependentTemplateNames.InsertNode(QTN, InsertPos);
6239 return TemplateName(QTN);
6240}
6241
Douglas Gregor71395fa2009-11-04 00:56:37 +00006242/// \brief Retrieve the template name that represents a dependent
6243/// template name such as \c MetaFun::template operator+.
6244TemplateName
6245ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00006246 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00006247 assert((!NNS || NNS->isDependent()) &&
6248 "Nested name specifier must be dependent");
6249
6250 llvm::FoldingSetNodeID ID;
6251 DependentTemplateName::Profile(ID, NNS, Operator);
6252
6253 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00006254 DependentTemplateName *QTN
6255 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006256
6257 if (QTN)
6258 return TemplateName(QTN);
6259
6260 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6261 if (CanonNNS == NNS) {
Richard Smitha5e69762012-08-16 01:19:31 +00006262 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6263 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00006264 } else {
6265 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Richard Smitha5e69762012-08-16 01:19:31 +00006266 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6267 DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00006268
6269 DependentTemplateName *CheckQTN
6270 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6271 assert(!CheckQTN && "Dependent template name canonicalization broken");
6272 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00006273 }
6274
6275 DependentTemplateNames.InsertNode(QTN, InsertPos);
6276 return TemplateName(QTN);
6277}
6278
Douglas Gregor5590be02011-01-15 06:45:20 +00006279TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00006280ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6281 TemplateName replacement) const {
6282 llvm::FoldingSetNodeID ID;
6283 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
6284
6285 void *insertPos = 0;
6286 SubstTemplateTemplateParmStorage *subst
6287 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6288
6289 if (!subst) {
6290 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6291 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6292 }
6293
6294 return TemplateName(subst);
6295}
6296
6297TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00006298ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6299 const TemplateArgument &ArgPack) const {
6300 ASTContext &Self = const_cast<ASTContext &>(*this);
6301 llvm::FoldingSetNodeID ID;
6302 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
6303
6304 void *InsertPos = 0;
6305 SubstTemplateTemplateParmPackStorage *Subst
6306 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6307
6308 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00006309 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00006310 ArgPack.pack_size(),
6311 ArgPack.pack_begin());
6312 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6313 }
6314
6315 return TemplateName(Subst);
6316}
6317
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006318/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00006319/// TargetInfo, produce the corresponding type. The unsigned @p Type
6320/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00006321CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006322 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00006323 case TargetInfo::NoInt: return CanQualType();
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00006324 case TargetInfo::SignedChar: return SignedCharTy;
6325 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006326 case TargetInfo::SignedShort: return ShortTy;
6327 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6328 case TargetInfo::SignedInt: return IntTy;
6329 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6330 case TargetInfo::SignedLong: return LongTy;
6331 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6332 case TargetInfo::SignedLongLong: return LongLongTy;
6333 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6334 }
6335
David Blaikie83d382b2011-09-23 05:06:16 +00006336 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00006337}
Ted Kremenek77c51b22008-07-24 23:58:27 +00006338
6339//===----------------------------------------------------------------------===//
6340// Type Predicates.
6341//===----------------------------------------------------------------------===//
6342
Fariborz Jahanian96207692009-02-18 21:49:28 +00006343/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6344/// garbage collection attribute.
6345///
John McCall553d45a2011-01-12 00:34:59 +00006346Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006347 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00006348 return Qualifiers::GCNone;
6349
David Blaikiebbafb8a2012-03-11 07:00:24 +00006350 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00006351 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6352
6353 // Default behaviour under objective-C's gc is for ObjC pointers
6354 // (or pointers to them) be treated as though they were declared
6355 // as __strong.
6356 if (GCAttrs == Qualifiers::GCNone) {
6357 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6358 return Qualifiers::Strong;
6359 else if (Ty->isPointerType())
6360 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6361 } else {
6362 // It's not valid to set GC attributes on anything that isn't a
6363 // pointer.
6364#ifndef NDEBUG
6365 QualType CT = Ty->getCanonicalTypeInternal();
6366 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6367 CT = AT->getElementType();
6368 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6369#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00006370 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00006371 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00006372}
6373
Chris Lattner49af6a42008-04-07 06:51:04 +00006374//===----------------------------------------------------------------------===//
6375// Type Compatibility Testing
6376//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00006377
Mike Stump11289f42009-09-09 15:08:12 +00006378/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006379/// compatible.
6380static bool areCompatVectorTypes(const VectorType *LHS,
6381 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00006382 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00006383 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00006384 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00006385}
6386
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006387bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6388 QualType SecondVec) {
6389 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6390 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6391
6392 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6393 return true;
6394
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006395 // Treat Neon vector types and most AltiVec vector types as if they are the
6396 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006397 const VectorType *First = FirstVec->getAs<VectorType>();
6398 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006399 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006400 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00006401 First->getVectorKind() != VectorType::AltiVecPixel &&
6402 First->getVectorKind() != VectorType::AltiVecBool &&
6403 Second->getVectorKind() != VectorType::AltiVecPixel &&
6404 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00006405 return true;
6406
6407 return false;
6408}
6409
Steve Naroff8e6aee52009-07-23 01:01:38 +00006410//===----------------------------------------------------------------------===//
6411// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6412//===----------------------------------------------------------------------===//
6413
6414/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6415/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00006416bool
6417ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6418 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00006419 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006420 return true;
6421 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
6422 E = rProto->protocol_end(); PI != E; ++PI)
6423 if (ProtocolCompatibleWithProtocol(lProto, *PI))
6424 return true;
6425 return false;
6426}
6427
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00006428/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6429/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006430bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6431 QualType rhs) {
6432 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6433 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6434 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6435
6436 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6437 E = lhsQID->qual_end(); I != E; ++I) {
6438 bool match = false;
6439 ObjCProtocolDecl *lhsProto = *I;
6440 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6441 E = rhsOPT->qual_end(); J != E; ++J) {
6442 ObjCProtocolDecl *rhsProto = *J;
6443 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6444 match = true;
6445 break;
6446 }
6447 }
6448 if (!match)
6449 return false;
6450 }
6451 return true;
6452}
6453
Steve Naroff8e6aee52009-07-23 01:01:38 +00006454/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6455/// ObjCQualifiedIDType.
6456bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6457 bool compare) {
6458 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00006459 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006460 lhs->isObjCIdType() || lhs->isObjCClassType())
6461 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006462 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00006463 rhs->isObjCIdType() || rhs->isObjCClassType())
6464 return true;
6465
6466 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00006467 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006468
Steve Naroff8e6aee52009-07-23 01:01:38 +00006469 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00006470
Steve Naroff8e6aee52009-07-23 01:01:38 +00006471 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00006472 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006473 // make sure we check the class hierarchy.
6474 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6475 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6476 E = lhsQID->qual_end(); I != E; ++I) {
6477 // when comparing an id<P> on lhs with a static type on rhs,
6478 // see if static class implements all of id's protocols, directly or
6479 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00006480 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00006481 return false;
6482 }
6483 }
6484 // If there are no qualifiers and no interface, we have an 'id'.
6485 return true;
6486 }
Mike Stump11289f42009-09-09 15:08:12 +00006487 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006488 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6489 E = lhsQID->qual_end(); I != E; ++I) {
6490 ObjCProtocolDecl *lhsProto = *I;
6491 bool match = false;
6492
6493 // when comparing an id<P> on lhs with a static type on rhs,
6494 // see if static class implements all of id's protocols, directly or
6495 // through its super class and categories.
6496 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6497 E = rhsOPT->qual_end(); J != E; ++J) {
6498 ObjCProtocolDecl *rhsProto = *J;
6499 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6500 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6501 match = true;
6502 break;
6503 }
6504 }
Mike Stump11289f42009-09-09 15:08:12 +00006505 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00006506 // make sure we check the class hierarchy.
6507 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6508 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6509 E = lhsQID->qual_end(); I != E; ++I) {
6510 // when comparing an id<P> on lhs with a static type on rhs,
6511 // see if static class implements all of id's protocols, directly or
6512 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00006513 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00006514 match = true;
6515 break;
6516 }
6517 }
6518 }
6519 if (!match)
6520 return false;
6521 }
Mike Stump11289f42009-09-09 15:08:12 +00006522
Steve Naroff8e6aee52009-07-23 01:01:38 +00006523 return true;
6524 }
Mike Stump11289f42009-09-09 15:08:12 +00006525
Steve Naroff8e6aee52009-07-23 01:01:38 +00006526 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6527 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6528
Mike Stump11289f42009-09-09 15:08:12 +00006529 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00006530 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006531 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006532 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
6533 E = lhsOPT->qual_end(); I != E; ++I) {
6534 ObjCProtocolDecl *lhsProto = *I;
6535 bool match = false;
6536
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006537 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00006538 // see if static class implements all of id's protocols, directly or
6539 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006540 // First, lhs protocols in the qualifier list must be found, direct
6541 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00006542 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6543 E = rhsQID->qual_end(); J != E; ++J) {
6544 ObjCProtocolDecl *rhsProto = *J;
6545 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6546 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6547 match = true;
6548 break;
6549 }
6550 }
6551 if (!match)
6552 return false;
6553 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00006554
6555 // Static class's protocols, or its super class or category protocols
6556 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6557 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6558 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6559 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6560 // This is rather dubious but matches gcc's behavior. If lhs has
6561 // no type qualifier and its class has no static protocol(s)
6562 // assume that it is mismatch.
6563 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6564 return false;
6565 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6566 LHSInheritedProtocols.begin(),
6567 E = LHSInheritedProtocols.end(); I != E; ++I) {
6568 bool match = false;
6569 ObjCProtocolDecl *lhsProto = (*I);
6570 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6571 E = rhsQID->qual_end(); J != E; ++J) {
6572 ObjCProtocolDecl *rhsProto = *J;
6573 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6574 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6575 match = true;
6576 break;
6577 }
6578 }
6579 if (!match)
6580 return false;
6581 }
6582 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00006583 return true;
6584 }
6585 return false;
6586}
6587
Eli Friedman47f77112008-08-22 00:56:42 +00006588/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00006589/// compatible for assignment from RHS to LHS. This handles validation of any
6590/// protocol qualifiers on the LHS or RHS.
6591///
Steve Naroff7cae42b2009-07-10 23:34:53 +00006592bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6593 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00006594 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6595 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6596
Steve Naroff1329fa02009-07-15 18:40:39 +00006597 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00006598 if (LHS->isObjCUnqualifiedIdOrClass() ||
6599 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00006600 return true;
6601
John McCall8b07ec22010-05-15 11:32:37 +00006602 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00006603 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6604 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00006605 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00006606
6607 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6608 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6609 QualType(RHSOPT,0));
6610
John McCall8b07ec22010-05-15 11:32:37 +00006611 // If we have 2 user-defined types, fall into that path.
6612 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00006613 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006614
Steve Naroff8e6aee52009-07-23 01:01:38 +00006615 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006616}
6617
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006618/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00006619/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006620/// arguments in block literals. When passed as arguments, passing 'A*' where
6621/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6622/// not OK. For the return type, the opposite is not OK.
6623bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6624 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006625 const ObjCObjectPointerType *RHSOPT,
6626 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006627 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006628 return true;
6629
6630 if (LHSOPT->isObjCBuiltinType()) {
6631 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6632 }
6633
Fariborz Jahanian440a6832010-04-06 17:23:39 +00006634 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006635 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6636 QualType(RHSOPT,0),
6637 false);
6638
6639 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6640 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6641 if (LHS && RHS) { // We have 2 user-defined types.
6642 if (LHS != RHS) {
6643 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006644 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006645 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006646 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006647 }
6648 else
6649 return true;
6650 }
6651 return false;
6652}
6653
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006654/// getIntersectionOfProtocols - This routine finds the intersection of set
6655/// of protocols inherited from two distinct objective-c pointer objects.
6656/// It is used to build composite qualifier list of the composite type of
6657/// the conditional expression involving two objective-c pointer objects.
6658static
6659void getIntersectionOfProtocols(ASTContext &Context,
6660 const ObjCObjectPointerType *LHSOPT,
6661 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006662 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006663
John McCall8b07ec22010-05-15 11:32:37 +00006664 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6665 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6666 assert(LHS->getInterface() && "LHS must have an interface base");
6667 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006668
6669 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6670 unsigned LHSNumProtocols = LHS->getNumProtocols();
6671 if (LHSNumProtocols > 0)
6672 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6673 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006674 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006675 Context.CollectInheritedProtocols(LHS->getInterface(),
6676 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006677 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6678 LHSInheritedProtocols.end());
6679 }
6680
6681 unsigned RHSNumProtocols = RHS->getNumProtocols();
6682 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00006683 ObjCProtocolDecl **RHSProtocols =
6684 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006685 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6686 if (InheritedProtocolSet.count(RHSProtocols[i]))
6687 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00006688 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006689 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00006690 Context.CollectInheritedProtocols(RHS->getInterface(),
6691 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00006692 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6693 RHSInheritedProtocols.begin(),
6694 E = RHSInheritedProtocols.end(); I != E; ++I)
6695 if (InheritedProtocolSet.count((*I)))
6696 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006697 }
6698}
6699
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006700/// areCommonBaseCompatible - Returns common base class of the two classes if
6701/// one found. Note that this is O'2 algorithm. But it will be called as the
6702/// last type comparison in a ?-exp of ObjC pointer types before a
6703/// warning is issued. So, its invokation is extremely rare.
6704QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00006705 const ObjCObjectPointerType *Lptr,
6706 const ObjCObjectPointerType *Rptr) {
6707 const ObjCObjectType *LHS = Lptr->getObjectType();
6708 const ObjCObjectType *RHS = Rptr->getObjectType();
6709 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6710 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00006711 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006712 return QualType();
6713
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006714 do {
John McCall8b07ec22010-05-15 11:32:37 +00006715 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006716 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006717 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00006718 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6719
6720 QualType Result = QualType(LHS, 0);
6721 if (!Protocols.empty())
6722 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6723 Result = getObjCObjectPointerType(Result);
6724 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00006725 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00006726 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00006727
6728 return QualType();
6729}
6730
John McCall8b07ec22010-05-15 11:32:37 +00006731bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6732 const ObjCObjectType *RHS) {
6733 assert(LHS->getInterface() && "LHS is not an interface type");
6734 assert(RHS->getInterface() && "RHS is not an interface type");
6735
Chris Lattner49af6a42008-04-07 06:51:04 +00006736 // Verify that the base decls are compatible: the RHS must be a subclass of
6737 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00006738 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00006739 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006740
Chris Lattner49af6a42008-04-07 06:51:04 +00006741 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6742 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00006743 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00006744 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006745
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006746 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6747 // more detailed analysis is required.
6748 if (RHS->getNumProtocols() == 0) {
6749 // OK, if LHS is a superclass of RHS *and*
6750 // this superclass is assignment compatible with LHS.
6751 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006752 bool IsSuperClass =
6753 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6754 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006755 // OK if conversion of LHS to SuperClass results in narrowing of types
6756 // ; i.e., SuperClass may implement at least one of the protocols
6757 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6758 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6759 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00006760 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00006761 // If super class has no protocols, it is not a match.
6762 if (SuperClassInheritedProtocols.empty())
6763 return false;
6764
6765 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6766 LHSPE = LHS->qual_end();
6767 LHSPI != LHSPE; LHSPI++) {
6768 bool SuperImplementsProtocol = false;
6769 ObjCProtocolDecl *LHSProto = (*LHSPI);
6770
6771 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6772 SuperClassInheritedProtocols.begin(),
6773 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6774 ObjCProtocolDecl *SuperClassProto = (*I);
6775 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6776 SuperImplementsProtocol = true;
6777 break;
6778 }
6779 }
6780 if (!SuperImplementsProtocol)
6781 return false;
6782 }
6783 return true;
6784 }
6785 return false;
6786 }
Mike Stump11289f42009-09-09 15:08:12 +00006787
John McCall8b07ec22010-05-15 11:32:37 +00006788 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6789 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00006790 LHSPI != LHSPE; LHSPI++) {
6791 bool RHSImplementsProtocol = false;
6792
6793 // If the RHS doesn't implement the protocol on the left, the types
6794 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00006795 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6796 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00006797 RHSPI != RHSPE; RHSPI++) {
6798 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00006799 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00006800 break;
6801 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006802 }
6803 // FIXME: For better diagnostics, consider passing back the protocol name.
6804 if (!RHSImplementsProtocol)
6805 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00006806 }
Steve Naroff114aecb2009-03-01 16:12:44 +00006807 // The RHS implements all protocols listed on the LHS.
6808 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00006809}
6810
Steve Naroffb7605152009-02-12 17:52:19 +00006811bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6812 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00006813 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6814 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00006815
Steve Naroff7cae42b2009-07-10 23:34:53 +00006816 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00006817 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00006818
6819 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6820 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00006821}
6822
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00006823bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6824 return canAssignObjCInterfaces(
6825 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6826 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6827}
6828
Mike Stump11289f42009-09-09 15:08:12 +00006829/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00006830/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00006831/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00006832/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006833bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6834 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006835 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00006836 return hasSameType(LHS, RHS);
6837
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006838 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00006839}
6840
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006841bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00006842 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00006843}
6844
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006845bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6846 return !mergeTypes(LHS, RHS, true).isNull();
6847}
6848
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006849/// mergeTransparentUnionType - if T is a transparent union type and a member
6850/// of T is compatible with SubType, return the merged type, else return
6851/// QualType()
6852QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6853 bool OfBlockPointer,
6854 bool Unqualified) {
6855 if (const RecordType *UT = T->getAsUnionType()) {
6856 RecordDecl *UD = UT->getDecl();
6857 if (UD->hasAttr<TransparentUnionAttr>()) {
6858 for (RecordDecl::field_iterator it = UD->field_begin(),
6859 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00006860 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006861 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6862 if (!MT.isNull())
6863 return MT;
6864 }
6865 }
6866 }
6867
6868 return QualType();
6869}
6870
Alp Toker9cacbab2014-01-20 20:26:09 +00006871/// mergeFunctionParameterTypes - merge two types which appear as function
6872/// parameter types
6873QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
6874 bool OfBlockPointer,
6875 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00006876 // GNU extension: two types are compatible if they appear as a function
6877 // argument, one of the types is a transparent union type and the other
6878 // type is compatible with a union member
6879 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6880 Unqualified);
6881 if (!lmerge.isNull())
6882 return lmerge;
6883
6884 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6885 Unqualified);
6886 if (!rmerge.isNull())
6887 return rmerge;
6888
6889 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6890}
6891
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006892QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006893 bool OfBlockPointer,
6894 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00006895 const FunctionType *lbase = lhs->getAs<FunctionType>();
6896 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006897 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6898 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00006899 bool allLTypes = true;
6900 bool allRTypes = true;
6901
6902 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006903 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00006904 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00006905 QualType RHS = rbase->getReturnType();
6906 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00006907 bool UnqualifiedResult = Unqualified;
6908 if (!UnqualifiedResult)
6909 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006910 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00006911 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006912 else
Alp Toker314cc812014-01-25 16:55:45 +00006913 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00006914 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006915 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006916
6917 if (Unqualified)
6918 retType = retType.getUnqualifiedType();
6919
Alp Toker314cc812014-01-25 16:55:45 +00006920 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
6921 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006922 if (Unqualified) {
6923 LRetType = LRetType.getUnqualifiedType();
6924 RRetType = RRetType.getUnqualifiedType();
6925 }
6926
6927 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006928 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006929 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00006930 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00006931
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00006932 // FIXME: double check this
6933 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6934 // rbase->getRegParmAttr() != 0 &&
6935 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00006936 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6937 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00006938
Douglas Gregor8c940862010-01-18 17:14:39 +00006939 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00006940 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Douglas Gregor8c940862010-01-18 17:14:39 +00006941 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006942
John McCall8c6b56f2010-12-15 01:06:38 +00006943 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00006944 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6945 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00006946 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6947 return QualType();
6948
John McCall31168b02011-06-15 23:02:42 +00006949 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6950 return QualType();
6951
John McCall8c6b56f2010-12-15 01:06:38 +00006952 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6953 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00006954
Rafael Espindola8778c282012-11-29 16:09:03 +00006955 if (lbaseInfo.getNoReturn() != NoReturn)
6956 allLTypes = false;
6957 if (rbaseInfo.getNoReturn() != NoReturn)
6958 allRTypes = false;
6959
John McCall31168b02011-06-15 23:02:42 +00006960 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00006961
Eli Friedman47f77112008-08-22 00:56:42 +00006962 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00006963 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6964 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00006965 // Compatible functions must have the same number of parameters
6966 if (lproto->getNumParams() != rproto->getNumParams())
Eli Friedman47f77112008-08-22 00:56:42 +00006967 return QualType();
6968
6969 // Variadic and non-variadic functions aren't compatible
6970 if (lproto->isVariadic() != rproto->isVariadic())
6971 return QualType();
6972
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00006973 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6974 return QualType();
6975
Fariborz Jahanian97676972011-09-28 21:52:05 +00006976 if (LangOpts.ObjCAutoRefCount &&
6977 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6978 return QualType();
Alp Toker601b22c2014-01-21 23:35:24 +00006979
6980 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006981 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00006982 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
6983 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
6984 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
6985 QualType paramType = mergeFunctionParameterTypes(
6986 lParamType, rParamType, OfBlockPointer, Unqualified);
6987 if (paramType.isNull())
6988 return QualType();
6989
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006990 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00006991 paramType = paramType.getUnqualifiedType();
6992
6993 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006994 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00006995 lParamType = lParamType.getUnqualifiedType();
6996 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006997 }
Alp Toker601b22c2014-01-21 23:35:24 +00006998
6999 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007000 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00007001 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007002 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00007003 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00007004
Eli Friedman47f77112008-08-22 00:56:42 +00007005 if (allLTypes) return lhs;
7006 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007007
7008 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7009 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00007010 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007011 }
7012
7013 if (lproto) allRTypes = false;
7014 if (rproto) allLTypes = false;
7015
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007016 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00007017 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007018 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00007019 if (proto->isVariadic()) return QualType();
7020 // Check that the types are compatible with the types that
7021 // would result from default argument promotions (C99 6.7.5.3p15).
7022 // The only types actually affected are promotable integer
7023 // types and floats, which would be passed as a different
7024 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00007025 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
7026 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00007027
Eli Friedman448ce402012-08-30 00:44:15 +00007028 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00007029 // to pass enum values.
Alp Toker601b22c2014-01-21 23:35:24 +00007030 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
7031 paramTy = Enum->getDecl()->getIntegerType();
7032 if (paramTy.isNull())
Eli Friedman448ce402012-08-30 00:44:15 +00007033 return QualType();
7034 }
Alp Toker601b22c2014-01-21 23:35:24 +00007035
7036 if (paramTy->isPromotableIntegerType() ||
7037 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eli Friedman47f77112008-08-22 00:56:42 +00007038 return QualType();
7039 }
7040
7041 if (allLTypes) return lhs;
7042 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007043
7044 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7045 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00007046 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007047 }
7048
7049 if (allLTypes) return lhs;
7050 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00007051 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00007052}
7053
John McCall433c2e62013-03-21 00:10:07 +00007054/// Given that we have an enum type and a non-enum type, try to merge them.
7055static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7056 QualType other, bool isBlockReturnType) {
7057 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7058 // a signed integer type, or an unsigned integer type.
7059 // Compatibility is based on the underlying type, not the promotion
7060 // type.
7061 QualType underlyingType = ET->getDecl()->getIntegerType();
7062 if (underlyingType.isNull()) return QualType();
7063 if (Context.hasSameType(underlyingType, other))
7064 return other;
7065
7066 // In block return types, we're more permissive and accept any
7067 // integral type of the same size.
7068 if (isBlockReturnType && other->isIntegerType() &&
7069 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7070 return other;
7071
7072 return QualType();
7073}
7074
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007075QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007076 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007077 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00007078 // C++ [expr]: If an expression initially has the type "reference to T", the
7079 // type is adjusted to "T" prior to any further analysis, the expression
7080 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007081 // expression is an lvalue unless the reference is an rvalue reference and
7082 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00007083 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7084 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007085
7086 if (Unqualified) {
7087 LHS = LHS.getUnqualifiedType();
7088 RHS = RHS.getUnqualifiedType();
7089 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00007090
Eli Friedman47f77112008-08-22 00:56:42 +00007091 QualType LHSCan = getCanonicalType(LHS),
7092 RHSCan = getCanonicalType(RHS);
7093
7094 // If two types are identical, they are compatible.
7095 if (LHSCan == RHSCan)
7096 return LHS;
7097
John McCall8ccfcb52009-09-24 19:53:00 +00007098 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007099 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7100 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00007101 if (LQuals != RQuals) {
7102 // If any of these qualifiers are different, we have a type
7103 // mismatch.
7104 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00007105 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7106 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00007107 return QualType();
7108
7109 // Exactly one GC qualifier difference is allowed: __strong is
7110 // okay if the other type has no GC qualifier but is an Objective
7111 // C object pointer (i.e. implicitly strong by default). We fix
7112 // this by pretending that the unqualified type was actually
7113 // qualified __strong.
7114 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7115 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7116 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7117
7118 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7119 return QualType();
7120
7121 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7122 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7123 }
7124 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7125 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7126 }
Eli Friedman47f77112008-08-22 00:56:42 +00007127 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00007128 }
7129
7130 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00007131
Eli Friedmandcca6332009-06-01 01:22:52 +00007132 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7133 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00007134
Chris Lattnerfd652912008-01-14 05:45:46 +00007135 // We want to consider the two function types to be the same for these
7136 // comparisons, just force one to the other.
7137 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7138 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00007139
7140 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00007141 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7142 LHSClass = Type::ConstantArray;
7143 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7144 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00007145
John McCall8b07ec22010-05-15 11:32:37 +00007146 // ObjCInterfaces are just specialized ObjCObjects.
7147 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7148 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7149
Nate Begemance4d7fc2008-04-18 23:10:10 +00007150 // Canonicalize ExtVector -> Vector.
7151 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7152 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00007153
Chris Lattner95554662008-04-07 05:43:21 +00007154 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007155 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00007156 // Note that we only have special rules for turning block enum
7157 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00007158 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007159 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007160 }
John McCall9dd450b2009-09-21 23:43:11 +00007161 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00007162 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00007163 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007164 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00007165 if (OfBlockPointer && !BlockReturnType) {
7166 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7167 return LHS;
7168 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7169 return RHS;
7170 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00007171
Eli Friedman47f77112008-08-22 00:56:42 +00007172 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00007173 }
Eli Friedman47f77112008-08-22 00:56:42 +00007174
Steve Naroffc6edcbd2008-01-09 22:43:08 +00007175 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00007176 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007177#define TYPE(Class, Base)
7178#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00007179#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007180#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7181#define DEPENDENT_TYPE(Class, Base) case Type::Class:
7182#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00007183 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007184
Richard Smith27d807c2013-04-30 13:56:41 +00007185 case Type::Auto:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007186 case Type::LValueReference:
7187 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007188 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00007189 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007190
John McCall8b07ec22010-05-15 11:32:37 +00007191 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007192 case Type::IncompleteArray:
7193 case Type::VariableArray:
7194 case Type::FunctionProto:
7195 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00007196 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007197
Chris Lattnerfd652912008-01-14 05:45:46 +00007198 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00007199 {
7200 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007201 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7202 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007203 if (Unqualified) {
7204 LHSPointee = LHSPointee.getUnqualifiedType();
7205 RHSPointee = RHSPointee.getUnqualifiedType();
7206 }
7207 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7208 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007209 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00007210 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007211 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00007212 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00007213 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007214 return getPointerType(ResultType);
7215 }
Steve Naroff68e167d2008-12-10 17:49:55 +00007216 case Type::BlockPointer:
7217 {
7218 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007219 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7220 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007221 if (Unqualified) {
7222 LHSPointee = LHSPointee.getUnqualifiedType();
7223 RHSPointee = RHSPointee.getUnqualifiedType();
7224 }
7225 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7226 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00007227 if (ResultType.isNull()) return QualType();
7228 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7229 return LHS;
7230 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7231 return RHS;
7232 return getBlockPointerType(ResultType);
7233 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00007234 case Type::Atomic:
7235 {
7236 // Merge two pointer types, while trying to preserve typedef info
7237 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7238 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7239 if (Unqualified) {
7240 LHSValue = LHSValue.getUnqualifiedType();
7241 RHSValue = RHSValue.getUnqualifiedType();
7242 }
7243 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7244 Unqualified);
7245 if (ResultType.isNull()) return QualType();
7246 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7247 return LHS;
7248 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7249 return RHS;
7250 return getAtomicType(ResultType);
7251 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007252 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00007253 {
7254 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7255 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7256 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7257 return QualType();
7258
7259 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7260 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007261 if (Unqualified) {
7262 LHSElem = LHSElem.getUnqualifiedType();
7263 RHSElem = RHSElem.getUnqualifiedType();
7264 }
7265
7266 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007267 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00007268 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7269 return LHS;
7270 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7271 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00007272 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7273 ArrayType::ArraySizeModifier(), 0);
7274 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7275 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007276 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7277 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00007278 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7279 return LHS;
7280 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7281 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00007282 if (LVAT) {
7283 // FIXME: This isn't correct! But tricky to implement because
7284 // the array's size has to be the size of LHS, but the type
7285 // has to be different.
7286 return LHS;
7287 }
7288 if (RVAT) {
7289 // FIXME: This isn't correct! But tricky to implement because
7290 // the array's size has to be the size of RHS, but the type
7291 // has to be different.
7292 return RHS;
7293 }
Eli Friedman3e62c212008-08-22 01:48:21 +00007294 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7295 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00007296 return getIncompleteArrayType(ResultType,
7297 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00007298 }
Chris Lattnerfd652912008-01-14 05:45:46 +00007299 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007300 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007301 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007302 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00007303 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00007304 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007305 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00007306 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00007307 case Type::Complex:
7308 // Distinct complex types are incompatible.
7309 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00007310 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00007311 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00007312 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7313 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00007314 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00007315 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00007316 case Type::ObjCObject: {
7317 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00007318 // FIXME: This should be type compatibility, e.g. whether
7319 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00007320 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7321 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7322 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00007323 return LHS;
7324
Eli Friedman47f77112008-08-22 00:56:42 +00007325 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00007326 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00007327 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007328 if (OfBlockPointer) {
7329 if (canAssignObjCInterfacesInBlockPointer(
7330 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007331 RHS->getAs<ObjCObjectPointerType>(),
7332 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00007333 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007334 return QualType();
7335 }
John McCall9dd450b2009-09-21 23:43:11 +00007336 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7337 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00007338 return LHS;
7339
Steve Naroffc68cfcf2008-12-10 22:14:21 +00007340 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00007341 }
Steve Naroff32e44c02007-10-15 20:41:53 +00007342 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007343
David Blaikie8a40f702012-01-17 06:56:22 +00007344 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00007345}
Ted Kremenekfc581a92007-10-31 17:10:13 +00007346
Fariborz Jahanian97676972011-09-28 21:52:05 +00007347bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7348 const FunctionProtoType *FromFunctionType,
7349 const FunctionProtoType *ToFunctionType) {
Alp Toker9cacbab2014-01-20 20:26:09 +00007350 if (FromFunctionType->hasAnyConsumedParams() !=
7351 ToFunctionType->hasAnyConsumedParams())
Fariborz Jahanian97676972011-09-28 21:52:05 +00007352 return false;
7353 FunctionProtoType::ExtProtoInfo FromEPI =
7354 FromFunctionType->getExtProtoInfo();
7355 FunctionProtoType::ExtProtoInfo ToEPI =
7356 ToFunctionType->getExtProtoInfo();
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007357 if (FromEPI.ConsumedParameters && ToEPI.ConsumedParameters)
Alp Toker601b22c2014-01-21 23:35:24 +00007358 for (unsigned i = 0, n = FromFunctionType->getNumParams(); i != n; ++i) {
7359 if (FromEPI.ConsumedParameters[i] != ToEPI.ConsumedParameters[i])
Fariborz Jahanian97676972011-09-28 21:52:05 +00007360 return false;
7361 }
7362 return true;
7363}
7364
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007365/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7366/// 'RHS' attributes and returns the merged version; including for function
7367/// return types.
7368QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7369 QualType LHSCan = getCanonicalType(LHS),
7370 RHSCan = getCanonicalType(RHS);
7371 // If two types are identical, they are compatible.
7372 if (LHSCan == RHSCan)
7373 return LHS;
7374 if (RHSCan->isFunctionType()) {
7375 if (!LHSCan->isFunctionType())
7376 return QualType();
Alp Toker314cc812014-01-25 16:55:45 +00007377 QualType OldReturnType =
7378 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007379 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00007380 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007381 QualType ResReturnType =
7382 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7383 if (ResReturnType.isNull())
7384 return QualType();
7385 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7386 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7387 // In either case, use OldReturnType to build the new function type.
7388 const FunctionType *F = LHS->getAs<FunctionType>();
7389 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00007390 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7391 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00007392 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00007393 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00007394 return ResultType;
7395 }
7396 }
7397 return QualType();
7398 }
7399
7400 // If the qualifiers are different, the types can still be merged.
7401 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7402 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7403 if (LQuals != RQuals) {
7404 // If any of these qualifiers are different, we have a type mismatch.
7405 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7406 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7407 return QualType();
7408
7409 // Exactly one GC qualifier difference is allowed: __strong is
7410 // okay if the other type has no GC qualifier but is an Objective
7411 // C object pointer (i.e. implicitly strong by default). We fix
7412 // this by pretending that the unqualified type was actually
7413 // qualified __strong.
7414 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7415 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7416 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7417
7418 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7419 return QualType();
7420
7421 if (GC_L == Qualifiers::Strong)
7422 return LHS;
7423 if (GC_R == Qualifiers::Strong)
7424 return RHS;
7425 return QualType();
7426 }
7427
7428 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7429 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7430 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7431 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7432 if (ResQT == LHSBaseQT)
7433 return LHS;
7434 if (ResQT == RHSBaseQT)
7435 return RHS;
7436 }
7437 return QualType();
7438}
7439
Chris Lattner4ba0cef2008-04-07 07:01:58 +00007440//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007441// Integer Predicates
7442//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00007443
Jay Foad39c79802011-01-12 09:06:06 +00007444unsigned ASTContext::getIntWidth(QualType T) const {
Richard Smithe9521062013-10-15 04:56:17 +00007445 if (const EnumType *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00007446 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00007447 if (T->isBooleanType())
7448 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00007449 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007450 return (unsigned)getTypeSize(T);
7451}
7452
Abramo Bagnara13640492012-09-09 10:21:24 +00007453QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007454 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00007455
7456 // Turn <4 x signed int> -> <4 x unsigned int>
7457 if (const VectorType *VTy = T->getAs<VectorType>())
7458 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00007459 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00007460
7461 // For enums, we return the unsigned version of the base type.
7462 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007463 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00007464
7465 const BuiltinType *BTy = T->getAs<BuiltinType>();
7466 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007467 switch (BTy->getKind()) {
7468 case BuiltinType::Char_S:
7469 case BuiltinType::SChar:
7470 return UnsignedCharTy;
7471 case BuiltinType::Short:
7472 return UnsignedShortTy;
7473 case BuiltinType::Int:
7474 return UnsignedIntTy;
7475 case BuiltinType::Long:
7476 return UnsignedLongTy;
7477 case BuiltinType::LongLong:
7478 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00007479 case BuiltinType::Int128:
7480 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007481 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007482 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00007483 }
7484}
7485
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00007486ASTMutationListener::~ASTMutationListener() { }
7487
Richard Smith1fa5d642013-05-11 05:45:24 +00007488void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7489 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00007490
7491//===----------------------------------------------------------------------===//
7492// Builtin Type Computation
7493//===----------------------------------------------------------------------===//
7494
7495/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00007496/// pointer over the consumed characters. This returns the resultant type. If
7497/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7498/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7499/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007500///
7501/// RequiresICE is filled in on return to indicate whether the value is required
7502/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00007503static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00007504 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007505 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00007506 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00007507 // Modifiers.
7508 int HowLong = 0;
7509 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007510 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00007511
Chris Lattnerdc226c22010-10-01 22:42:38 +00007512 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00007513 bool Done = false;
7514 while (!Done) {
7515 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00007516 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00007517 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007518 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00007519 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007520 case 'S':
7521 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7522 assert(!Signed && "Can't use 'S' modifier multiple times!");
7523 Signed = true;
7524 break;
7525 case 'U':
7526 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7527 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7528 Unsigned = true;
7529 break;
7530 case 'L':
7531 assert(HowLong <= 2 && "Can't have LLLL modifier");
7532 ++HowLong;
7533 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00007534 case 'W':
7535 // This modifier represents int64 type.
7536 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
7537 switch (Context.getTargetInfo().getInt64Type()) {
7538 default:
7539 llvm_unreachable("Unexpected integer type");
7540 case TargetInfo::SignedLong:
7541 HowLong = 1;
7542 break;
7543 case TargetInfo::SignedLongLong:
7544 HowLong = 2;
7545 break;
7546 }
Chris Lattnerecd79c62009-06-14 00:45:47 +00007547 }
7548 }
7549
7550 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00007551
Chris Lattnerecd79c62009-06-14 00:45:47 +00007552 // Read the base type.
7553 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00007554 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007555 case 'v':
7556 assert(HowLong == 0 && !Signed && !Unsigned &&
7557 "Bad modifiers used with 'v'!");
7558 Type = Context.VoidTy;
7559 break;
Jack Carter24bef982013-08-15 15:16:57 +00007560 case 'h':
7561 assert(HowLong == 0 && !Signed && !Unsigned &&
7562 "Bad modifiers used with 'f'!");
7563 Type = Context.HalfTy;
7564 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007565 case 'f':
7566 assert(HowLong == 0 && !Signed && !Unsigned &&
7567 "Bad modifiers used with 'f'!");
7568 Type = Context.FloatTy;
7569 break;
7570 case 'd':
7571 assert(HowLong < 2 && !Signed && !Unsigned &&
7572 "Bad modifiers used with 'd'!");
7573 if (HowLong)
7574 Type = Context.LongDoubleTy;
7575 else
7576 Type = Context.DoubleTy;
7577 break;
7578 case 's':
7579 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7580 if (Unsigned)
7581 Type = Context.UnsignedShortTy;
7582 else
7583 Type = Context.ShortTy;
7584 break;
7585 case 'i':
7586 if (HowLong == 3)
7587 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7588 else if (HowLong == 2)
7589 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7590 else if (HowLong == 1)
7591 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7592 else
7593 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7594 break;
7595 case 'c':
7596 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7597 if (Signed)
7598 Type = Context.SignedCharTy;
7599 else if (Unsigned)
7600 Type = Context.UnsignedCharTy;
7601 else
7602 Type = Context.CharTy;
7603 break;
7604 case 'b': // boolean
7605 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7606 Type = Context.BoolTy;
7607 break;
7608 case 'z': // size_t.
7609 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7610 Type = Context.getSizeType();
7611 break;
7612 case 'F':
7613 Type = Context.getCFConstantStringType();
7614 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00007615 case 'G':
7616 Type = Context.getObjCIdType();
7617 break;
7618 case 'H':
7619 Type = Context.getObjCSelType();
7620 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00007621 case 'M':
7622 Type = Context.getObjCSuperType();
7623 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007624 case 'a':
7625 Type = Context.getBuiltinVaListType();
7626 assert(!Type.isNull() && "builtin va list type not initialized!");
7627 break;
7628 case 'A':
7629 // This is a "reference" to a va_list; however, what exactly
7630 // this means depends on how va_list is defined. There are two
7631 // different kinds of va_list: ones passed by value, and ones
7632 // passed by reference. An example of a by-value va_list is
7633 // x86, where va_list is a char*. An example of by-ref va_list
7634 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7635 // we want this argument to be a char*&; for x86-64, we want
7636 // it to be a __va_list_tag*.
7637 Type = Context.getBuiltinVaListType();
7638 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007639 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00007640 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007641 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00007642 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007643 break;
7644 case 'V': {
7645 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007646 unsigned NumElements = strtoul(Str, &End, 10);
7647 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00007648 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00007649
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007650 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7651 RequiresICE, false);
7652 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00007653
7654 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00007655 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00007656 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007657 break;
7658 }
Douglas Gregorfed66992012-06-07 18:08:25 +00007659 case 'E': {
7660 char *End;
7661
7662 unsigned NumElements = strtoul(Str, &End, 10);
7663 assert(End != Str && "Missing vector size");
7664
7665 Str = End;
7666
7667 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7668 false);
7669 Type = Context.getExtVectorType(ElementType, NumElements);
7670 break;
7671 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007672 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007673 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7674 false);
7675 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00007676 Type = Context.getComplexType(ElementType);
7677 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00007678 }
7679 case 'Y' : {
7680 Type = Context.getPointerDiffType();
7681 break;
7682 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00007683 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00007684 Type = Context.getFILEType();
7685 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007686 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007687 return QualType();
7688 }
Mike Stump2adb4da2009-07-28 23:47:15 +00007689 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00007690 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00007691 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00007692 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00007693 else
7694 Type = Context.getjmp_bufType();
7695
Mike Stump2adb4da2009-07-28 23:47:15 +00007696 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00007697 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00007698 return QualType();
7699 }
7700 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00007701 case 'K':
7702 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7703 Type = Context.getucontext_tType();
7704
7705 if (Type.isNull()) {
7706 Error = ASTContext::GE_Missing_ucontext;
7707 return QualType();
7708 }
7709 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00007710 case 'p':
7711 Type = Context.getProcessIDType();
7712 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00007713 }
Mike Stump11289f42009-09-09 15:08:12 +00007714
Chris Lattnerdc226c22010-10-01 22:42:38 +00007715 // If there are modifiers and if we're allowed to parse them, go for it.
7716 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007717 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00007718 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007719 default: Done = true; --Str; break;
7720 case '*':
7721 case '&': {
7722 // Both pointers and references can have their pointee types
7723 // qualified with an address space.
7724 char *End;
7725 unsigned AddrSpace = strtoul(Str, &End, 10);
7726 if (End != Str && AddrSpace != 0) {
7727 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7728 Str = End;
7729 }
7730 if (c == '*')
7731 Type = Context.getPointerType(Type);
7732 else
7733 Type = Context.getLValueReferenceType(Type);
7734 break;
7735 }
7736 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7737 case 'C':
7738 Type = Type.withConst();
7739 break;
7740 case 'D':
7741 Type = Context.getVolatileType(Type);
7742 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00007743 case 'R':
7744 Type = Type.withRestrict();
7745 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007746 }
7747 }
Chris Lattner84733392010-10-01 07:13:18 +00007748
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007749 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00007750 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00007751
Chris Lattnerecd79c62009-06-14 00:45:47 +00007752 return Type;
7753}
7754
7755/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00007756QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007757 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00007758 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00007759 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00007760
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007761 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00007762
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007763 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00007764 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007765 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7766 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007767 if (Error != GE_None)
7768 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007769
7770 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7771
Chris Lattnerecd79c62009-06-14 00:45:47 +00007772 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007773 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007774 if (Error != GE_None)
7775 return QualType();
7776
Chris Lattnerbd6e6932010-10-01 22:53:11 +00007777 // If this argument is required to be an IntegerConstantExpression and the
7778 // caller cares, fill in the bitmask we return.
7779 if (RequiresICE && IntegerConstantArgs)
7780 *IntegerConstantArgs |= 1 << ArgTypes.size();
7781
Chris Lattnerecd79c62009-06-14 00:45:47 +00007782 // Do array -> pointer decay. The builtin should use the decayed type.
7783 if (Ty->isArrayType())
7784 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00007785
Chris Lattnerecd79c62009-06-14 00:45:47 +00007786 ArgTypes.push_back(Ty);
7787 }
7788
7789 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7790 "'.' should only occur at end of builtin type list!");
7791
Reid Kleckner78af0702013-08-27 23:08:25 +00007792 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00007793 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7794
7795 bool Variadic = (TypeStr[0] == '.');
7796
7797 // We really shouldn't be making a no-proto type here, especially in C++.
7798 if (ArgTypes.empty() && Variadic)
7799 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00007800
John McCalldb40c7f2010-12-14 08:05:40 +00007801 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00007802 EPI.ExtInfo = EI;
7803 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00007804
Jordan Rose5c382722013-03-08 21:51:21 +00007805 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00007806}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00007807
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007808GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007809 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007810 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007811
Rafael Espindola3ae00052013-05-13 00:12:11 +00007812 GVALinkage External = GVA_StrongExternal;
7813 switch (FD->getTemplateSpecializationKind()) {
7814 case TSK_Undeclared:
7815 case TSK_ExplicitSpecialization:
7816 External = GVA_StrongExternal;
7817 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007818
Rafael Espindola3ae00052013-05-13 00:12:11 +00007819 case TSK_ExplicitInstantiationDefinition:
7820 return GVA_ExplicitTemplateInstantiation;
7821
7822 case TSK_ExplicitInstantiationDeclaration:
7823 case TSK_ImplicitInstantiation:
7824 External = GVA_TemplateInstantiation;
7825 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007826 }
7827
7828 if (!FD->isInlined())
7829 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00007830
Alp Tokerbfa39342014-01-14 12:51:41 +00007831 if ((!getLangOpts().CPlusPlus && !getLangOpts().MSVCCompat) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00007832 FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007833 // GNU or C99 inline semantics. Determine whether this symbol should be
7834 // externally visible.
7835 if (FD->isInlineDefinitionExternallyVisible())
7836 return External;
7837
7838 // C99 inline semantics, where the symbol is not externally visible.
7839 return GVA_C99Inline;
7840 }
7841
7842 // C++0x [temp.explicit]p9:
7843 // [ Note: The intent is that an inline function that is the subject of
7844 // an explicit instantiation declaration will still be implicitly
7845 // instantiated when used so that the body can be considered for
7846 // inlining, but that no out-of-line copy of the inline function would be
7847 // generated in the translation unit. -- end note ]
7848 if (FD->getTemplateSpecializationKind()
7849 == TSK_ExplicitInstantiationDeclaration)
7850 return GVA_C99Inline;
7851
7852 return GVA_CXXInline;
7853}
7854
7855GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007856 if (!VD->isExternallyVisible())
7857 return GVA_Internal;
7858
Richard Smith8809a0c2013-09-27 20:14:12 +00007859 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00007860 case TSK_Undeclared:
7861 case TSK_ExplicitSpecialization:
7862 return GVA_StrongExternal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007863
Rafael Espindola3ae00052013-05-13 00:12:11 +00007864 case TSK_ExplicitInstantiationDeclaration:
7865 llvm_unreachable("Variable should not be instantiated");
7866 // Fall through to treat this like any other instantiation.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007867
Rafael Espindola3ae00052013-05-13 00:12:11 +00007868 case TSK_ExplicitInstantiationDefinition:
7869 return GVA_ExplicitTemplateInstantiation;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007870
Rafael Espindola3ae00052013-05-13 00:12:11 +00007871 case TSK_ImplicitInstantiation:
7872 return GVA_TemplateInstantiation;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007873 }
Rafael Espindola27699c82013-05-13 14:05:53 +00007874
7875 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007876}
7877
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00007878bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007879 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7880 if (!VD->isFileVarDecl())
7881 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00007882 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7883 // We never need to emit an uninstantiated function template.
7884 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
7885 return false;
7886 } else
7887 return false;
7888
7889 // If this is a member of a class template, we do not need to emit it.
7890 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007891 return false;
7892
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007893 // Weak references don't produce any output by themselves.
7894 if (D->hasAttr<WeakRefAttr>())
7895 return false;
7896
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007897 // Aliases and used decls are required.
7898 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7899 return true;
7900
7901 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7902 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00007903 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00007904 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007905
7906 // Constructors and destructors are required.
7907 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7908 return true;
7909
John McCall6bd2a892013-01-25 22:31:03 +00007910 // The key function for a class is required. This rule only comes
7911 // into play when inline functions can be key functions, though.
7912 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7913 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7914 const CXXRecordDecl *RD = MD->getParent();
7915 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7916 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
7917 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7918 return true;
7919 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007920 }
7921 }
7922
7923 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7924
7925 // static, static inline, always_inline, and extern inline functions can
7926 // always be deferred. Normal inline functions can be deferred in C99/C++.
7927 // Implicit template instantiations can also be deferred in C++.
7928 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev79de4d42012-02-02 06:06:34 +00007929 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007930 return false;
7931 return true;
7932 }
Douglas Gregor87d81242011-09-10 00:22:34 +00007933
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007934 const VarDecl *VD = cast<VarDecl>(D);
7935 assert(VD->isFileVarDecl() && "Expected file scoped var");
7936
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00007937 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7938 return false;
7939
Richard Smitha0e5e542012-11-12 21:38:00 +00007940 // Variables that can be needed in other TUs are required.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007941 GVALinkage L = GetGVALinkageForVariable(VD);
Richard Smitha0e5e542012-11-12 21:38:00 +00007942 if (L != GVA_Internal && L != GVA_TemplateInstantiation)
7943 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007944
Richard Smitha0e5e542012-11-12 21:38:00 +00007945 // Variables that have destruction with side-effects are required.
7946 if (VD->getType().isDestructedType())
7947 return true;
7948
7949 // Variables that have initialization with side-effects are required.
7950 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
7951 return true;
7952
7953 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00007954}
Charles Davis53c59df2010-08-16 03:33:14 +00007955
Reid Kleckner78af0702013-08-27 23:08:25 +00007956CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
7957 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00007958 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00007959 if (IsCXXMethod)
7960 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00007961
Reid Kleckner78af0702013-08-27 23:08:25 +00007962 return (LangOpts.MRTD && !IsVariadic) ? CC_X86StdCall : CC_C;
Charles Davis99202b32010-11-09 18:04:24 +00007963}
7964
Jay Foad39c79802011-01-12 09:06:06 +00007965bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00007966 // Pass through to the C++ ABI object
7967 return ABI->isNearlyEmpty(RD);
7968}
7969
Reid Kleckner96f8f932014-02-05 17:27:08 +00007970VTableContextBase *ASTContext::getVTableContext() {
7971 if (!VTContext.get()) {
7972 if (Target->getCXXABI().isMicrosoft())
7973 VTContext.reset(new MicrosoftVTableContext(*this));
7974 else
7975 VTContext.reset(new ItaniumVTableContext(*this));
7976 }
7977 return VTContext.get();
7978}
7979
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007980MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00007981 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00007982 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00007983 case TargetCXXABI::GenericItanium:
7984 case TargetCXXABI::GenericARM:
7985 case TargetCXXABI::iOS:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00007986 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00007987 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00007988 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007989 }
David Blaikie83d382b2011-09-23 05:06:16 +00007990 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00007991}
7992
Charles Davis53c59df2010-08-16 03:33:14 +00007993CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00007994
7995size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00007996 return ASTRecordLayouts.getMemorySize() +
7997 llvm::capacity_in_bytes(ObjCLayouts) +
7998 llvm::capacity_in_bytes(KeyFunctions) +
7999 llvm::capacity_in_bytes(ObjCImpls) +
8000 llvm::capacity_in_bytes(BlockVarCopyInits) +
8001 llvm::capacity_in_bytes(DeclAttrs) +
8002 llvm::capacity_in_bytes(TemplateOrInstantiation) +
8003 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
8004 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
8005 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
8006 llvm::capacity_in_bytes(OverriddenMethods) +
8007 llvm::capacity_in_bytes(Types) +
8008 llvm::capacity_in_bytes(VariableArrayTypes) +
8009 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00008010}
Ted Kremenek540017e2011-10-06 05:00:56 +00008011
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00008012/// getIntTypeForBitwidth -
8013/// sets integer QualTy according to specified details:
8014/// bitwidth, signed/unsigned.
8015/// Returns empty type if there is no appropriate target types.
8016QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
8017 unsigned Signed) const {
8018 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
8019 CanQualType QualTy = getFromTargetType(Ty);
8020 if (!QualTy && DestWidth == 128)
8021 return Signed ? Int128Ty : UnsignedInt128Ty;
8022 return QualTy;
8023}
8024
8025/// getRealTypeForBitwidth -
8026/// sets floating point QualTy according to specified bitwidth.
8027/// Returns empty type if there is no appropriate target types.
8028QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
8029 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
8030 switch (Ty) {
8031 case TargetInfo::Float:
8032 return FloatTy;
8033 case TargetInfo::Double:
8034 return DoubleTy;
8035 case TargetInfo::LongDouble:
8036 return LongDoubleTy;
8037 case TargetInfo::NoFloat:
8038 return QualType();
8039 }
8040
8041 llvm_unreachable("Unhandled TargetInfo::RealType value");
8042}
8043
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008044void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
8045 if (Number > 1)
8046 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00008047}
8048
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008049unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
8050 llvm::DenseMap<const NamedDecl *, unsigned>::const_iterator I =
8051 MangleNumbers.find(ND);
8052 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00008053}
8054
Eli Friedman3b7d46c2013-07-10 00:30:46 +00008055MangleNumberingContext &
8056ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00008057 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
8058 MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
8059 if (!MCtx)
8060 MCtx = createMangleNumberingContext();
8061 return *MCtx;
8062}
8063
8064MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
8065 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00008066}
8067
Ted Kremenek540017e2011-10-06 05:00:56 +00008068void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8069 ParamIndices[D] = index;
8070}
8071
8072unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8073 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8074 assert(I != ParamIndices.end() &&
8075 "ParmIndices lacks entry set by ParmVarDecl");
8076 return I->second;
8077}
Fariborz Jahanian615de762013-05-28 17:37:39 +00008078
Richard Smithe6c01442013-06-05 00:46:14 +00008079APValue *
8080ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8081 bool MayCreate) {
8082 assert(E && E->getStorageDuration() == SD_Static &&
8083 "don't need to cache the computed value for this temporary");
8084 if (MayCreate)
8085 return &MaterializedTemporaryValues[E];
8086
8087 llvm::DenseMap<const MaterializeTemporaryExpr *, APValue>::iterator I =
8088 MaterializedTemporaryValues.find(E);
8089 return I == MaterializedTemporaryValues.end() ? 0 : &I->second;
8090}
8091
Fariborz Jahanian615de762013-05-28 17:37:39 +00008092bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8093 const llvm::Triple &T = getTargetInfo().getTriple();
8094 if (!T.isOSDarwin())
8095 return false;
8096
Bob Wilson2c82c3d2013-11-02 23:27:49 +00008097 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
8098 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
8099 return false;
8100
Fariborz Jahanian615de762013-05-28 17:37:39 +00008101 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8102 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8103 uint64_t Size = sizeChars.getQuantity();
8104 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8105 unsigned Align = alignChars.getQuantity();
8106 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8107 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8108}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00008109
8110namespace {
8111
8112 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8113 /// parents as defined by the \c RecursiveASTVisitor.
8114 ///
8115 /// Note that the relationship described here is purely in terms of AST
8116 /// traversal - there are other relationships (for example declaration context)
8117 /// in the AST that are better modeled by special matchers.
8118 ///
8119 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
8120 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
8121
8122 public:
8123 /// \brief Builds and returns the translation unit's parent map.
8124 ///
8125 /// The caller takes ownership of the returned \c ParentMap.
8126 static ASTContext::ParentMap *buildMap(TranslationUnitDecl &TU) {
8127 ParentMapASTVisitor Visitor(new ASTContext::ParentMap);
8128 Visitor.TraverseDecl(&TU);
8129 return Visitor.Parents;
8130 }
8131
8132 private:
8133 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8134
8135 ParentMapASTVisitor(ASTContext::ParentMap *Parents) : Parents(Parents) {
8136 }
8137
8138 bool shouldVisitTemplateInstantiations() const {
8139 return true;
8140 }
8141 bool shouldVisitImplicitCode() const {
8142 return true;
8143 }
8144 // Disables data recursion. We intercept Traverse* methods in the RAV, which
8145 // are not triggered during data recursion.
8146 bool shouldUseDataRecursionFor(clang::Stmt *S) const {
8147 return false;
8148 }
8149
8150 template <typename T>
8151 bool TraverseNode(T *Node, bool(VisitorBase:: *traverse) (T *)) {
8152 if (Node == NULL)
8153 return true;
8154 if (ParentStack.size() > 0)
8155 // FIXME: Currently we add the same parent multiple times, for example
8156 // when we visit all subexpressions of template instantiations; this is
8157 // suboptimal, bug benign: the only way to visit those is with
8158 // hasAncestor / hasParent, and those do not create new matches.
8159 // The plan is to enable DynTypedNode to be storable in a map or hash
8160 // map. The main problem there is to implement hash functions /
8161 // comparison operators for all types that DynTypedNode supports that
8162 // do not have pointer identity.
8163 (*Parents)[Node].push_back(ParentStack.back());
8164 ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node));
8165 bool Result = (this ->* traverse) (Node);
8166 ParentStack.pop_back();
8167 return Result;
8168 }
8169
8170 bool TraverseDecl(Decl *DeclNode) {
8171 return TraverseNode(DeclNode, &VisitorBase::TraverseDecl);
8172 }
8173
8174 bool TraverseStmt(Stmt *StmtNode) {
8175 return TraverseNode(StmtNode, &VisitorBase::TraverseStmt);
8176 }
8177
8178 ASTContext::ParentMap *Parents;
8179 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8180
8181 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8182 };
8183
8184} // end namespace
8185
8186ASTContext::ParentVector
8187ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
8188 assert(Node.getMemoizationData() &&
8189 "Invariant broken: only nodes that support memoization may be "
8190 "used in the parent map.");
8191 if (!AllParents) {
8192 // We always need to run over the whole translation unit, as
8193 // hasAncestor can escape any subtree.
8194 AllParents.reset(
8195 ParentMapASTVisitor::buildMap(*getTranslationUnitDecl()));
8196 }
8197 ParentMap::const_iterator I = AllParents->find(Node.getMemoizationData());
8198 if (I == AllParents->end()) {
8199 return ParentVector();
8200 }
8201 return I->second;
8202}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008203
8204bool
8205ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
8206 const ObjCMethodDecl *MethodImpl) {
8207 // No point trying to match an unavailable/deprecated mothod.
8208 if (MethodDecl->hasAttr<UnavailableAttr>()
8209 || MethodDecl->hasAttr<DeprecatedAttr>())
8210 return false;
8211 if (MethodDecl->getObjCDeclQualifier() !=
8212 MethodImpl->getObjCDeclQualifier())
8213 return false;
Alp Toker314cc812014-01-25 16:55:45 +00008214 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00008215 return false;
8216
8217 if (MethodDecl->param_size() != MethodImpl->param_size())
8218 return false;
8219
8220 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
8221 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
8222 EF = MethodDecl->param_end();
8223 IM != EM && IF != EF; ++IM, ++IF) {
8224 const ParmVarDecl *DeclVar = (*IF);
8225 const ParmVarDecl *ImplVar = (*IM);
8226 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
8227 return false;
8228 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
8229 return false;
8230 }
8231 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
8232
8233}